koan-server 0.23.2

GraphQL, Subsonic REST, and MCP server for koan music player.
Documentation
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
use async_graphql::connection::{DisableNodesField, EmptyFields};
use async_graphql::{Context, Enum, InputObject, Object, SimpleObject};
use koan_core::db::queries;

use super::DbHandle;
use super::helpers::paginate;

/// Connection type alias — standard async-graphql Connection with `nodes` field disabled.
/// Exposes `edges` + `pageInfo` only (proper Relay spec).
pub(super) type Conn<T> = async_graphql::connection::Connection<
    usize,
    T,
    EmptyFields,
    EmptyFields,
    async_graphql::connection::DefaultConnectionName,
    async_graphql::connection::DefaultEdgeName,
    DisableNodesField,
>;

// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum PlaybackStateEnum {
    Stopped,
    Playing,
    Paused,
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum TrackSource {
    Local,
    Remote,
    Cached,
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum ArtistSortField {
    Name,
    TrackCount,
    AlbumCount,
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum AlbumSortField {
    Title,
    Date,
    ArtistThenDate,
    TrackCount,
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum TrackSortField {
    Title,
    Artist,
    Album,
    Duration,
    ArtistAlbumDiscTrack,
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum SortDirection {
    Asc,
    Desc,
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum FuzzySearchKind {
    Track,
    Album,
    Artist,
}

/// Queue entry status — mirrors `QueueEntryStatus` from koan-core.
/// Derived from cursor position + load state.
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(super) enum GqlQueueEntryStatus {
    /// After the cursor — waiting to play.
    Queued,
    /// At the cursor and loaded — currently playing.
    Playing,
    /// Before the cursor — already played.
    Played,
    /// Downloading (not at cursor).
    Downloading,
    /// At the cursor but not yet loaded — priority pending.
    PriorityPending,
    /// Download or load failed.
    Failed,
}

// ---------------------------------------------------------------------------
// GraphQL types
// ---------------------------------------------------------------------------

pub(super) struct GqlArtist {
    pub row: queries::ArtistRow,
}

#[Object(name = "Artist")]
impl GqlArtist {
    async fn id(&self) -> i64 {
        self.row.id
    }

    async fn name(&self) -> &str {
        &self.row.name
    }

    async fn albums(
        &self,
        ctx: &Context<'_>,
        after: Option<String>,
        first: Option<i32>,
    ) -> async_graphql::Result<Conn<GqlAlbum>> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let all = queries::albums_for_artist(&db.conn, self.row.id)
            .map_err(|e| async_graphql::Error::new(format!("db error: {}", e)))?;
        paginate(
            all.into_iter().map(|row| GqlAlbum { row }).collect(),
            after,
            first,
        )
    }

    async fn tracks(
        &self,
        ctx: &Context<'_>,
        after: Option<String>,
        first: Option<i32>,
    ) -> async_graphql::Result<Conn<GqlTrack>> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let all = queries::tracks_for_artist(&db.conn, self.row.id)
            .map_err(|e| async_graphql::Error::new(format!("db error: {}", e)))?;
        paginate(
            all.into_iter().map(|row| GqlTrack { row }).collect(),
            after,
            first,
        )
    }

    async fn album_count(&self, ctx: &Context<'_>) -> async_graphql::Result<i32> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let albums = queries::albums_for_artist(&db.conn, self.row.id)
            .map_err(|e| async_graphql::Error::new(format!("db error: {}", e)))?;
        Ok(albums.len() as i32)
    }

    async fn track_count(&self, ctx: &Context<'_>) -> async_graphql::Result<i32> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let tracks = queries::tracks_for_artist(&db.conn, self.row.id)
            .map_err(|e| async_graphql::Error::new(format!("db error: {}", e)))?;
        Ok(tracks.len() as i32)
    }
}

pub(super) struct GqlAlbum {
    pub row: queries::AlbumRow,
}

#[Object(name = "Album")]
impl GqlAlbum {
    async fn id(&self) -> i64 {
        self.row.id
    }

    async fn title(&self) -> &str {
        &self.row.title
    }

    async fn artist_id(&self) -> i64 {
        self.row.artist_id
    }

    async fn artist_name(&self) -> &str {
        &self.row.artist_name
    }

    async fn date(&self) -> Option<&str> {
        self.row.date.as_deref()
    }

    async fn codec(&self) -> Option<&str> {
        self.row.codec.as_deref()
    }

    async fn label(&self) -> Option<&str> {
        self.row.label.as_deref()
    }

    async fn disc_count(&self) -> Option<i32> {
        self.row.total_discs
    }

    async fn tracks(
        &self,
        ctx: &Context<'_>,
        after: Option<String>,
        first: Option<i32>,
    ) -> async_graphql::Result<Conn<GqlTrack>> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let all = queries::tracks_for_album(&db.conn, self.row.id)
            .map_err(|e| async_graphql::Error::new(format!("db error: {}", e)))?;
        paginate(
            all.into_iter().map(|row| GqlTrack { row }).collect(),
            after,
            first,
        )
    }

    async fn track_count(&self, ctx: &Context<'_>) -> async_graphql::Result<i32> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let tracks = queries::tracks_for_album(&db.conn, self.row.id)
            .map_err(|e| async_graphql::Error::new(format!("db error: {}", e)))?;
        Ok(tracks.len() as i32)
    }

    async fn total_duration_ms(&self, ctx: &Context<'_>) -> async_graphql::Result<i64> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let tracks = queries::tracks_for_album(&db.conn, self.row.id)
            .map_err(|e| async_graphql::Error::new(format!("db error: {}", e)))?;
        Ok(tracks.iter().filter_map(|t| t.duration_ms).sum())
    }
}

pub(super) struct GqlTrack {
    pub row: queries::TrackRow,
}

#[Object(name = "Track")]
impl GqlTrack {
    async fn id(&self) -> i64 {
        self.row.id
    }

    async fn title(&self) -> &str {
        &self.row.title
    }

    async fn artist(&self) -> &str {
        &self.row.artist_name
    }

    async fn album_artist(&self) -> &str {
        &self.row.album_artist_name
    }

    async fn album(&self) -> &str {
        &self.row.album_title
    }

    async fn album_id(&self) -> Option<i64> {
        self.row.album_id
    }

    async fn artist_id(&self) -> Option<i64> {
        self.row.artist_id
    }

    async fn disc(&self) -> Option<i32> {
        self.row.disc
    }

    async fn track_number(&self) -> Option<i32> {
        self.row.track_number
    }

    async fn duration_ms(&self) -> Option<i64> {
        self.row.duration_ms
    }

    async fn codec(&self) -> Option<&str> {
        self.row.codec.as_deref()
    }

    async fn sample_rate(&self) -> Option<i32> {
        self.row.sample_rate
    }

    async fn bit_depth(&self) -> Option<i32> {
        self.row.bit_depth
    }

    async fn channels(&self) -> Option<i32> {
        self.row.channels
    }

    async fn bitrate(&self) -> Option<i32> {
        self.row.bitrate
    }

    async fn genre(&self) -> Option<&str> {
        self.row.genre.as_deref()
    }

    async fn source(&self) -> TrackSource {
        match self.row.source.as_str() {
            "local" => TrackSource::Local,
            "cached" => TrackSource::Cached,
            _ => TrackSource::Remote,
        }
    }

    async fn remote_id(&self) -> Option<&str> {
        self.row.remote_id.as_deref()
    }

    async fn path(&self) -> Option<&str> {
        self.row.path.as_deref()
    }

    async fn cached_path(&self) -> Option<&str> {
        self.row.cached_path.as_deref()
    }

    async fn is_favourite(&self, ctx: &Context<'_>) -> async_graphql::Result<bool> {
        let db = ctx.data::<DbHandle>()?.open()?;
        let favs = queries::load_favourites(&db.conn)
            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
        let path = self
            .row
            .path
            .as_ref()
            .or(self.row.cached_path.as_ref())
            .map(std::path::PathBuf::from);
        Ok(path.map(|p| favs.contains(&p)).unwrap_or(false))
    }
}

#[derive(SimpleObject)]
#[graphql(name = "NowPlaying")]
pub(super) struct GqlNowPlaying {
    pub state: PlaybackStateEnum,
    pub position_ms: u64,
    pub duration_ms: Option<u64>,
    pub track: Option<GqlNowPlayingTrack>,
    pub queue_item_id: Option<String>,
}

#[derive(SimpleObject)]
#[graphql(name = "NowPlayingTrack")]
pub(super) struct GqlNowPlayingTrack {
    pub title: String,
    pub artist: String,
    pub album: String,
    pub codec: String,
    pub sample_rate: u32,
    pub bit_depth: Option<u16>,
    pub bitrate_kbps: Option<u32>,
    pub channels: u16,
    pub duration_ms: u64,
}

pub(super) struct GqlQueueEntry {
    pub queue_item_id: String,
    pub title: String,
    pub artist: String,
    pub album: String,
    pub codec: Option<String>,
    pub track_number: Option<i64>,
    pub disc: Option<i64>,
    pub duration_ms: Option<u64>,
    pub is_current: bool,
    pub status: GqlQueueEntryStatus,
    pub download_progress: Option<GqlDownloadProgress>,
}

#[Object(name = "QueueEntry")]
impl GqlQueueEntry {
    async fn queue_item_id(&self) -> &str {
        &self.queue_item_id
    }

    async fn title(&self) -> &str {
        &self.title
    }

    async fn artist(&self) -> &str {
        &self.artist
    }

    async fn album(&self) -> &str {
        &self.album
    }

    async fn codec(&self) -> Option<&str> {
        self.codec.as_deref()
    }

    async fn track_number(&self) -> Option<i64> {
        self.track_number
    }

    async fn disc(&self) -> Option<i64> {
        self.disc
    }

    async fn duration_ms(&self) -> Option<u64> {
        self.duration_ms
    }

    async fn is_current(&self) -> bool {
        self.is_current
    }

    /// Derived status: Queued, Playing, Played, Downloading, PriorityPending, Failed.
    async fn status(&self) -> GqlQueueEntryStatus {
        self.status
    }

    /// Download progress — present only when the track is being downloaded.
    async fn download_progress(&self) -> Option<&GqlDownloadProgress> {
        self.download_progress.as_ref()
    }
}

#[derive(SimpleObject)]
#[graphql(name = "LibraryStats")]
pub(super) struct GqlLibraryStats {
    pub total_tracks: i64,
    pub local_tracks: i64,
    pub remote_tracks: i64,
    pub cached_tracks: i64,
    pub total_albums: i64,
    pub total_artists: i64,
}

#[derive(SimpleObject)]
#[graphql(name = "Device")]
pub(super) struct GqlDevice {
    pub name: String,
    pub sample_rates: Vec<f64>,
}

#[derive(SimpleObject)]
#[graphql(name = "SimilarArtist")]
pub(super) struct GqlSimilarArtist {
    pub artist: GqlSimilarArtistInfo,
    pub score: f64,
    pub source: String,
    pub relationship: String,
}

#[derive(SimpleObject)]
#[graphql(name = "SimilarArtistInfo")]
pub(super) struct GqlSimilarArtistInfo {
    pub id: i64,
    pub name: String,
}

#[derive(SimpleObject)]
#[graphql(name = "PlayHistoryEntry")]
pub(super) struct GqlPlayHistoryEntry {
    pub track_id: i64,
    pub played_at: i64,
    pub duration_ms: Option<i64>,
    pub track: Option<GqlPlayHistoryTrack>,
}

#[derive(SimpleObject)]
#[graphql(name = "PlayHistoryTrack")]
pub(super) struct GqlPlayHistoryTrack {
    pub title: String,
    pub artist: String,
    pub album: String,
}

#[derive(SimpleObject)]
#[graphql(name = "Snapshot")]
pub(super) struct GqlSnapshot {
    pub name: String,
    pub track_count: i32,
    pub position_ms: u64,
    pub created_at: String,
}

#[derive(SimpleObject)]
#[graphql(name = "RadioStatus")]
pub(super) struct GqlRadioStatus {
    pub enabled: bool,
}

#[derive(SimpleObject)]
#[graphql(name = "FuzzyMatch")]
pub(super) struct GqlFuzzyMatch {
    pub id: i64,
    pub name: String,
    pub rank: i32,
    pub kind: FuzzySearchKind,
}

#[derive(SimpleObject)]
#[graphql(name = "Lyrics")]
pub(super) struct GqlLyrics {
    pub content: String,
    pub synced: bool,
    pub source: String,
}

#[derive(SimpleObject)]
#[graphql(name = "CoverArt")]
pub(super) struct GqlCoverArt {
    pub data_base64: String,
    pub mime: String,
}

#[derive(SimpleObject)]
#[graphql(name = "OrganizePreview")]
pub(super) struct GqlOrganizePreview {
    pub moves: Vec<GqlFileMove>,
    pub errors: Vec<String>,
    pub skipped: i32,
}

#[derive(SimpleObject)]
#[graphql(name = "FileMove")]
pub(super) struct GqlFileMove {
    pub track_id: i64,
    pub from_path: String,
    pub to_path: String,
}

#[derive(SimpleObject)]
#[graphql(name = "OrganizeResult")]
pub(super) struct GqlOrganizeResult {
    pub moved_count: i32,
    pub errors: Vec<String>,
    pub skipped: i32,
}

#[derive(SimpleObject)]
#[graphql(name = "ScanResult")]
pub(super) struct GqlScanResult {
    pub tracks_added: i64,
    pub tracks_updated: i64,
    pub tracks_unchanged: i64,
}

#[derive(SimpleObject)]
#[graphql(name = "Share")]
pub(super) struct GqlShare {
    pub url: Option<String>,
    pub id: String,
}

pub(super) struct GqlSimilarTrack {
    pub row: queries::TrackRow,
    pub distance: f64,
}

#[Object(name = "SimilarTrack")]
impl GqlSimilarTrack {
    async fn track_id(&self) -> i64 {
        self.row.id
    }

    async fn title(&self) -> &str {
        &self.row.title
    }

    async fn artist(&self) -> &str {
        &self.row.artist_name
    }

    async fn album(&self) -> &str {
        &self.row.album_title
    }

    async fn distance(&self) -> f64 {
        self.distance
    }

    async fn duration_ms(&self) -> Option<i64> {
        self.row.duration_ms
    }

    async fn genre(&self) -> Option<&str> {
        self.row.genre.as_deref()
    }
}

/// Mutation/query result status.
pub(super) struct GqlStatus {
    pub success: bool,
    pub message: String,
}

#[Object(name = "Status")]
impl GqlStatus {
    async fn ok(&self) -> bool {
        self.success
    }

    async fn message(&self) -> &str {
        &self.message
    }
}

impl GqlStatus {
    pub fn success(msg: impl Into<String>) -> Self {
        Self {
            success: true,
            message: msg.into(),
        }
    }
}

/// Download progress for a queue entry.
#[derive(SimpleObject, Clone)]
#[graphql(name = "DownloadProgress")]
pub(super) struct GqlDownloadProgress {
    /// Bytes downloaded so far.
    pub downloaded: u64,
    /// Total bytes expected (0 if unknown).
    pub total: u64,
}

/// Queue snapshot with version for change detection.
#[derive(SimpleObject)]
#[graphql(name = "QueueSnapshot")]
pub(super) struct GqlQueueSnapshot {
    /// Monotonically increasing version — changes on every playlist mutation.
    pub version: u64,
    /// Queue entries with derived status.
    pub entries: Vec<GqlQueueEntry>,
    /// Number of entries before the cursor (already played).
    pub finished_count: i32,
    /// Whether any entry is currently playing.
    pub has_playing: bool,
    /// Number of entries after the cursor (queued).
    pub queue_count: i32,
}

/// A single frame of visualizer data.
#[derive(SimpleObject, Clone)]
#[graphql(name = "VizFrame")]
pub(super) struct GqlVizFrame {
    /// Spectrum bar heights (0.0..1.0), 48 bars.
    pub spectrum: Vec<f32>,
    /// Peak hold values (slowly decaying maxima), 48 bars.
    pub peaks: Vec<f32>,
    /// RMS VU levels: [left, right], each 0.0..1.0.
    pub vu_levels: Vec<f32>,
    /// Beat energy (0.0..1.0). Spikes on transients.
    pub beat_energy: f32,
    /// Raw waveform samples (interleaved stereo). Empty when disabled or no audio playing.
    /// Opt-in: only populated when the client requests it.
    pub waveform: Vec<f32>,
}

/// Top-level config as exposed via GraphQL.
#[derive(SimpleObject)]
#[graphql(name = "Config")]
pub(super) struct GqlConfig {
    pub library_folders: Vec<String>,
    pub replaygain_mode: String,
    pub pre_amp_db: f64,
    pub output_device: Option<String>,
    pub target_fps: i32,
    pub art_size: i32,
    pub remote_enabled: bool,
    pub remote_url: String,
    pub remote_username: String,
    pub transcode_quality: String,
    pub cache_limit: Option<String>,
    pub visualizer_fps: i32,
    pub radio_enabled: bool,
    pub graphql_port: i32,
    pub graphql_playground: bool,
}

/// Input for updating config fields. All optional — only provided fields are written.
#[derive(InputObject)]
#[graphql(name = "ConfigInput")]
pub(super) struct GqlConfigInput {
    pub library_folders: Option<Vec<String>>,
    pub replaygain_mode: Option<String>,
    pub pre_amp_db: Option<f64>,
    pub output_device: Option<String>,
    pub target_fps: Option<i32>,
    pub art_size: Option<i32>,
    pub remote_enabled: Option<bool>,
    pub remote_url: Option<String>,
    pub remote_username: Option<String>,
    pub transcode_quality: Option<String>,
    pub cache_limit: Option<String>,
    pub visualizer_fps: Option<i32>,
    pub graphql_port: Option<i32>,
    pub graphql_playground: Option<bool>,
}

pub(super) struct GqlQueueMutationResult {
    pub success: bool,
    pub message: String,
    pub added_count: i32,
    pub queue_item_ids: Vec<String>,
}

#[Object(name = "QueueMutationResult")]
impl GqlQueueMutationResult {
    async fn ok(&self) -> bool {
        self.success
    }

    async fn message(&self) -> &str {
        &self.message
    }

    async fn added_count(&self) -> i32 {
        self.added_count
    }

    async fn queue_item_ids(&self) -> &[String] {
        &self.queue_item_ids
    }
}