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
// Copyright (c) 2026
// Author: prjctimg <prjctimg@outlook.com>
// CLI subcommand dispatch via daemon IPC
//
// This is free software released under the GPL-3.0 license.
use std::io::Write;
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use gtm_core::client::DaemonClient;
use gtm_core::global::RepeatMode;
use crate::footer::format_uptime;
#[derive(Parser)]
#[command(
name = "gtm",
version = option_env!("CARGO_PKG_VERSION").unwrap_or("0.1.0"),
about = "gtm music player"
)]
pub struct Args {
#[arg(long, short, help = "Run in CLI mode instead of TUI")]
pub cli: bool,
#[arg(long, short, global = true, help = "Verbose output")]
pub verbose: bool,
#[arg(long, short, global = true, help = "Daemon socket path")]
pub socket: Option<String>,
#[arg(long, short, global = true, help = "Output as JSON (CLI mode only)")]
pub json: bool,
#[command(subcommand)]
pub command: Option<CliCommand>,
}
#[derive(Subcommand)]
pub enum CliCommand {
/// Play an audio file or resume playback
Play {
#[arg(value_name = "PATH", value_hint = clap::ValueHint::FilePath)]
path: String,
#[arg(value_name = "SECONDS")]
start_pos: Option<f64>,
},
/// Toggle play/pause
PlayPause,
/// Pause playback
Pause,
/// Stop playback
Stop,
/// Skip to next track
Next,
/// Skip to previous track
Prev,
/// Seek to a position in seconds
Seek { position_secs: f64 },
/// Set volume (0-100)
Volume { volume: u8 },
/// Toggle shuffle
Shuffle,
/// Set repeat mode (off, one, all)
Repeat {
#[arg(value_name = "MODE", value_parser = ["off", "one", "all"])]
mode: String,
},
/// Toggle mute
Mute,
/// Enable/disable crossfade with optional duration
Crossfade {
#[arg(
value_name = "ENABLED",
action = clap::ArgAction::Set,
value_parser = clap::builder::BoolishValueParser::new()
)]
enabled: bool,
duration_secs: Option<u8>,
},
/// Show the current queue
Queue,
/// Add audio files or directories to the queue
QueueAdd {
#[arg(value_name = "PATH", value_hint = clap::ValueHint::AnyPath, num_args = 1..)]
paths: Vec<String>,
#[arg(long, value_name = "INDEX")]
position: Option<u64>,
},
/// Remove a track from the queue by index
QueueRemove { index: u64 },
/// Move a track within the queue
QueueMove { from: u64, to: u64 },
/// Clear the entire queue
QueueClear,
/// Replace the queue with the given tracks
QueueSet {
#[arg(value_name = "PATH", value_hint = clap::ValueHint::AnyPath, num_args = 1..)]
paths: Vec<String>,
#[arg(long, value_name = "INDEX")]
start_idx: u64,
},
/// Scan a directory for audio files and add to library
Scan {
#[arg(value_name = "DIR", value_hint = clap::ValueHint::DirPath)]
path: String,
},
/// List library tracks with optional filter and sort
Tracks {
filter: Option<String>,
sort: Option<String>,
},
/// List playlists
Playlists,
/// Create a new playlist
CreatePlaylist { name: String },
/// Delete a playlist
DeletePlaylist { id: i64 },
/// Add tracks to a playlist
AddToPlaylist {
playlist_id: i64,
track_ids: Vec<i64>,
},
/// Import an M3U playlist file
ImportM3u {
#[arg(value_name = "FILE", value_hint = clap::ValueHint::FilePath)]
path: String,
},
/// Export a playlist to M3U file
ExportM3u {
playlist_id: i64,
#[arg(value_name = "FILE", value_hint = clap::ValueHint::FilePath)]
path: String,
},
/// Show recently played tracks
Recent { count: u64 },
/// Sync metadata for a file or all library tracks
MetadataSync {
#[arg(value_name = "PATH", value_hint = clap::ValueHint::FilePath)]
path: Option<String>,
},
/// List favourite tracks
Favourites,
/// Add a track to favourites
FavouriteAdd { track_id: i64 },
/// Remove a track from favourites
FavouriteRemove { track_id: i64 },
/// Search for lyrics (format: "artist - title")
Lyrics { query: String },
/// Search the library
Search { query: String },
/// Show daemon status
Status {
#[arg(long)]
stream: bool,
},
/// Check daemon health
CheckHealth,
/// Ping the daemon
Ping,
/// Quit the daemon
Quit,
/// Manage config file
Config {
#[arg(long)]
reset: bool,
#[arg(long)]
validate: bool,
},
/// Set a sleep timer in minutes
SleepTimer { minutes: u32 },
/// Cancel the current sleep timer
CancelSleepTimer,
/// Edit track metadata (field: title, artist, album, genre, year, track-number)
UpdateMetadata {
track_id: i64,
#[arg(value_name = "FIELD")]
field: String,
#[arg(value_name = "VALUE")]
value: String,
},
#[command(subcommand)]
/// Spotify integration commands
Spotify(SpotifyAction),
}
#[derive(Subcommand)]
pub enum SpotifyAction {
/// Link a Spotify account with an access token
Connect { token: String },
/// Start the OAuth browser flow and wait for you to finish login
Login {
client_id: Option<String>,
/// Local redirect port (defaults to 8990 or $GTM_SPOTIFY_PORT)
#[clap(long)]
port: Option<u16>,
},
/// Unlink the Spotify account
Disconnect,
/// Show Spotify connection status
Status,
/// Sync Spotify playlists to the library
Sync,
}
pub fn run(socket: Option<String>, json: bool, verbose: bool, cmd: &CliCommand) {
if let CliCommand::Config { reset, validate } = cmd {
if *reset {
let path = crate::app::ensure_prefs_file();
let _ = std::fs::remove_file(&path);
let path = crate::app::ensure_prefs_file();
println!("config reset to defaults at {}", path.display());
} else if *validate {
let path = crate::app::ensure_prefs_file();
match std::fs::read_to_string(&path) {
Ok(contents) => match toml::from_str::<crate::app::Prefs>(&contents) {
Ok(_) => println!("config is valid"),
Err(e) => {
eprintln!("config error: {e}");
std::process::exit(1);
}
},
Err(e) => {
eprintln!("failed to read config: {e}");
std::process::exit(1);
}
}
} else {
if let Err(e) = open_config_in_editor() {
eprintln!("error: {e}");
std::process::exit(1);
}
}
return;
}
let rt = tokio::runtime::Runtime::new().unwrap();
let result: Result<String, String> = rt.block_on(async {
let socket_path = socket
.map(PathBuf::from)
.unwrap_or_else(gtm_core::resolve_command_socket);
let client = DaemonClient::connect(&socket_path)
.await
.map_err(|e| format!("Failed to connect to daemon at {socket_path:?}: {e}"))?;
match cmd {
CliCommand::Play { path, start_pos } => {
let pos = start_pos.unwrap_or(0.0);
client
.play(path, pos)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string())
}
CliCommand::PlayPause => client
.play_pause()
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Pause => client
.pause()
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Stop => client
.stop()
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Next => {
client.next().await.map_err(|e| e.to_string())?;
if verbose {
match client.get_status().await {
Ok(state) => {
if let Some(ref t) = state.current_track {
Ok(format!(
"Now Playing: {}\n{} - {}",
t.title, t.artist, t.album
))
} else {
Ok("Stopped".to_string())
}
}
Err(_) => Ok("ok".to_string()),
}
} else {
Ok("ok".to_string())
}
}
CliCommand::Prev => {
client.prev().await.map_err(|e| e.to_string())?;
if verbose {
match client.get_status().await {
Ok(state) => {
if let Some(ref t) = state.current_track {
Ok(format!(
"Now Playing: {}\n{} - {}",
t.title, t.artist, t.album
))
} else {
Ok("Stopped".to_string())
}
}
Err(_) => Ok("ok".to_string()),
}
} else {
Ok("ok".to_string())
}
}
CliCommand::Seek { position_secs } => client
.seek(*position_secs)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Volume { volume } => {
client
.set_volume(*volume)
.await
.map_err(|e| e.to_string())?;
if verbose {
Ok(format!("Volume: {}%", volume))
} else {
Ok("ok".to_string())
}
}
CliCommand::Shuffle => client
.toggle_shuffle()
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Repeat { mode } => {
let mode: RepeatMode = mode.parse().map_err(|e: String| e)?;
client
.cycle_repeat(mode)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string())
}
CliCommand::Mute => client
.toggle_mute()
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Crossfade {
enabled,
duration_secs,
} => {
let dur = duration_secs.unwrap_or(7);
client
.crossfade(*enabled, dur)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string())
}
CliCommand::Queue => {
let res = client.queue().list().await.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&res).map_err(|e| e.to_string())
} else {
Ok(format!("{res:?}"))
}
}
CliCommand::QueueAdd { paths, position } => client
.queue()
.add_many(paths.clone(), *position)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::QueueRemove { index } => client
.queue()
.remove(*index)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::QueueMove { from, to } => client
.queue()
.reorder(*from, *to)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::QueueClear => client
.queue()
.clear()
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::QueueSet { paths, start_idx } => client
.queue()
.set(paths.clone(), *start_idx)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Scan { path } => client
.library()
.scan(path)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Tracks { filter, sort } => {
let res = client
.library()
.get_tracks(filter.clone(), sort.clone())
.await
.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&res).map_err(|e| e.to_string())
} else {
Ok(format!("{res:?}"))
}
}
CliCommand::Playlists => {
let res = client
.library()
.get_playlists()
.await
.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&res).map_err(|e| e.to_string())
} else {
Ok(format!("{res:?}"))
}
}
CliCommand::CreatePlaylist { name } => client
.library()
.create_playlist(name)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::DeletePlaylist { id } => client
.library()
.delete_playlist(*id)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::AddToPlaylist {
playlist_id,
track_ids,
} => client
.library()
.add_to_playlist(*playlist_id, track_ids.clone())
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::ImportM3u { path } => client
.library()
.import_m3u(path)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::ExportM3u { playlist_id, path } => client
.library()
.export_m3u(*playlist_id, path)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Recent { count } => {
let res = client
.library()
.get_recent(*count)
.await
.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&res).map_err(|e| e.to_string())
} else {
Ok(format!("{res:?}"))
}
}
CliCommand::MetadataSync { path } => {
client
.library()
.sync_metadata(path.clone())
.await
.map_err(|e| e.to_string())?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1800);
loop {
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
let st = client
.library()
.sync_status()
.await
.map_err(|e| e.to_string())?;
if !st.running {
if json {
return serde_json::to_string_pretty(&st).map_err(|e| e.to_string());
}
return Ok(format!(
"Metadata synced: {}/{} tracks",
st.synced, st.total
));
}
if std::time::Instant::now() >= deadline {
return Err("metadata sync timed out".to_string());
}
}
}
CliCommand::Favourites => {
let res = client
.favourites()
.list()
.await
.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&res).map_err(|e| e.to_string())
} else {
Ok(format!("{res:?}"))
}
}
CliCommand::FavouriteAdd { track_id } => client
.favourites()
.add(*track_id)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::FavouriteRemove { track_id } => client
.favourites()
.remove(*track_id)
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Search { query } => {
let res = client.search(query).await.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&res).map_err(|e| e.to_string())
} else {
Ok(format!("{res:?}"))
}
}
CliCommand::Lyrics { query } => {
let (artist, title) = match query.split_once(" - ") {
Some((a, t)) => (a.trim().to_string(), t.trim().to_string()),
None => (String::new(), query.trim().to_string()),
};
let lyrics = client
.lyrics()
.search(&artist, &title)
.await
.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&lyrics).map_err(|e| e.to_string())
} else {
match lyrics {
Some(l) => {
if l.lines.is_empty() {
let artist_str = if let Some(ref a) = l.artist {
format!("{a}: ")
} else {
String::new()
};
Ok(format!(
"Found lyrics metadata for {}{} but no timed lines.",
artist_str,
l.title.as_ref().unwrap_or(&String::from("unknown"))
))
} else {
let mut out = String::new();
if let Some(ref t) = l.title {
out += &format!("{t}\n");
}
if let Some(ref a) = l.artist {
out += &format!("{a}\n");
}
out += &"-".repeat(32);
out += "\n";
for line in &l.lines {
if line.timestamp < 0.0 {
out += &line.text;
out += "\n";
} else {
let mm = (line.timestamp / 60.0) as u64;
let ss = line.timestamp % 60.0;
out += &format!("[{:02}:{:05.2}] {}\n", mm, ss, line.text);
}
}
Ok(out)
}
}
None => Ok("No lyrics found.".to_string()),
}
}
}
CliCommand::Status { stream } => {
if *stream {
let mut last_track: Option<String> = None;
let mut lyrics: Option<gtm_core::track::LrcData> = None;
let mut first = true;
loop {
let state = client.get_status().await.map_err(|e| e.to_string())?;
let elapsed = state.time_pos as u64;
let dur = state.duration as u64;
let track = state.current_track.as_ref().map_or("No track".into(), |t| {
if t.artist.is_empty() {
t.title.clone()
} else {
format!("{} - {}", t.artist, t.title)
}
});
let vol = state.volume;
// (Re)fetch time-synced lyrics whenever the track changes.
let track_key = state.current_track.as_ref().map(|t| t.path.clone());
if track_key != last_track {
last_track = track_key;
lyrics = match &state.current_track {
Some(t) => client
.lyrics()
.search(&t.artist, &t.title)
.await
.ok()
.flatten(),
None => None,
};
}
// Pick the active lyric line for the current position.
let active = lyrics.as_ref().and_then(|l| {
let pos = state.time_pos;
l.lines
.iter()
.rfind(|ln| ln.timestamp >= 0.0 && ln.timestamp <= pos)
.or_else(|| l.lines.iter().find(|ln| ln.timestamp < 0.0))
.map(|ln| ln.text.trim().to_string())
});
if !first {
print!("\x1b[1A");
}
first = false;
print!(
"\r\x1b[KStream: {} | {}s / {}s | {}%",
track, elapsed, dur, vol
);
if let Some(line) = active {
print!("\n\x1b[K ♪ {}", line);
} else {
print!("\n\x1b[K");
}
std::io::stdout().flush().ok();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
} else {
let state = client.get_status().await.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&state).map_err(|e| e.to_string())
} else {
let status_str = match state.status {
gtm_core::global::PlaybackStatus::Playing => "\x1b[32m▶ Playing\x1b[0m",
gtm_core::global::PlaybackStatus::Paused => "\x1b[33m⏸ Paused\x1b[0m",
gtm_core::global::PlaybackStatus::Stopped => "\x1b[31m⏹ Stopped\x1b[0m",
};
let track_str = state
.current_track
.as_ref()
.map(|t| {
let title = if t.title.is_empty() {
std::path::Path::new(&t.path)
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| "Unknown".into())
} else {
t.title.clone()
};
if t.artist.is_empty() {
title
} else {
format!("{}: {}", t.artist, title)
}
})
.unwrap_or_else(|| "No track".into());
let vol_str = format!("\x1b[36m{}%\x1b[0m", state.volume);
let repeat_str = format!("{:?}", state.repeat);
let shuffle_str = if state.shuffle {
"\x1b[32mOn\x1b[0m"
} else {
"Off"
};
let queue_str = format!(
"{} tracks, cursor {}/{}",
state.queue.len(),
state.queue_cursor + 1,
state.queue.len().max(1)
);
let mute_str = if state.mute {
"\x1b[33mMuted\x1b[0m"
} else {
"Unmuted"
};
Ok(format!(
"\x1b[1mPlayback:\x1b[0m {}\n\
\x1b[1mTrack:\x1b[0m {}\n\
\x1b[1mVolume:\x1b[0m {} ({})\n\
\x1b[1mRepeat:\x1b[0m {}\n\
\x1b[1mShuffle:\x1b[0m {}\n\
\x1b[1mQueue:\x1b[0m {}",
status_str,
track_str,
vol_str,
mute_str,
repeat_str,
shuffle_str,
queue_str
))
}
}
}
CliCommand::Ping => {
client.ping().await.map_err(|e| e.to_string())?;
Ok("pong".into())
}
CliCommand::CheckHealth => {
let report = client.check_health().await.map_err(|e| e.to_string())?;
if json {
serde_json::to_string_pretty(&report).map_err(|e| e.to_string())
} else {
let mut out = format!(
"\x1b[1mgtm Health Report\x1b[0m (v{})\n\
Daemon uptime: {}\n",
report.version,
format_uptime(report.daemon_uptime_secs)
);
for c in &report.components {
let icon = match c.status {
gtm_core::ipc::HealthStatus::Ok => "\x1b[32m✓\x1b[0m",
gtm_core::ipc::HealthStatus::Degraded => "\x1b[33m⚠\x1b[0m",
gtm_core::ipc::HealthStatus::Error => "\x1b[31m✗\x1b[0m",
};
out += &format!(" {icon} \x1b[1m{}\x1b[0m", c.name);
if let Some(ref msg) = c.message {
out += &format!(": {msg}");
}
if let Some(uptime) = c.uptime_secs {
out += &format!(" (uptime {:.0}s)", uptime);
}
out += "\n";
}
Ok(out)
}
}
CliCommand::Quit => client
.quit()
.await
.map(|()| "ok".to_string())
.map_err(|e| e.to_string()),
CliCommand::Config { .. } => unreachable!(),
CliCommand::SleepTimer { minutes } => client
.set_sleep_timer(*minutes)
.await
.map(|()| format!("sleep timer set for {minutes} min"))
.map_err(|e| e.to_string()),
CliCommand::CancelSleepTimer => client
.cancel_sleep_timer()
.await
.map(|()| "sleep timer cancelled".to_string())
.map_err(|e| e.to_string()),
CliCommand::UpdateMetadata {
track_id,
field,
value,
} => {
let mut patch = gtm_core::ipc::MetadataPatch::default();
match field.as_str() {
"title" => patch.title = Some(value.clone()),
"artist" => patch.artist = Some(value.clone()),
"album" => patch.album = Some(value.clone()),
"genre" => patch.genre = Some(value.clone()),
"year" => {
patch.year = Some(
value
.trim()
.parse::<i32>()
.map_err(|_| format!("invalid year: {value}"))?,
)
}
"track-number" | "track_number" => {
patch.track_number = Some(
value
.trim()
.parse::<i32>()
.map_err(|_| format!("invalid track number: {value}"))?,
)
}
other => {
return Err(format!(
"unknown field `{other}` (use title, artist, album, genre, year, \
track-number)"
));
}
}
if patch == gtm_core::ipc::MetadataPatch::default() {
return Err("no field to update: pass a supported FIELD".to_string());
}
client
.library()
.update_metadata(*track_id, patch)
.await
.map(|()| "metadata updated".to_string())
.map_err(|e| e.to_string())
}
CliCommand::Spotify(action) => match action {
SpotifyAction::Connect { token } => {
let st = client
.spotify()
.set_token(token)
.await
.map_err(|e| e.to_string())?;
Ok(format_spotify_status(&st))
}
SpotifyAction::Login { client_id, port } => {
let port = port
.or_else(|| {
std::env::var("GTM_SPOTIFY_PORT")
.ok()
.and_then(|v| v.parse().ok())
})
.unwrap_or(8990);
// Resolve the client id: explicit arg > keychain > masked prompt
// (so a locked keychain still lets the user log in).
let client_id = match client_id.clone() {
Some(c) => c,
None => match gtm_core::secret::get_secret(
gtm_core::secret::SPOTIFY_CLIENT_ID_KEY,
) {
Some(c) => c,
None => {
use std::io::Write;
print!("Spotify Client ID: ");
let _ = std::io::stdout().flush();
match rpassword::read_password() {
Ok(s) => s.trim().to_string(),
Err(_) => {
return Err("could not read client id from terminal".into());
}
}
}
},
};
if client_id.trim().is_empty() {
return Err("no Spotify client id provided".into());
}
gtm_core::secret::set_secret(
gtm_core::secret::SPOTIFY_CLIENT_ID_KEY,
&client_id,
);
let url = client
.spotify()
.oauth_start(&client_id, port)
.await
.map_err(|e| e.to_string())?;
println!("Open this URL in your browser to authorize gtm:\n{url}\n");
let _ = webbrowser::open(&url);
println!("Waiting for you to finish login in your browser…");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);
loop {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
match client.spotify().status().await {
Ok(st) if st.linked => return Ok(format_spotify_status(&st)),
Ok(_) if std::time::Instant::now() < deadline => continue,
Ok(_) => return Err("timed out waiting for Spotify login".to_string()),
Err(e) => return Err(e.to_string()),
}
}
}
SpotifyAction::Disconnect => {
let st = client.spotify().clear().await.map_err(|e| e.to_string())?;
Ok(format_spotify_status(&st))
}
SpotifyAction::Status => {
let st = client.spotify().status().await.map_err(|e| e.to_string())?;
Ok(format_spotify_status(&st))
}
SpotifyAction::Sync => client
.spotify()
.sync()
.await
.map(|()| "spotify playlists synced".to_string())
.map_err(|e| e.to_string()),
},
}
});
match result {
Ok(msg) => println!("{msg}"),
Err(e) => {
eprintln!("error: {e}");
std::process::exit(1);
}
}
}
fn open_config_in_editor() -> Result<(), String> {
let path = crate::app::ensure_prefs_file();
let editor = pick_editor().ok_or_else(|| {
format!(
"no editor found: set $VISUAL or $EDITOR to open {}",
path.display()
)
})?;
let program = editor[0].clone();
let args = &editor[1..];
let status = std::process::Command::new(&program)
.args(args)
.arg(&path)
.status()
.map_err(|e| format!("failed to launch editor `{program}`: {e}"))?;
if status.success() {
println!("Opened config at {}", path.display());
Ok(())
} else {
Err(format!("editor `{program}` exited with status {status}"))
}
}
fn pick_editor() -> Option<Vec<String>> {
for var in ["VISUAL", "EDITOR"] {
if let Ok(val) = std::env::var(var) {
let parts: Vec<String> = val.split_whitespace().map(String::from).collect();
if let Some(program) = parts.first()
&& command_exists(program)
{
return Some(parts);
}
}
}
for name in ["vim", "nvim", "vi", "nano", "micro", "emacs", "ed"] {
if command_exists(name) {
return Some(vec![name.to_string()]);
}
}
None
}
fn command_exists(name: &str) -> bool {
std::env::var_os("PATH")
.map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(name).is_file()))
.unwrap_or(false)
}
fn format_spotify_status(st: >m_core::spotify::SpotifyStatus) -> String {
let mut out = if st.linked {
format!("Linked as {}", st.user.as_deref().unwrap_or("(unknown)"))
} else {
"Disconnected".to_string()
};
if let Some(dev) = st.device.as_deref().filter(|d| !d.is_empty()) {
out += &format!(" | device: {dev}");
}
if st.linked {
if st.premium {
out += if st.playing {
" | playing ▶"
} else {
" | paused ❚❚"
};
} else {
out += " | playback control needs Premium";
}
out += &format!(" | {} playlists, {} tracks", st.playlists, st.tracks);
}
if let Some(e) = st.error.as_deref() {
out += &format!(" | error: {e}");
}
out
}