1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
|
/*
* This file is a part of RSPlayer
* Licensed under the GPL-3.0 License
* Copyright (C) 2026 Salmonik @ salmonik@tuta.io
* https://codeberg.org/salmonik/RSPlayer
*/
use crate::config::Config;
use crate::database::Database;
use clap::{Command, CommandFactory, Parser, Subcommand};
use clap_complete::{Shell, generate};
use std::path::PathBuf;
use std::time::Duration;
#[derive(Parser)]
#[command(name = "rsp", infer_long_args = true)]
#[command(about = "Rust music player daemon", long_about = None)]
pub struct Cli {
#[command(subcommand)]
pub command: Commands,
}
#[derive(Subcommand)]
pub enum Commands {
/// Start the daemon
StartDaemon,
/// Stop the daemon
StopDaemon,
/// Restart the daemon (kill existing and start new)
Restart,
/// Play a track, album, or artist
Play {
/// Add after current track and skip to it
#[arg(short = 'i', long = "now")]
now: bool,
/// Add to queue after current track (don't skip)
#[arg(short = 'n', long = "next")]
next: bool,
/// Queue the entire album containing this track (start at this track)
#[arg(short = 'a', long = "album")]
album: bool,
#[arg(value_name = "QUERY")]
query: Option<String>,
},
/// Pause playback
Pause,
/// Resume playback
Resume,
/// Toggle play/pause
Toggle,
/// Stop playback
Stop,
/// Skip to next track
Next,
/// Skip to previous track
Previous,
/// Set volume (0-100)
Volume {
#[arg(value_name = "LEVEL")]
level: Option<u8>,
},
/// Shuffle mode
Shuffle {
#[arg(value_name = "MODE")]
mode: Option<String>,
},
/// Queue management
Queue {
#[arg(value_name = "POSITION")]
position: Option<String>,
#[arg(value_name = "QUERY")]
query: Option<String>,
},
/// Show player status
Status,
/// Scan music paths to populate database
Scan {
#[arg(long)]
force: bool,
#[arg(long, value_name = "PATHS")]
paths: Option<Vec<PathBuf>>,
},
/// Settings management
Settings {
#[command(subcommand)]
command: SettingsCommands,
},
#[clap(hide = true)]
/// Generate shell completions (developer only)
Completions {
/// Shell to generate (bash, zsh, fish, elvish, powershell)
/// If not specified, generates all completion files
#[arg(value_name = "SHELL")]
shell: Option<String>,
},
#[clap(hide = true)]
/// Complete artists, albums, or tracks from database
DbComplete {
/// Query string (e.g. \"J\", \"Artist/\", \"Artist/Album/\")
#[arg(value_name = "QUERY")]
query: String,
},
/// display lyrics
Lyrics,
}
#[derive(Subcommand)]
pub enum SettingsCommands {
/// Get a setting value
Get {
#[arg(value_name = "KEY")]
key: String,
},
/// Set a setting value
Set {
#[arg(value_name = "KEY")]
key: String,
#[arg(value_name = "VALUE")]
value: String,
},
/// List all settings
List,
/// Unset a setting
Unset {
#[arg(value_name = "KEY")]
key: String,
},
/// Reload config from disk (re-reads config file, re-validates scrobbling tokens)
Reload,
}
impl Cli {
pub fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
match &self.command {
Commands::StartDaemon => {
crate::daemon::start_daemon()?;
}
Commands::StopDaemon => {
crate::daemon::stop_daemon()?;
}
Commands::Restart => {
crate::daemon::restart_daemon()?;
}
Commands::Play {
now,
next,
album,
query,
..
} => {
if let Some(q) = query {
let pos = if *now {
"now"
} else if *next {
"next"
} else {
"last"
};
if *album {
crate::daemon::send_command(format!("play-album {} {}", pos, q))?;
} else {
crate::daemon::send_command(format!("play {} {}", pos, q))?;
}
} else {
crate::daemon::send_command("play last".to_string())?;
}
}
Commands::Pause => {
crate::daemon::send_command("pause".to_string())?;
}
Commands::Resume => {
crate::daemon::send_command("resume".to_string())?;
}
Commands::Toggle => {
crate::daemon::send_command("toggle".to_string())?;
}
Commands::Stop => {
crate::daemon::send_command("stop".to_string())?;
}
Commands::Next => {
crate::daemon::send_command("next".to_string())?;
}
Commands::Previous => {
crate::daemon::send_command("previous".to_string())?;
}
Commands::Volume { level } => {
if let Some(l) = level {
crate::daemon::send_command(format!("volume {}", l))?;
} else {
crate::daemon::send_command("volume".to_string())?;
}
}
Commands::Shuffle { mode } => {
if let Some(m) = mode {
crate::daemon::send_command(format!("shuffle {}", m))?;
} else {
crate::daemon::send_command("shuffle".to_string())?;
}
}
Commands::Queue { position, query } => match (position, query) {
(None, None) => {
crate::daemon::send_command("queue".to_string())?;
}
(pos, Some(q)) => {
let pos = pos.as_deref().unwrap_or("last");
crate::daemon::send_command(format!("queue {} {}", pos, q))?;
}
_ => {}
},
Commands::Status => {
crate::daemon::send_command("status".to_string())?;
}
Commands::Scan { force, paths } => {
let config = Config::load()?;
let db = Database::open(&config)?;
if let Some(custom_paths) = paths {
db.scan_paths(custom_paths, *force)?;
} else {
db.scan_paths(&config.music_paths, *force)?;
}
println!("Scan complete");
}
Commands::Settings { command } => {
let mut config = Config::load()?;
match command {
SettingsCommands::Get { key } => {
println!("{}", config.get(key)?);
}
SettingsCommands::Set { key, value } => {
config.set(key, value)?;
config.save()?;
if key == "listenbrainz_token" {
let _ = crate::daemon::send_command("validate".to_string());
}
}
SettingsCommands::List => {
config.list();
}
SettingsCommands::Unset { key } => {
config.unset(key)?;
config.save()?;
}
SettingsCommands::Reload => {
let _ = crate::daemon::send_command("reload".to_string());
}
}
}
Commands::DbComplete { query } => {
// Unescape shell escapes in the input query
let query = {
let mut unescaped = String::with_capacity(query.len());
let mut chars = query.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
unescaped.push(next);
}
} else {
unescaped.push(c);
}
}
unescaped
};
// Empty query: synchronously query the DB directly (no timeout thread)
// and never fall back to a directory listing, which would be confusing.
if query.is_empty() {
if let Ok(config) = Config::load()
&& let Ok(db) = Database::open(&config)
{
let results = db.complete("").unwrap_or_default();
for r in &results {
println!("{r}");
}
}
return Ok(());
}
// If query looks like a filesystem path, skip DB entirely
if looks_like_path(&query) {
for c in complete_path(&query) {
println!("{c}");
}
return Ok(());
}
// Try DB completion with a timeout; if nothing returned, fall back
// to filesystem path completion (e.g. empty library, no match).
let db_results = db_complete_with_timeout(&query, Duration::from_millis(100));
if let Some(ref results) = db_results
&& !results.is_empty()
{
for r in results {
println!("{r}");
}
return Ok(());
}
// Fallback: filesystem path completion
for c in complete_path(&query) {
println!("{c}");
}
}
Commands::Completions { shell } => {
let full = Cli::command();
let subcommands: Vec<Command> = full
.get_subcommands()
.filter(|s| s.get_name() != "completions" && s.get_name() != "db-complete")
.cloned()
.collect();
let cmd_name = full.get_name().to_string();
let about = full.get_about().cloned();
let mut cmd = Command::new(cmd_name).infer_long_args(true);
if let Some(a) = about {
cmd = cmd.about(a);
}
for sc in subcommands {
cmd = cmd.subcommand(sc);
}
if let Some(s) = shell {
let shell = match s.as_str() {
"bash" => Shell::Bash,
"zsh" => Shell::Zsh,
"fish" => Shell::Fish,
"elvish" => Shell::Elvish,
"powershell" => Shell::PowerShell,
_ => {
eprintln!("Unknown shell: {s}");
return Ok(());
}
};
generate(shell, &mut cmd, "rsp", &mut std::io::stdout());
} else {
std::fs::create_dir_all("completions/")?;
let shells = [
(Shell::Bash, "bash"),
(Shell::Zsh, "zsh"),
(Shell::Fish, "fish"),
(Shell::Elvish, "elvish"),
(Shell::PowerShell, "powershell"),
];
for (shell, ext) in &shells {
let path = format!("completions/rsp.{ext}");
let mut file = std::fs::File::create(&path)?;
generate(*shell, &mut cmd, "rsp", &mut file);
println!("Generated {path}");
}
}
}
Commands::Lyrics => {
let _ = crate::daemon::send_command("lyrics".to_string());
}
}
Ok(())
}
}
/// Returns true if the query looks like a filesystem path.
fn looks_like_path(query: &str) -> bool {
query.starts_with("./")
|| query.starts_with("../")
|| query.starts_with("~/")
|| query.starts_with('/')
}
/// List files/directories matching `query`, formatted as completion candidates.
///
/// Directories get a trailing `/` so the shell knows they can be further expanded.
fn complete_path(query: &str) -> Vec<String> {
if query.is_empty() {
return Vec::new();
}
// Split at the last '/' to separate directory and filename prefix
let (dir_part, file_prefix) = match query.rfind('/') {
Some(pos) => (&query[..=pos], &query[pos + 1..]),
None => ("", query),
};
// Resolve the directory to read. For ~/… we need the expanded path;
// everything else works as-is from the CWD.
let read_dir = if let Some(rest) = dir_part.strip_prefix("~/") {
if let Some(home) = dirs::home_dir() {
if rest.is_empty() {
home
} else {
home.join(rest.trim_end_matches('/'))
}
} else {
PathBuf::from(dir_part)
}
} else if dir_part.is_empty() {
PathBuf::from(".")
} else {
PathBuf::from(dir_part)
};
let mut results: Vec<String> = Vec::new();
if let Ok(entries) = std::fs::read_dir(&read_dir) {
for entry in entries.flatten() {
let name = entry.file_name();
let name_str = name.to_string_lossy().to_string();
// Skip hidden entries unless the query explicitly asks for them
if name_str.starts_with('.') && !file_prefix.starts_with('.') {
continue;
}
if name_str == "." || name_str == ".." {
continue;
}
if !name_str.starts_with(file_prefix) {
continue;
}
let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
if is_dir {
results.push(format!("{dir_part}{name_str}/"));
} else {
results.push(format!("{dir_part}{name_str}"));
}
}
}
results.sort();
results
}
/// Try the DB completion query in a separate thread with a timeout.
///
/// Opens its own database connection so the caller doesn't need to keep one
/// alive. Returns `None` on timeout or when the DB can't be opened.
fn db_complete_with_timeout(query: &str, timeout: Duration) -> Option<Vec<String>> {
let query = query.to_string();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
if let Ok(config) = Config::load()
&& let Ok(db) = Database::open(&config)
{
let results = db.complete(&query).unwrap_or_default();
let _ = tx.send(results);
}
});
rx.recv_timeout(timeout).ok()
}
|