Skip to main content

koan_core/
playlists.rs

1//! Playlists beyond the database: keeping them in step with the server, and
2//! writing them out as files.
3//!
4//! The database module owns what a playlist *is*. This owns what happens to it
5//! next — which is either a Subsonic call or an M3U8 on disk.
6
7use std::io::Write;
8use std::path::{Path, PathBuf};
9
10use crate::config::Config;
11use crate::db::connection::Database;
12use crate::db::queries;
13use crate::helpers::subsonic_client;
14use crate::player::state::SharedPlayerState;
15use crate::remote::client::SubsonicClient;
16
17/// The queue, and the playlist or record it is still exactly.
18///
19/// While the two match, the queue *follows* a playlist: an edit there is an
20/// edit here, quietly. The moment you rearrange the queue yourself, add to it,
21/// or let radio extend it, they stop matching and the playlist becomes a
22/// document you are editing rather than the thing you are listening to.
23///
24/// A record cannot be edited, so locking to one buys no following — only the
25/// ability to say what you are listening to, which is worth saying.
26///
27/// Derived rather than tracked, which is the whole reason it is simple. There
28/// is no flag to keep in sync, nothing to persist and nothing to migrate — and
29/// it cannot get stuck, because a queue that stops matching stops being locked
30/// and one that happens to match again is locked again. Playing a playlist
31/// shuffled scrambles the order on purpose, so that queue is not locked, which
32/// is the right answer rather than a special case.
33pub fn queue_lock(db: &Database, state: &SharedPlayerState) -> Option<QueueLock> {
34    let (items, _) = state.snapshot_playlist();
35    if items.is_empty() {
36        return None;
37    }
38
39    // Every item has to have come from the same playlist. One that did not —
40    // played next, dropped in, found by radio — is the queue having diverged.
41    let entry_ids: Vec<i64> = items.iter().filter_map(|i| i.playlist_entry_id).collect();
42    if entry_ids.len() == items.len()
43        && let Ok(Some(playlist_id)) = queries::playlist_of_entry(&db.conn, entry_ids[0])
44        && queries::playlist_entry_ids(&db.conn, playlist_id).is_ok_and(|ids| ids == entry_ids)
45    {
46        return Some(QueueLock::Playlist(playlist_id));
47    }
48
49    // A record needs no provenance of its own: an album *is* an ordered set of
50    // tracks in the library, so the queue being that album is a question about
51    // the tracks it holds. Which means this works for a queue restored from a
52    // previous session, where nothing remembers where it came from.
53    let track_ids: Vec<i64> = items.iter().filter_map(|i| i.db_id).collect();
54    if track_ids.len() != items.len() {
55        return None;
56    }
57    let album_id = queries::get_track_row(&db.conn, track_ids[0])
58        .ok()
59        .flatten()?
60        .album_id?;
61    let album: Vec<i64> = queries::tracks_for_album(&db.conn, album_id)
62        .ok()?
63        .into_iter()
64        .map(|t| t.id)
65        .collect();
66    (album == track_ids).then_some(QueueLock::Album(album_id))
67}
68
69/// What the queue still is, when it is still something.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum QueueLock {
72    Playlist(i64),
73    Album(i64),
74}
75
76/// What a reconciliation did.
77#[derive(Debug, Default, Clone, Copy)]
78pub struct PlaylistSync {
79    /// Playlists taken from the server, new or updated.
80    pub pulled: usize,
81    /// Playlists sent to the server, new or updated.
82    pub pushed: usize,
83}
84
85/// Reconcile playlists with the server, both directions.
86///
87/// Unlike favourites, a playlist has an order and a server that records when it
88/// last changed — so this is last-writer-wins on `changed`, not a union. Local
89/// edits push the moment they happen, so a local copy ahead of the server's
90/// means a push that never got out (koan was offline, the server was down), and
91/// that is exactly the case where ours should win.
92///
93/// Playlists that have never been to the server are created there. Ones the
94/// server no longer has are dropped locally: deleting a playlist on Navidrome
95/// and having it reappear on the next sync would make deletion impossible.
96pub fn reconcile_playlists(db: &Database, client: &SubsonicClient, username: &str) -> PlaylistSync {
97    let mut out = PlaylistSync::default();
98
99    let remote = match client.get_playlists() {
100        Ok(lists) => lists,
101        Err(e) => {
102            log::warn!("could not fetch playlists from the server: {e}");
103            return out;
104        }
105    };
106
107    // Only playlists this user owns are ours to write back. A public playlist
108    // belonging to someone else is still worth having locally, but pushing our
109    // copy of it would be editing their playlist.
110    let mut seen_remote_ids = Vec::new();
111
112    for summary in &remote {
113        seen_remote_ids.push(summary.id.clone());
114        let local = queries::playlist_by_remote_id(&db.conn, &summary.id)
115            .ok()
116            .flatten();
117        let ours = summary
118            .owner
119            .as_deref()
120            .is_none_or(|owner| owner == username);
121
122        if let Some(local) = &local
123            && ours
124            && newer(&local.changed_at, summary.changed.as_deref())
125        {
126            if push(db, client, local.id, Some(&summary.id)).is_ok() {
127                out.pushed += 1;
128            }
129            continue;
130        }
131
132        let full = match client.get_playlist(&summary.id) {
133            Ok(full) => full,
134            Err(e) => {
135                log::warn!("could not fetch playlist {}: {e}", summary.id);
136                continue;
137            }
138        };
139
140        let id = match local {
141            Some(local) => local.id,
142            None => {
143                match queries::create_playlist(&db.conn, &summary.name, summary.comment.as_deref())
144                {
145                    Ok(id) => id,
146                    Err(e) => {
147                        log::warn!("could not store playlist {}: {e}", summary.name);
148                        continue;
149                    }
150                }
151            }
152        };
153
154        let _ = queries::rename_playlist(&db.conn, id, &summary.name);
155        let _ = queries::set_playlist_remote(
156            &db.conn,
157            id,
158            &summary.id,
159            summary.owner.as_deref(),
160            summary.public,
161            summary.changed.as_deref(),
162        );
163
164        let remote_song_ids: Vec<String> = full.entry.iter().map(|s| s.id.clone()).collect();
165        let track_ids: Vec<i64> = queries::track_ids_for_remote_ids(&db.conn, &remote_song_ids)
166            .unwrap_or_default()
167            .into_iter()
168            .flatten()
169            .collect();
170        if let Err(e) = queries::set_playlist_tracks(&db.conn, id, &track_ids) {
171            log::warn!(
172                "could not store playlist contents for {}: {e}",
173                summary.name
174            );
175            continue;
176        }
177        // `set_playlist_tracks` stamps the local copy as changed, which would
178        // make the next sync think we were ahead of the server. We are not:
179        // this *is* the server's copy.
180        let _ = queries::set_playlist_remote(
181            &db.conn,
182            id,
183            &summary.id,
184            summary.owner.as_deref(),
185            summary.public,
186            summary.changed.as_deref(),
187        );
188        out.pulled += 1;
189    }
190
191    // A playlist we hold a server id for that the server no longer lists was
192    // deleted there.
193    for local in queries::list_playlists(&db.conn).unwrap_or_default() {
194        if let Some(remote_id) = &local.remote_id
195            && !seen_remote_ids.contains(remote_id)
196        {
197            let _ = queries::delete_playlist(&db.conn, local.id);
198        }
199    }
200
201    for local in queries::playlists_without_remote(&db.conn).unwrap_or_default() {
202        if push(db, client, local.id, None).is_ok() {
203            out.pushed += 1;
204        }
205    }
206
207    out
208}
209
210/// Send a playlist's name and contents to the server, in order.
211///
212/// `createPlaylist` with a `playlistId` replaces the contents wholesale, which
213/// is the only Subsonic call that can express a reorder — so a push is always
214/// the whole list rather than a diff.
215fn push(
216    db: &Database,
217    client: &SubsonicClient,
218    id: i64,
219    remote_id: Option<&str>,
220) -> Result<(), ()> {
221    let Ok(Some(local)) = queries::get_playlist(&db.conn, id) else {
222        return Err(());
223    };
224    let song_ids = queries::remote_ids_for_playlist(&db.conn, id).unwrap_or_default();
225
226    // A playlist made entirely of local files has nothing the server could
227    // point at. Creating an empty one there would be worse than not creating it.
228    if remote_id.is_none() && song_ids.is_empty() {
229        return Err(());
230    }
231
232    // The name has to travel on its own. Navidrome's `createPlaylist` with a
233    // `playlistId` replaces the songs and ignores the `name` it is handed, so a
234    // rename pushed that way reached the server and changed nothing — which is
235    // exactly what it looked like from the outside. `updatePlaylist` is the
236    // call that carries metadata; `createPlaylist` is the one that carries
237    // order. A push needs both.
238    if let Some(remote_id) = remote_id
239        && let Err(e) = client.update_playlist(
240            remote_id,
241            Some(&local.name),
242            local.comment.as_deref(),
243            Some(local.public),
244        )
245    {
246        log::warn!(
247            "could not rename playlist '{}' on the server: {e}",
248            local.name
249        );
250    }
251
252    match client.create_playlist(remote_id, &local.name, &song_ids) {
253        Ok(created) => {
254            let new_id = created
255                .as_ref()
256                .map(|c| c.playlist.id.clone())
257                .or_else(|| remote_id.map(str::to_string));
258            if let Some(new_id) = new_id {
259                let changed = created.as_ref().and_then(|c| c.playlist.changed.clone());
260                let owner = created.as_ref().and_then(|c| c.playlist.owner.clone());
261                let _ = queries::set_playlist_remote(
262                    &db.conn,
263                    id,
264                    &new_id,
265                    owner.as_deref(),
266                    local.public,
267                    changed.as_deref(),
268                );
269            }
270            Ok(())
271        }
272        Err(e) => {
273            log::warn!(
274                "could not push playlist '{}' to the server: {e}",
275                local.name
276            );
277            Err(())
278        }
279    }
280}
281
282/// Whether `local` was changed after the server's copy was.
283///
284/// Both are ISO 8601 in UTC — SQLite's `datetime('now')` on our side, the
285/// server's own stamp on theirs — near enough that comparing the digits works,
286/// once SQLite's space is made a `T`. A server that sends no timestamp at all
287/// cannot be shown to be newer, so ours wins and the push settles it.
288fn newer(local: &str, remote: Option<&str>) -> bool {
289    let Some(remote) = remote else { return true };
290    let normalise = |s: &str| s.replace(' ', "T").trim_end_matches('Z').to_string();
291    normalise(local) > normalise(remote)
292}
293
294/// Push a playlist to the server in the background, if there is one.
295///
296/// Fire and forget on its own thread, the way favourites are: the local copy is
297/// already written, and a slow server should not hold up the edit that caused
298/// this. A failure leaves the local copy newer than the server's, which is
299/// exactly what [`reconcile_playlists`] resolves on the next sync.
300///
301/// The thread opens its own database handle rather than borrowing the caller's:
302/// a `rusqlite::Connection` is neither `Send` nor `Sync`, and the answer has to
303/// be written back — the new server id — so it needs one of its own.
304pub fn push_to_remote(id: i64) {
305    let cfg = Config::load().unwrap_or_default();
306    if !cfg.remote.enabled {
307        return;
308    }
309    let Some(client) = subsonic_client(&cfg) else {
310        return;
311    };
312    std::thread::Builder::new()
313        .name("koan-playlist-sync".into())
314        .spawn(move || {
315            let Ok(db) = Database::open_default() else {
316                return;
317            };
318            let remote_id = queries::get_playlist(&db.conn, id)
319                .ok()
320                .flatten()
321                .and_then(|p| p.remote_id);
322            let _ = push(&db, &client, id, remote_id.as_deref());
323        })
324        .ok();
325}
326
327/// Delete a playlist on the server. Nothing to do for one that never went.
328pub fn delete_on_remote(remote_id: String) {
329    let cfg = Config::load().unwrap_or_default();
330    if !cfg.remote.enabled {
331        return;
332    }
333    let Some(client) = subsonic_client(&cfg) else {
334        return;
335    };
336    std::thread::Builder::new()
337        .name("koan-playlist-sync".into())
338        .spawn(move || {
339            if let Err(e) = client.delete_playlist(&remote_id) {
340                log::warn!("could not delete playlist {remote_id} on the server: {e}");
341            }
342        })
343        .ok();
344}
345
346/// What an export wrote, and what it could not.
347#[derive(Debug, Default, Clone, Copy)]
348pub struct ExportSummary {
349    pub written: usize,
350    /// Tracks with no file on this machine. A playlist file is a list of
351    /// paths, and a remote track that has never been downloaded has none.
352    pub skipped: usize,
353}
354
355/// Write a playlist as an extended M3U8.
356///
357/// Absolute paths, UTF-8, `#EXTINF` per entry — the format every player still
358/// reads. Remote tracks that have not been downloaded are left out rather than
359/// written as stream URLs: a Subsonic stream URL carries the credentials that
360/// authorise it, and a playlist file is something people mail to each other.
361pub fn export_m3u8(
362    db: &Database,
363    playlist_id: i64,
364    dest: &Path,
365) -> Result<ExportSummary, std::io::Error> {
366    let name = queries::get_playlist(&db.conn, playlist_id)
367        .ok()
368        .flatten()
369        .map(|p| p.name)
370        .unwrap_or_default();
371    let tracks = queries::playlist_tracks(&db.conn, playlist_id).unwrap_or_default();
372
373    let mut out = ExportSummary::default();
374    let mut file = std::fs::File::create(dest)?;
375    writeln!(file, "#EXTM3U")?;
376    if !name.is_empty() {
377        writeln!(file, "#PLAYLIST:{name}")?;
378    }
379
380    for track in &tracks {
381        let path = track
382            .path
383            .as_deref()
384            .or(track.cached_path.as_deref())
385            .map(PathBuf::from)
386            .filter(|p| p.exists());
387        let Some(path) = path else {
388            out.skipped += 1;
389            continue;
390        };
391        let seconds = track.duration_ms.unwrap_or(0) / 1000;
392        writeln!(
393            file,
394            "#EXTINF:{seconds},{} - {}",
395            track.artist_name, track.title
396        )?;
397        writeln!(file, "{}", path.display())?;
398        out.written += 1;
399    }
400
401    Ok(out)
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407    use crate::db::queries::{TrackMeta, upsert_track};
408
409    fn meta(title: &str, path: &Path) -> TrackMeta {
410        TrackMeta {
411            title: title.into(),
412            artist: "Artist".into(),
413            album_artist: Some("Artist".into()),
414            album: "Album".into(),
415            date: None,
416            disc: None,
417            track_number: None,
418            genre: None,
419            label: None,
420            duration_ms: Some(185_000),
421            codec: Some("FLAC".into()),
422            sample_rate: None,
423            bit_depth: None,
424            channels: None,
425            bitrate: None,
426            size_bytes: None,
427            mtime: None,
428            path: Some(path.to_string_lossy().into_owned()),
429            source: "local".into(),
430            remote_id: None,
431            remote_url: None,
432            album_remote_id: None,
433            artist_remote_id: None,
434            mbid: None,
435            album_added_at: None,
436        }
437    }
438
439    /// The queue is locked while it is still exactly the playlist, and stops
440    /// being the moment it is not. Everything else about following follows from
441    /// this one answer.
442    #[test]
443    fn a_queue_is_locked_only_while_it_is_still_the_playlist() {
444        use crate::player::state::{LoadState, PlaylistItem, QueueItemId, SharedPlayerState};
445
446        let dir = tempfile::tempdir().unwrap();
447        let db = Database::open(&dir.path().join("koan.db")).unwrap();
448        let a = upsert_track(&db.conn, &meta("A", &dir.path().join("a.flac"))).unwrap();
449        let b = upsert_track(&db.conn, &meta("B", &dir.path().join("b.flac"))).unwrap();
450
451        let id = queries::create_playlist(&db.conn, "Evening", None).unwrap();
452        let entries = queries::add_tracks(&db.conn, id, &[a, b]).unwrap();
453
454        let state = SharedPlayerState::new();
455        let queued = |entry: Option<i64>| PlaylistItem {
456            id: QueueItemId::new(),
457            db_id: Some(a),
458            playlist_entry_id: entry,
459            path: dir.path().join("a.flac"),
460            title: "A".into(),
461            artist: "Artist".into(),
462            album_artist: "Artist".into(),
463            album: "Album".into(),
464            year: None,
465            codec: None,
466            track_number: None,
467            disc: None,
468            duration_ms: None,
469            load_state: LoadState::Ready,
470        };
471
472        assert_eq!(
473            queue_lock(&db, &state),
474            None,
475            "an empty queue is not locked"
476        );
477
478        state.add_items(vec![queued(Some(entries[0])), queued(Some(entries[1]))]);
479        assert_eq!(
480            queue_lock(&db, &state),
481            Some(QueueLock::Playlist(id)),
482            "the queue is the playlist"
483        );
484
485        // Something that never came from the playlist — played next, dropped
486        // in, found by radio.
487        state.add_items(vec![queued(None)]);
488        assert_eq!(queue_lock(&db, &state), None);
489    }
490
491    /// Reordering the queue by hand ends the lock, which is the whole point of
492    /// deriving it: there is no flag anyone has to remember to clear.
493    #[test]
494    fn rearranging_the_queue_ends_the_lock() {
495        use crate::player::state::{LoadState, PlaylistItem, QueueItemId, SharedPlayerState};
496
497        let dir = tempfile::tempdir().unwrap();
498        let db = Database::open(&dir.path().join("koan.db")).unwrap();
499        let a = upsert_track(&db.conn, &meta("A", &dir.path().join("a.flac"))).unwrap();
500        let b = upsert_track(&db.conn, &meta("B", &dir.path().join("b.flac"))).unwrap();
501        let id = queries::create_playlist(&db.conn, "Evening", None).unwrap();
502        let entries = queries::add_tracks(&db.conn, id, &[a, b]).unwrap();
503
504        let state = SharedPlayerState::new();
505        let items: Vec<PlaylistItem> = entries
506            .iter()
507            .map(|entry| PlaylistItem {
508                id: QueueItemId::new(),
509                db_id: Some(a),
510                playlist_entry_id: Some(*entry),
511                path: dir.path().join("a.flac"),
512                title: "A".into(),
513                artist: "Artist".into(),
514                album_artist: "Artist".into(),
515                album: "Album".into(),
516                year: None,
517                codec: None,
518                track_number: None,
519                disc: None,
520                duration_ms: None,
521                load_state: LoadState::Ready,
522            })
523            .collect();
524        let ids: Vec<QueueItemId> = items.iter().map(|i| i.id).collect();
525        state.add_items(items);
526        assert_eq!(queue_lock(&db, &state), Some(QueueLock::Playlist(id)));
527
528        state.reorder_to(&[ids[1], ids[0]]);
529        assert_eq!(
530            queue_lock(&db, &state),
531            None,
532            "same tracks, different order — no longer the playlist"
533        );
534
535        // And the playlist catching up locks it again. Nothing had to be reset.
536        queries::reorder_entries(&db.conn, id, &[entries[1], entries[0]]).unwrap();
537        assert_eq!(queue_lock(&db, &state), Some(QueueLock::Playlist(id)));
538    }
539
540    /// A record needs no provenance: it *is* an ordered set of tracks, so the
541    /// queue being that record is a question about what the queue holds. Which
542    /// is why it survives a relaunch, where nothing remembers what was played.
543    #[test]
544    fn a_queue_holding_exactly_one_record_is_locked_to_it() {
545        use crate::player::state::{LoadState, PlaylistItem, QueueItemId, SharedPlayerState};
546
547        let dir = tempfile::tempdir().unwrap();
548        let db = Database::open(&dir.path().join("koan.db")).unwrap();
549        let a = upsert_track(&db.conn, &meta("A", &dir.path().join("a.flac"))).unwrap();
550        let b = upsert_track(&db.conn, &meta("B", &dir.path().join("b.flac"))).unwrap();
551        let album_id = queries::get_track_row(&db.conn, a)
552            .unwrap()
553            .unwrap()
554            .album_id
555            .unwrap();
556
557        let state = SharedPlayerState::new();
558        let queued = |track: i64| PlaylistItem {
559            id: QueueItemId::new(),
560            db_id: Some(track),
561            playlist_entry_id: None,
562            path: dir.path().join("a.flac"),
563            title: "A".into(),
564            artist: "Artist".into(),
565            album_artist: "Artist".into(),
566            album: "Album".into(),
567            year: None,
568            codec: None,
569            track_number: None,
570            disc: None,
571            duration_ms: None,
572            load_state: LoadState::Ready,
573        };
574
575        state.add_items(vec![queued(a)]);
576        assert_eq!(
577            queue_lock(&db, &state),
578            None,
579            "half a record is not the record"
580        );
581
582        state.add_items(vec![queued(b)]);
583        assert_eq!(queue_lock(&db, &state), Some(QueueLock::Album(album_id)));
584    }
585
586    #[test]
587    fn export_writes_what_is_on_disk_and_counts_what_is_not() {
588        let dir = tempfile::tempdir().unwrap();
589        let db = Database::open(&dir.path().join("koan.db")).unwrap();
590
591        let present = dir.path().join("here.flac");
592        std::fs::write(&present, b"x").unwrap();
593        let here = upsert_track(&db.conn, &meta("Here", &present)).unwrap();
594        let gone = upsert_track(&db.conn, &meta("Gone", &dir.path().join("gone.flac"))).unwrap();
595
596        let id = queries::create_playlist(&db.conn, "Evening", None).unwrap();
597        queries::add_tracks(&db.conn, id, &[here, gone]).unwrap();
598
599        let dest = dir.path().join("evening.m3u8");
600        let summary = export_m3u8(&db, id, &dest).unwrap();
601        assert_eq!((summary.written, summary.skipped), (1, 1));
602
603        let written = std::fs::read_to_string(&dest).unwrap();
604        assert!(written.starts_with("#EXTM3U\n#PLAYLIST:Evening\n"));
605        assert!(written.contains("#EXTINF:185,Artist - Here"));
606        assert!(written.contains(&present.display().to_string()));
607        assert!(!written.contains("gone.flac"));
608    }
609}