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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
|
/*
* 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::audio::AudioEngine;
use crate::config::Config;
use crate::notification;
use crate::queue::{Queue, ShuffleMode, Track};
use crate::scrobbler::Scrobbler;
use std::io::{Read, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime};
use std::{fs, thread};
pub struct ScrobbleState {
pub track: Option<Track>,
pub start_time: Option<Instant>,
pub timestamp: Option<u64>,
}
impl Default for ScrobbleState {
fn default() -> Self {
Self::new()
}
}
impl ScrobbleState {
pub fn new() -> Self {
ScrobbleState {
track: None,
start_time: None,
timestamp: None,
}
}
pub fn start(&mut self, track: Track) {
if track.is_stream {
crate::debug_eprintln(format_args!(
"scrobble: not tracking stream '{}'",
track.path.display()
));
self.clear();
return;
}
let ts = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let title = track.title.clone().unwrap_or_default();
let artist = track.artist.clone().unwrap_or_default();
crate::debug_eprintln(format_args!(
"scrobble: tracking start for '{} - {}' (ts={})",
artist, title, ts
));
self.track = Some(track);
self.start_time = Some(Instant::now());
self.timestamp = Some(ts);
}
pub fn should_scrobble(&self) -> bool {
let (Some(track), Some(start)) = (&self.track, self.start_time) else {
crate::debug_eprintln(format_args!(
"scrobble: should_scrobble false — no track or start_time"
));
return false;
};
let elapsed = start.elapsed().as_secs();
let result = Self::should_scrobble_with_params(elapsed, track.duration_secs);
let threshold = track
.duration_secs
.map(|d| (d / 2.0) as u64)
.unwrap_or(u64::MAX)
.min(240);
crate::debug_eprintln(format_args!(
"scrobble: should_scrobble {} (elapsed={}s threshold={}s duration={:?})",
result, elapsed, threshold, track.duration_secs
));
result
}
pub fn should_scrobble_with_params(elapsed: u64, duration_secs: Option<f64>) -> bool {
if elapsed < 30 {
return false;
}
let threshold = duration_secs
.map(|d| (d / 2.0) as u64)
.unwrap_or(u64::MAX)
.min(240);
elapsed >= threshold
}
pub fn clear(&mut self) {
self.track = None;
self.start_time = None;
self.timestamp = None;
}
}
pub fn try_scrobble_current(scrobbler: &RwLock<Scrobbler>, state: &mut ScrobbleState) {
if let Some(ref track) = state.track
&& track.is_stream
{
crate::debug_eprintln(format_args!("scrobble: skipping scrobble for stream track"));
state.clear();
return;
}
if state.should_scrobble()
&& let (Some(track), Some(ts)) = (&state.track, state.timestamp)
{
let artist = track.artist.as_deref().unwrap_or("(unknown artist)");
let title = track.title.as_deref().unwrap_or("(unknown title)");
let album = track.album.as_deref();
crate::debug_eprintln(format_args!(
"scrobble: sending scrobble for '{} - {}' at ts={}",
artist, title, ts
));
if let Ok(s) = scrobbler.read() {
s.scrobble(artist, title, album, ts);
}
} else {
let title = state
.track
.as_ref()
.and_then(|t| t.title.as_deref())
.unwrap_or("(no track)");
crate::debug_eprintln(format_args!(
"scrobble: skipping scrobble for '{}' — not enough play time",
title
));
}
state.clear();
}
pub fn send_now_playing(scrobbler: &RwLock<Scrobbler>, track: &Track) {
if track.is_stream {
crate::debug_eprintln(format_args!(
"scrobble: skipping now_playing for stream track"
));
return;
}
let artist = track.artist.as_deref().unwrap_or("(unknown artist)");
let title = track.title.as_deref().unwrap_or("(unknown title)");
let album = track.album.as_deref();
crate::debug_eprintln(format_args!(
"scrobble: sending now_playing for '{} - {}'",
artist, title
));
if let Ok(s) = scrobbler.read() {
s.now_playing(artist, title, album);
}
}
pub fn start_daemon() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?;
let socket_path = Config::get_socket_path();
let pid_path = get_pid_path(&config);
// Check if daemon is already running
if let Ok(pid) = check_running_daemon(&pid_path) {
return Err(format!("Daemon already running with PID {}", pid).into());
}
// Clean up stale socket file if it exists
if socket_path.exists() {
std::fs::remove_file(&socket_path).ok();
}
// Create runtime directory
if let Some(parent) = socket_path.parent() {
std::fs::create_dir_all(parent)?;
}
if let Some(parent) = pid_path.parent() {
std::fs::create_dir_all(parent)?;
}
// Write PID file
let pid = std::process::id();
std::fs::write(&pid_path, pid.to_string())?;
println!("Daemon started with PID {}", pid);
// Shared shutdown flag - can be triggered by signal or command
let shutdown_flag = Arc::new(AtomicBool::new(false));
let shutdown_flag_signal = Arc::clone(&shutdown_flag);
// Handle SIGTERM and SIGINT
ctrlc::set_handler(move || {
println!("Received shutdown signal");
shutdown_flag_signal.store(true, Ordering::SeqCst);
})?;
let listener = UnixListener::bind(&socket_path)?;
println!("Listening on {:?}", socket_path);
let audio_engine = Arc::new(AudioEngine::new());
let queue = Arc::new(Mutex::new(Queue::new()));
// Load and apply saved settings
if let Some(vol) = config.volume {
audio_engine.set_volume(vol as f32 / 100.0);
}
if let Some(ref shuffle_str) = config.shuffle
&& let Ok(mut q) = queue.lock()
{
match shuffle_str.as_str() {
"on" | "all" => q.set_shuffle(ShuffleMode::All),
"album" => q.set_shuffle(ShuffleMode::Album),
"albums" => q.set_shuffle(ShuffleMode::Albums),
_ => {}
}
}
// Create scrobbler from config
let scrobbler = Arc::new(RwLock::new(Scrobbler::new(
config.lastfm_api_key.clone(),
config.lastfm_api_secret.clone(),
config.lastfm_session_key.clone(),
config.listenbrainz_token.clone(),
)));
// Validate ListenBrainz token at startup
if let Some(token) = &config.listenbrainz_token
&& !token.is_empty()
&& let Ok(s) = scrobbler.read()
{
match s.validate_listenbrainz_token() {
Ok(Some(user)) => crate::debug_eprintln(format_args!(
"scrobble: listenbrainz token valid (user: {})",
user
)),
Ok(None) => crate::debug_eprintln(format_args!(
"scrobble: listenbrainz token invalid, scrobbling disabled"
)),
Err(e) => crate::debug_eprintln(format_args!(
"scrobble: listenbrainz validation error: {}",
e
)),
}
}
let scrobble_state = Arc::new(Mutex::new(ScrobbleState::new()));
// Save full config
config.save()?;
// Start MPRIS D-Bus server for external control (playerctl, etc.)
crate::mpris::start_mpris_server(
Arc::clone(&audio_engine),
Arc::clone(&queue),
Arc::clone(&scrobbler),
Arc::clone(&scrobble_state),
Arc::clone(&shutdown_flag),
);
// Accept connections until shutdown
listener.set_nonblocking(true)?;
// Helper: poll until a specific track actually starts playing or timeout
fn wait_for_start(audio: &AudioEngine, target: &PathBuf, timeout_ms: u64) -> bool {
use std::time::{Duration, Instant};
let start = Instant::now();
while start.elapsed() < Duration::from_millis(timeout_ms) {
if audio.is_playing()
&& let Some(cur) = audio.current_track()
&& &cur == target
{
return true;
}
std::thread::sleep(Duration::from_millis(10));
}
false
}
loop {
// Check for shutdown signal
if shutdown_flag.load(Ordering::SeqCst) {
break;
}
// Check if track ended and play next (robust with startup feedback)
if audio_engine.poll_track_ended()
&& let Ok(mut q) = queue.lock()
{
// Scrobble the track that just ended
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(&scrobbler, &mut s);
}
let original_position = q.position();
let mut started = false;
let mut had_next = false;
let max_trials = 4usize;
for _ in 0..max_trials {
if let Some(next_track) = q.next() {
had_next = true;
audio_engine.play(next_track.clone());
if wait_for_start(&audio_engine, &next_track, 500) {
started = true;
let track = Track::from_path(next_track.clone());
// Send now playing and record scrobble start
send_now_playing(&scrobbler, &track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(&track, fmt.as_deref());
break;
}
} else {
break;
}
}
if !started {
q.set_position(original_position);
audio_engine.stop();
if had_next {
notification::notify_error("Playback failed");
} else {
notification::notify_queue_ended();
q.clear();
}
}
}
match listener.accept() {
Ok((stream, _)) => {
let audio_clone = Arc::clone(&audio_engine);
let shutdown_flag_clone = Arc::clone(&shutdown_flag);
let queue_clone = Arc::clone(&queue);
let scrobbler_clone = Arc::clone(&scrobbler);
let scrobble_state_clone = Arc::clone(&scrobble_state);
thread::spawn(move || {
handle_client(
stream,
audio_clone,
shutdown_flag_clone,
queue_clone,
scrobbler_clone,
scrobble_state_clone,
);
});
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(50));
continue;
}
Err(e) => eprintln!("Connection failed: {}", e),
}
thread::sleep(Duration::from_millis(50));
}
// Cleanup
cleanup_daemon(&socket_path, &pid_path);
println!("Daemon stopped");
Ok(())
}
pub fn stop_daemon() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?;
let pid_path = get_pid_path(&config);
match check_running_daemon(&pid_path) {
Ok(pid) => {
// Try to send stop command first for graceful shutdown
if let Ok(()) = send_command_raw("stop_daemon".to_string()) {
// Wait for daemon to stop
for _ in 0..50 {
thread::sleep(Duration::from_millis(100));
if !is_process_running(pid) {
break;
}
}
}
// Force kill if still running
if is_process_running(pid) {
unsafe {
libc::kill(pid as i32, libc::SIGTERM);
}
thread::sleep(Duration::from_millis(500));
// Force kill if still alive
if is_process_running(pid) {
unsafe {
libc::kill(pid as i32, libc::SIGKILL);
}
}
}
// Clean up files
let socket_path = Config::get_socket_path();
std::fs::remove_file(&socket_path).ok();
std::fs::remove_file(&pid_path).ok();
println!("Daemon stopped");
Ok(())
}
Err(e) => Err(format!("Daemon not running: {}", e).into()),
}
}
pub fn restart_daemon() -> Result<(), Box<dyn std::error::Error>> {
// Stop existing daemon
if let Ok(()) = stop_daemon() {
// Wait a bit for cleanup
thread::sleep(Duration::from_millis(500));
}
// Start new daemon in background
let current_exe = std::env::current_exe()?;
std::process::Command::new(current_exe)
.arg("start-daemon")
.spawn()?;
println!("Daemon restarted");
Ok(())
}
pub fn send_command(cmd: String) -> Result<(), Box<dyn std::error::Error>> {
send_command_raw(cmd)?;
Ok(())
}
fn send_command_raw(cmd: String) -> Result<(), Box<dyn std::error::Error>> {
let socket_path = Config::get_socket_path();
let mut stream = UnixStream::connect(socket_path)?;
stream.write_all(cmd.as_bytes())?;
let mut buf = [0u8; 4096];
loop {
match stream.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if let Ok(s) = std::str::from_utf8(&buf[..n]) {
print!("{}", s);
}
}
Err(_) => break,
}
}
let _ = std::io::stdout().flush();
Ok(())
}
fn handle_client(
mut stream: UnixStream,
audio: Arc<AudioEngine>,
shutdown_flag: Arc<AtomicBool>,
queue: Arc<Mutex<Queue>>,
scrobbler: Arc<RwLock<Scrobbler>>,
scrobble_state: Arc<Mutex<ScrobbleState>>,
) {
let mut buffer = [0; 1024];
if let Ok(size) = stream.read(&mut buffer) {
let cmd = String::from_utf8_lossy(&buffer[..size]);
let trimmed = cmd.trim();
if trimmed == "lyrics" {
handle_lyrics_stream(&mut stream, &audio);
} else {
let response = process_command(
trimmed,
&audio,
&shutdown_flag,
&queue,
&scrobbler,
&scrobble_state,
);
let _ = stream.write_all(response.as_bytes());
}
}
}
struct LrcLine {
time: f64,
text: String,
}
fn parse_lrc(content: &str) -> Vec<LrcLine> {
let mut lines: Vec<LrcLine> = Vec::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
if let Some(rest) = line.strip_prefix('[')
&& let Some(idx) = rest.find(']')
{
let ts = &rest[..idx];
let text = rest[idx + 1..].trim().to_string();
if let Some(secs) = parse_lrc_timestamp(ts) {
lines.push(LrcLine { time: secs, text });
}
}
}
lines.sort_by(|a, b| {
a.time
.partial_cmp(&b.time)
.unwrap_or(std::cmp::Ordering::Equal)
});
lines
}
fn parse_lrc_timestamp(ts: &str) -> Option<f64> {
let ts = ts.trim();
if let Some((mm, rest)) = ts.split_once(':') {
let mm: f64 = mm.parse().ok()?;
let ss: f64 = rest.parse().ok()?;
Some(mm * 60.0 + ss)
} else {
None
}
}
fn handle_lyrics_stream(stream: &mut UnixStream, audio: &Arc<AudioEngine>) {
let track_path = match audio.current_track() {
Some(p) => p,
None => return,
};
let mut lrc_path = PathBuf::from(&track_path);
if !lrc_path.set_extension("lrc") || !lrc_path.exists() {
return;
}
let content = match fs::read_to_string(&lrc_path) {
Ok(c) => c,
Err(_) => return,
};
let lyrics = parse_lrc(&content);
if lyrics.is_empty() {
return;
}
let mut last_idx = None;
let mut prev_line_count = 0;
loop {
let pos = audio.position();
let current_idx = lyrics.iter().rposition(|l| l.time <= pos).unwrap_or(0);
if last_idx == Some(current_idx) {
thread::sleep(Duration::from_millis(100));
continue;
}
last_idx = Some(current_idx);
let start = current_idx.saturating_sub(1);
let end = (current_idx + 3).min(lyrics.len());
let mut output = String::new();
for (idx, l) in lyrics.iter().enumerate().take(end).skip(start) {
if idx == current_idx {
output.push_str(&format!(" > {}\n", l.text));
} else {
output.push_str(&format!(" {}\n", l.text));
}
}
let line_count = output.lines().count();
let mut frame = String::new();
if prev_line_count > 0 {
frame.push_str(&format!("\x1b[{}A\x1b[1B", prev_line_count));
} else {
frame.push_str("\x1b[2K");
}
frame.push_str(&output);
if stream.write_all(frame.as_bytes()).is_err() {
break;
}
if stream.flush().is_err() {
break;
}
prev_line_count = line_count;
thread::sleep(Duration::from_millis(100));
}
}
fn process_command(
cmd: &str,
audio: &AudioEngine,
shutdown_flag: &Arc<AtomicBool>,
queue: &Arc<Mutex<Queue>>,
scrobbler: &RwLock<Scrobbler>,
scrobble_state: &Arc<Mutex<ScrobbleState>>,
) -> String {
match cmd {
"status" => {
if audio.is_playing() {
if let Some(track_path) = audio.current_track() {
let track = Track::from_path(track_path);
let fmt = Config::load().ok().and_then(|c| c.display_format.clone());
let track_str = match fmt.as_deref() {
Some(f) => track.format(f),
None => track.display_string(0, 1),
};
format!("Playing\nTrack: {}\n", track_str)
} else {
"Playing\n".to_string()
}
} else {
"Stopped\n".to_string()
}
}
"pause" => {
audio.pause();
notification::notify_change("Paused");
"Paused\n".to_string()
}
"resume" => {
audio.resume();
notification::notify_change("Resumed");
"Resumed\n".to_string()
}
"toggle" => {
if audio.is_playing() {
audio.pause();
notification::notify_change("Paused");
"Paused\n".to_string()
} else {
audio.resume();
notification::notify_change("Resumed");
"Resumed\n".to_string()
}
}
"stop" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
audio.stop();
if let Ok(mut q) = queue.lock() {
q.clear();
}
notification::notify_change("Stopped");
"Stopped\n".to_string()
}
"stop_daemon" => {
shutdown_flag.store(true, Ordering::SeqCst);
"Shutting down\n".to_string()
}
"reload" | "validate" => {
if let Ok(config) = Config::load() {
let temp_scrobbler = Scrobbler::new(
config.lastfm_api_key.clone(),
config.lastfm_api_secret.clone(),
config.lastfm_session_key.clone(),
config.listenbrainz_token.clone(),
);
let result = match temp_scrobbler.validate_listenbrainz_token() {
Ok(Some(user)) => {
notification::notify(
"RSPlayer scrobbler login",
&format!("Logged in to ListenBrainz as {}", user),
);
format!("ListenBrainz token valid (user: {})\n", user)
}
Ok(None) => {
notification::notify_error("Invalid ListenBrainz token");
"ListenBrainz token invalid\n".to_string()
}
Err(e) => {
notification::notify_error(&format!("ListenBrainz validation: {}", e));
format!("ListenBrainz validation error: {}\n", e)
}
};
// Replace shared scrobbler state (only on reload, both is fine)
if let Ok(mut s) = scrobbler.write() {
*s = temp_scrobbler;
}
result
} else {
"Failed to load config\n".to_string()
}
}
"next" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
if let Ok(mut q) = queue.lock() {
if let Some(next_track) = q.next() {
audio.play(next_track.clone());
let track = Track::from_path(next_track.clone());
send_now_playing(scrobbler, &track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(&track, fmt.as_deref());
"Playing next track\n".to_string()
} else {
audio.stop();
notification::notify_queue_ended();
q.clear();
"Queue empty, stopped\n".to_string()
}
} else {
"Error accessing queue\n".to_string()
}
}
"previous" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
if let Ok(mut q) = queue.lock() {
if let Some(prev_track) = q.previous() {
audio.play(prev_track.clone());
let track = Track::from_path(prev_track.clone());
send_now_playing(scrobbler, &track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(&track, fmt.as_deref());
"Playing previous track\n".to_string()
} else {
"No previous track\n".to_string()
}
} else {
"Error accessing queue\n".to_string()
}
}
"shuffle" => {
if let Ok(q) = queue.lock() {
match q.shuffle_mode() {
ShuffleMode::None => "Shuffle: off\n".to_string(),
ShuffleMode::All => "Shuffle: on (all)\n".to_string(),
ShuffleMode::Album => "Shuffle: on (album)\n".to_string(),
ShuffleMode::Albums => "Shuffle: on (albums)\n".to_string(),
}
} else {
"Error accessing queue\n".to_string()
}
}
_ if cmd.starts_with("shuffle ") => {
let mode_str = cmd[8..].trim();
if let Ok(mut q) = queue.lock() {
let result = if mode_str == "on" || mode_str == "all" {
q.set_shuffle(ShuffleMode::All);
"Shuffle: on (all)\n".to_string()
} else if mode_str == "album" {
q.set_shuffle(ShuffleMode::Album);
"Shuffle: on (album)\n".to_string()
} else if mode_str == "albums" {
q.set_shuffle(ShuffleMode::Albums);
"Shuffle: on (albums)\n".to_string()
} else if mode_str == "off" || mode_str == "none" {
q.set_shuffle(ShuffleMode::None);
"Shuffle: off\n".to_string()
} else {
"Usage: shuffle [on|off|album|albums]\n".to_string()
};
// Save to config
if let Ok(mut config) = Config::load() {
if mode_str == "off" || mode_str == "none" {
config.shuffle = None;
} else {
config.shuffle = Some(mode_str.to_string());
}
let _ = config.save();
}
result
} else {
"Error accessing queue\n".to_string()
}
}
_ if cmd.starts_with("play-album ") => {
let rest = &cmd[11..].trim();
let (position, query_str): (&str, &str) = if let Some((pos, p)) = rest.split_once(' ') {
if pos == "now" || pos == "next" || pos == "last" {
(pos, p)
} else {
("last", rest)
}
} else {
("last", rest)
};
if query_str.is_empty() {
return "Usage: play-album [now|next|last] <path_or_query>\n".to_string();
}
let path = std::path::PathBuf::from(query_str);
// Resolve the full album containing the requested track, ordered by
// track_number. The album is rotated so playback starts at the
// requested track while the *entire* album is queued (auto-advance
// wraps through any earlier tracks). If the argument is an existing
// file, derive the album from its metadata; otherwise query the DB
// by hierarchical path or free-text search.
let (album_tracks, display_name): (Vec<PathBuf>, String) = if path.is_file() {
let canon = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
let (artist, album, _, _, _) = crate::database::extract_metadata(&canon);
let full: Vec<PathBuf> = match Config::load() {
Ok(config) => match crate::database::Database::open(&config) {
Ok(db) => db
.find_tracks_by_album(&artist, &album)
.unwrap_or_default()
.into_iter()
.map(|t| t.path)
.collect(),
Err(_) => Vec::new(),
},
Err(_) => Vec::new(),
};
let start_idx = full.iter().position(|p| *p == canon).unwrap_or(0);
let mut rotated: Vec<PathBuf> = full[start_idx..].to_vec();
rotated.extend_from_slice(&full[..start_idx]);
if rotated.is_empty() {
rotated.push(path.clone());
}
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown")
.to_string();
(rotated, name)
} else {
match Config::load() {
Ok(config) => match crate::database::Database::open(&config) {
Ok(db) => {
let tracks = match db.resolve_path(query_str) {
Ok(Some(t)) => t,
Ok(None) => match db.search_tracks(query_str) {
Ok(t) => t,
Err(e) => return format!("Database error: {}\n", e),
},
Err(e) => return format!("Database error: {}\n", e),
};
if tracks.is_empty() {
return format!("No tracks found matching '{}'\n", query_str);
}
let (full, display): (Vec<crate::database::Track>, String) =
if tracks.len() > 1 {
// resolve_path returned the full album
// ("Artist/Album" query) — keep order.
let d = format!(
"{} - {}",
tracks[0].artist_name.as_deref().unwrap_or("unknown"),
tracks[0].title,
);
(tracks, d)
} else {
// Single track from "Artist/Album/Track"
// or a search result — fetch the whole
// album and rotate so the requested
// track plays first.
let db_track = &tracks[0];
let full = match db.find_tracks_by_album(
db_track.artist_name.as_deref().unwrap_or(""),
db_track.album_title.as_deref().unwrap_or(""),
) {
Ok(f) if !f.is_empty() => f,
_ => vec![db_track.clone()],
};
let start_idx = full
.iter()
.position(|t| t.path == db_track.path)
.unwrap_or(0);
let mut rotated: Vec<crate::database::Track> =
full[start_idx..].to_vec();
rotated.extend_from_slice(&full[..start_idx]);
let d = format!(
"{} - {}",
db_track.artist_name.as_deref().unwrap_or("unknown"),
db_track.title,
);
(rotated, d)
};
let album_tracks: Vec<PathBuf> =
full.iter().map(|t| t.path.clone()).collect();
(album_tracks, display)
}
Err(e) => return format!("Database error: {}\n", e),
},
Err(e) => return format!("Config error: {}\n", e),
}
};
if let Ok(mut q) = queue.lock() {
let was_empty = q.is_empty();
match position {
"now" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
// album_tracks[0] is the track to start at; insert the
// whole block in correct order.
if was_empty {
for t in &album_tracks {
q.add_track(t.clone());
}
} else {
for t in album_tracks.iter().rev() {
q.insert_after_current(t.clone());
}
let new_pos = q.position() + 1;
q.set_position(new_pos);
}
if let Some(track) = q.track_at(q.position()) {
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(track, fmt.as_deref());
}
format!(
"Playing {} with {} album track(s)\n",
display_name,
album_tracks.len().saturating_sub(1)
)
}
"next" => {
if was_empty {
for t in &album_tracks {
q.add_track(t.clone());
}
} else {
for t in album_tracks.iter().rev() {
q.insert_after_current(t.clone());
}
}
format!(
"Queued next: {} with {} album track(s)\n",
display_name,
album_tracks.len().saturating_sub(1)
)
}
_ => {
for t in &album_tracks {
q.add_track(t.clone());
}
if was_empty
&& !audio.is_playing()
&& let Some(track) = q.current()
{
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
}
format!(
"Queued: {} with {} album track(s)\n",
display_name,
album_tracks.len().saturating_sub(1)
)
}
}
} else {
"Error accessing queue\n".to_string()
}
}
_ if cmd.starts_with("play ") => {
let rest = &cmd[5..].trim();
let (position, path_str): (&str, &str) = if let Some((pos, p)) = rest.split_once(' ') {
if pos == "now" || pos == "next" || pos == "last" {
(pos, p)
} else {
("last", rest)
}
} else {
("last", rest)
};
let path_str = if path_str.starts_with("~/") {
std::env::var("HOME")
.map(|h| path_str.replacen("~", &h, 1))
.unwrap_or_else(|_| path_str.to_string())
} else {
path_str.to_string()
};
// Strip trailing slash so autocompleted Artist/Album/ resolves cleanly
let path_str = path_str.trim_end_matches('/').to_string();
// Unescape backslash sequences (e.g., \! → !) so shell escaping works
let path_str = {
let mut unescaped = String::with_capacity(path_str.len());
let mut chars = path_str.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
unescaped.push(next);
}
} else {
unescaped.push(c);
}
}
unescaped
};
if path_str.is_empty() {
return "Usage: play [now|next|last] <path>\n".to_string();
}
let is_url = path_str.starts_with("http://") || path_str.starts_with("https://");
if is_url {
if let Ok(mut q) = queue.lock() {
let was_empty = q.is_empty();
let track = Track::from_url(&path_str);
match position {
"now" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
q.push_track(track.clone());
if !was_empty {
let new_pos = q.position() + 1;
q.set_position(new_pos);
}
if let Some(track) = q.track_at(q.position()) {
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt =
Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(track, fmt.as_deref());
}
format!("Playing now: {}\n", path_str)
}
"next" => {
q.push_track(track);
format!("Queued next: {}\n", path_str)
}
_ => {
let was_playing = audio.is_playing();
q.push_track(track.clone());
if was_empty
&& !was_playing
&& let Some(track) = q.current()
{
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt =
Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(track, fmt.as_deref());
}
format!("Queued: {}\n", path_str)
}
}
} else {
"Error accessing queue\n".to_string()
}
} else {
let path = std::path::PathBuf::from(path_str.clone());
if path.is_file() {
if let Ok(mut q) = queue.lock() {
let was_empty = q.is_empty();
match position {
"now" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
q.insert_after_current(path.clone());
if !was_empty {
let new_pos = q.position() + 1;
q.set_position(new_pos);
}
if let Some(track) = q.track_at(q.position()) {
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt =
Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(track, fmt.as_deref());
}
format!("Playing now: {}\n", path_str)
}
"next" => {
q.insert_after_current(path.clone());
format!("Queued next: {}\n", path_str)
}
_ => {
let was_empty = q.is_empty();
let was_playing = audio.is_playing();
q.add_track(path.clone());
if was_empty && !was_playing {
let track = Track::from_path(path.clone());
audio.play(path);
send_now_playing(scrobbler, &track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt =
Config::load().ok().and_then(|c| c.display_format.clone());
notification::notify_track(&track, fmt.as_deref());
format!("Playing: {}\n", path_str)
} else {
format!("Queued: {}\n", path_str)
}
}
}
} else {
"Error accessing queue\n".to_string()
}
} else if path.is_dir() {
match find_audio_in_dir(&path) {
Some(files) if !files.is_empty() => {
if let Ok(mut q) = queue.lock() {
let was_empty = q.is_empty();
match position {
"now" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
for file in files.iter().rev() {
q.insert_after_current(file.clone());
}
if !was_empty {
let new_pos = q.position() + 1;
q.set_position(new_pos);
}
if let Some(track) = q.track_at(q.position()) {
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load()
.ok()
.and_then(|c| c.display_format.clone());
notification::notify_track(track, fmt.as_deref());
}
format!(
"Playing now: {} tracks from {}\n",
files.len(),
path_str
)
}
"next" => {
for file in files.iter().rev() {
q.insert_after_current(file.clone());
}
format!(
"Queued next: {} tracks from {}\n",
files.len(),
path_str
)
}
_ => {
let was_playing = audio.is_playing();
for file in &files {
q.add_track(file.clone());
}
if was_empty && !was_playing {
q.shuffle_initial();
if let Some(track) = q.current() {
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load()
.ok()
.and_then(|c| c.display_format.clone());
notification::notify_track(track, fmt.as_deref());
}
}
format!(
"Queued {} tracks from: {}\n",
files.len(),
path_str
)
}
}
} else {
"Error accessing queue\n".to_string()
}
}
_ => format!("Error: No audio files found in '{}'\n", path_str),
}
} else {
match Config::load() {
Ok(config) => match crate::database::Database::open(&config) {
Ok(db) => {
// Collect tracks: try hierarchical path first, fallback to search
let tracks = match db.resolve_path(&path_str) {
Ok(Some(t)) => t,
Ok(None) => {
let query = path_str
.rsplit_once('/')
.and_then(|(_, after)| {
(!after.is_empty()).then_some(after)
})
.unwrap_or(&path_str);
match db.search_tracks(query) {
Ok(t) => t,
Err(e) => return format!("Database error: {}\n", e),
}
}
Err(e) => return format!("Database error: {}\n", e),
};
if tracks.is_empty() {
return format!("No tracks found matching '{}'\n", path_str);
}
let is_album_play = tracks.len() > 1;
if let Ok(mut q) = queue.lock() {
let was_empty = q.is_empty();
match position {
"now" => {
if let Ok(mut s) = scrobble_state.lock() {
try_scrobble_current(scrobbler, &mut s);
}
for t in tracks.iter().rev() {
q.insert_after_current(t.path.clone());
}
if !was_empty {
let new_pos = q.position() + 1;
q.set_position(new_pos);
}
if let Some(track) = q.track_at(q.position()) {
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load()
.ok()
.and_then(|c| c.display_format.clone());
notification::notify_track(track, fmt.as_deref());
}
if is_album_play {
format!(
"Playing now: {} tracks from {}\n",
tracks.len(),
path_str
)
} else {
format!("Playing now: {}\n", path_str)
}
}
"next" => {
for t in tracks.iter().rev() {
q.insert_after_current(t.path.clone());
}
if is_album_play {
format!(
"Queued next: {} tracks from {}\n",
tracks.len(),
path_str
)
} else {
format!("Queued next: {}\n", path_str)
}
}
_ => {
let was_playing = audio.is_playing();
for t in &tracks {
q.add_track(t.path.clone());
}
if was_empty && !was_playing {
if is_album_play {
q.shuffle_initial();
}
if let Some(track) = q.current() {
audio.play(track.path.clone());
send_now_playing(scrobbler, track);
if let Ok(mut s) = scrobble_state.lock() {
s.start(track.clone());
}
let fmt = Config::load()
.ok()
.and_then(|c| c.display_format.clone());
notification::notify_track(
track,
fmt.as_deref(),
);
}
if is_album_play {
format!(
"Playing: {} tracks from {}\n",
tracks.len(),
path_str
)
} else {
format!("Playing: {}\n", path_str)
}
} else if is_album_play {
format!(
"Queued {} tracks from: {}\n",
tracks.len(),
path_str
)
} else {
format!("Queued: {}\n", path_str)
}
}
}
} else {
"Error accessing queue\n".to_string()
}
}
Err(e) => format!("Database error: {}\n", e),
},
Err(e) => format!("Config error: {}\n", e),
}
}
}
}
_ if cmd == "volume" => {
let vol = audio.get_volume();
format!("Volume: {}\n", vol)
}
_ if cmd.starts_with("volume ") => {
if let Ok(level) = cmd[7..].trim().parse::<u8>() {
audio.set_volume(level as f32 / 100.0);
// Save to config
if let Ok(mut config) = Config::load() {
config.volume = Some(level);
let _ = config.save();
}
format!("Volume set to {}\n", level)
} else {
"Usage: volume <0-100>\n".to_string()
}
}
_ if cmd.starts_with("queue") => {
if let Ok(q) = queue.lock() {
if q.is_empty() {
"Queue is empty\n".to_string()
} else {
let mut output = String::new();
let current_position = q.position();
let playing_track_idx = match q.shuffle_mode() {
ShuffleMode::None => current_position,
_ => q
.shuffled_indices()
.get(current_position)
.copied()
.unwrap_or(0),
};
let indices: Vec<usize> = if *q.shuffle_mode() == ShuffleMode::None {
(0..q.len()).collect()
} else {
q.shuffled_indices().to_vec()
};
let is_playing = audio.is_playing();
let fmt = Config::load().ok().and_then(|c| c.display_format.clone());
for (display_idx, &track_idx) in indices.iter().enumerate() {
if let Some(track) = q.track_at(track_idx) {
let track_str = match fmt.as_deref() {
Some(f) => track.format(f),
None => track.display_string(display_idx, q.len()),
};
if track_idx == playing_track_idx && is_playing {
output.push_str(&format!("> {} (playing)\n", track_str));
} else if track_idx == playing_track_idx && !is_playing {
output.push_str(&format!("> {} (paused)\n", track_str));
} else {
output.push_str(&format!(" {}\n", track_str));
}
}
}
// Always return full output - client can pipe to pager if needed
output
}
} else {
"Error accessing queue\n".to_string()
}
}
_ => "Unknown command\n".to_string(),
}
}
fn find_audio_in_dir(dir: &Path) -> Option<Vec<std::path::PathBuf>> {
use std::ffi::OsStr;
let mut results = Vec::new();
if let Ok(entries) = std::fs::read_dir(dir) {
let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
if path.is_file() {
if let Some(ext) = path.extension().and_then(OsStr::to_str)
&& matches!(
ext.to_lowercase().as_str(),
"mp3" | "flac" | "ogg" | "m4a" | "wav" | "opus"
)
{
results.push(path);
}
} else if path.is_dir()
&& let Some(mut found) = find_audio_in_dir(&path)
{
results.append(&mut found);
}
}
}
if results.is_empty() {
None
} else {
Some(results)
}
}
/// Get the PID file path for the daemon
fn get_pid_path(_config: &Config) -> std::path::PathBuf {
let runtime_dir = std::env::var("XDG_RUNTIME_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| std::path::PathBuf::from("/tmp"));
runtime_dir.join("rsplayer").join("rsplayer.pid")
}
/// Check if a process with the given PID is running
fn is_process_running(pid: u32) -> bool {
unsafe {
// send signal 0 to check if process exists
libc::kill(pid as i32, 0) == 0
}
}
/// Check if daemon is running by reading PID file
fn check_running_daemon(pid_path: &std::path::Path) -> Result<u32, Box<dyn std::error::Error>> {
if !pid_path.exists() {
return Err("PID file not found".into());
}
let contents = std::fs::read_to_string(pid_path)?;
let pid = contents.trim().parse::<u32>()?;
if is_process_running(pid) {
Ok(pid)
} else {
// Stale PID file, clean it up
std::fs::remove_file(pid_path).ok();
Err("Stale PID file, daemon not running".into())
}
}
/// Clean up daemon resources (socket and PID file)
fn cleanup_daemon(socket_path: &std::path::Path, pid_path: &std::path::Path) {
std::fs::remove_file(socket_path).ok();
std::fs::remove_file(pid_path).ok();
}
|