koan-core 0.65.1

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
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
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
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
//! Playlists beyond the database: keeping them in step with the server, and
//! writing them out as files.
//!
//! The database module owns what a playlist *is*. This owns what happens to it
//! next — which is either a Subsonic call or an M3U8 on disk.

use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::path::{Path, PathBuf};

use crate::config::Config;
use crate::db::connection::{Database, DbError};
use crate::db::queries;
use crate::helpers::subsonic_client;
use crate::player::commands::PlayerCommand;
use crate::player::state::{QueueItemId, SharedPlayerState};
use crate::remote::client::{SubsonicClient, SubsonicError};

/// Each playlist's earlier states, for undo and redo.
///
/// The queue keeps its own (`player::undo`); this is the same for playlists,
/// held by whoever edits them. An edit records the playlist as it was first;
/// undoing puts that back exactly, entry ids included, so a queue following
/// the playlist stays locked to it. Per playlist, so undoing in one never
/// reaches into another, and in memory: it lasts the session, as the queue's
/// does.
#[derive(Default)]
pub struct PlaylistHistory {
    steps: parking_lot::Mutex<HashMap<i64, Steps>>,
}

#[derive(Default)]
struct Steps {
    undo: Vec<Vec<(i64, i64)>>,
    redo: Vec<Vec<(i64, i64)>>,
}

/// How many edits back a playlist can go, as the queue's history.
const HISTORY_DEPTH: usize = 100;

/// A playlist as it was before an edit, recorded once the edit has landed.
pub struct Before {
    id: i64,
    entries: Vec<(i64, i64)>,
}

impl PlaylistHistory {
    /// The playlist as it is now, taken before an edit.
    pub fn before(conn: &rusqlite::Connection, id: i64) -> Result<Before, DbError> {
        Ok(Before {
            id,
            entries: queries::entry_snapshot(conn, id)?,
        })
    }

    /// After an edit has landed: the playlist as it was before. An edit that
    /// failed is never recorded, so undo has nothing to step over. A new edit
    /// forgets what had been undone.
    pub fn record(&self, before: Before) {
        let mut steps = self.steps.lock();
        let steps = steps.entry(before.id).or_default();
        steps.undo.push(before.entries);
        if steps.undo.len() > HISTORY_DEPTH {
            steps.undo.remove(0);
        }
        steps.redo.clear();
    }

    /// Back one edit. Whether there was one.
    pub fn undo(&self, conn: &rusqlite::Connection, id: i64) -> Result<bool, DbError> {
        self.step(conn, id, true)
    }

    /// Forward one undone edit. Whether there was one.
    pub fn redo(&self, conn: &rusqlite::Connection, id: i64) -> Result<bool, DbError> {
        self.step(conn, id, false)
    }

    fn step(&self, conn: &rusqlite::Connection, id: i64, back: bool) -> Result<bool, DbError> {
        let mut all = self.steps.lock();
        let steps = all.entry(id).or_default();
        let target = if back {
            steps.undo.pop()
        } else {
            steps.redo.pop()
        };
        let Some(target) = target else {
            return Ok(false);
        };
        let now = queries::entry_snapshot(conn, id)?;
        queries::restore_entries(conn, id, &target)?;
        if back {
            steps.redo.push(now)
        } else {
            steps.undo.push(now)
        }
        Ok(true)
    }
}

#[cfg(test)]
mod history_tests {
    use super::*;
    use crate::db::queries::{LOCAL_USER, sample_meta, upsert_track};

    #[test]
    fn undo_and_redo_walk_a_playlists_edits() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        conn.pragma_update(None, "foreign_keys", "on").unwrap();
        crate::db::schema::create_tables(&conn).unwrap();
        let (a, b) = (
            upsert_track(&conn, &sample_meta("A", "Artist", "X")).unwrap(),
            upsert_track(&conn, &sample_meta("B", "Artist", "X")).unwrap(),
        );
        let id = queries::create_playlist(&conn, LOCAL_USER, "Mix", None).unwrap();
        let history = PlaylistHistory::default();

        let before = PlaylistHistory::before(&conn, id).unwrap();
        queries::add_tracks(&conn, id, &[a, b]).unwrap();
        history.record(before);
        let full = queries::entry_snapshot(&conn, id).unwrap();
        let before = PlaylistHistory::before(&conn, id).unwrap();
        queries::remove_entries(&conn, id, &[full[0].0]).unwrap();
        history.record(before);

        assert!(history.undo(&conn, id).unwrap());
        assert_eq!(queries::entry_snapshot(&conn, id).unwrap(), full);
        assert!(history.undo(&conn, id).unwrap());
        assert!(queries::entry_snapshot(&conn, id).unwrap().is_empty());
        assert!(!history.undo(&conn, id).unwrap(), "nothing further back");

        assert!(history.redo(&conn, id).unwrap());
        assert_eq!(queries::entry_snapshot(&conn, id).unwrap(), full);
    }
}

/// The queue, and the playlist or record it is still exactly.
///
/// While the two match, the queue *follows* a playlist: an edit there is an
/// edit here, quietly. The moment you rearrange the queue yourself or add to
/// it, they stop matching and the playlist becomes a document you are editing
/// rather than the thing you are listening to.
///
/// A record cannot be edited, so locking to one buys no following — only the
/// ability to say what you are listening to, which is worth saying.
///
/// Derived rather than tracked: there is no flag to keep in sync, nothing to
/// persist and nothing to migrate, and it cannot get stuck, because a queue
/// that stops matching stops being locked and one that happens to match again
/// is locked again. Playing a playlist shuffled scrambles the order on purpose,
/// so that queue is not locked.
pub fn queue_lock(db: &Database, state: &SharedPlayerState) -> Option<QueueLock> {
    let (items, _) = state.snapshot_playlist();
    if items.is_empty() {
        return None;
    }

    // Every item has to have come from the same playlist. One that did not —
    // played next, dropped in — is the queue having diverged.
    let entry_ids: Vec<i64> = items.iter().filter_map(|i| i.playlist_entry_id).collect();
    if entry_ids.len() == items.len()
        && let Ok(Some(playlist_id)) = queries::playlist_of_entry(&db.conn, entry_ids[0])
        && queries::playlist_entry_ids(&db.conn, playlist_id).is_ok_and(|ids| ids == entry_ids)
    {
        return Some(QueueLock::Playlist(playlist_id));
    }

    // A record needs no provenance of its own: an album *is* an ordered set of
    // tracks in the library, so the queue being that album is a question about
    // the tracks it holds. Which means this works for a queue restored from a
    // previous session, where nothing remembers where it came from.
    let track_ids: Vec<i64> = items.iter().filter_map(|i| i.db_id).collect();
    if track_ids.len() != items.len() {
        return None;
    }
    let album_id = queries::get_track_row(&db.conn, track_ids[0])
        .ok()
        .flatten()?
        .album_id?;
    let album: Vec<i64> = queries::tracks_for_album(&db.conn, album_id)
        .ok()?
        .into_iter()
        .map(|t| t.id)
        .collect();
    (album == track_ids).then_some(QueueLock::Album(album_id))
}

/// What the queue still is, when it is still something.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueueLock {
    Playlist(i64),
    Album(i64),
}

/// What a reconciliation did.
#[derive(Debug, Default, Clone, Copy)]
pub struct PlaylistSync {
    /// Playlists taken from the server, new or updated.
    pub pulled: usize,
    /// Playlists sent to the server, new or updated.
    pub pushed: usize,
}

/// Whether the queue is still exactly this playlist.
pub fn locked_to(db: &Database, state: &SharedPlayerState, playlist_id: i64) -> bool {
    queue_lock(db, state) == Some(QueueLock::Playlist(playlist_id))
}

/// Make the queue follow a playlist that has just been edited.
///
/// Only when the queue was still exactly that playlist beforehand —
/// `was_locked` is read *before* the edit lands, because afterwards the two
/// no longer match and every queue would look diverged.
///
/// The edit is applied to the queue rather than the queue being rebuilt
/// from the playlist: entries that survived keep their queue items, and
/// with them their ids, what has played, what is mid-download and what the
/// cursor is pointing at.
pub fn follow_edit(
    db: &Database,
    state: &SharedPlayerState,
    playlist_id: i64,
    was_locked: bool,
    send: &dyn Fn(PlayerCommand),
) {
    if !was_locked {
        return;
    }
    let Ok(entries) = queries::playlist_entries(&db.conn, playlist_id) else {
        return;
    };
    let (items, _) = state.snapshot_playlist();
    let mut cmds = Vec::new();

    // Queue items whose entry has gone from the playlist.
    let live: std::collections::HashSet<i64> = entries.iter().map(|e| e.id).collect();
    let doomed: Vec<QueueItemId> = items
        .iter()
        .filter(|i| i.playlist_entry_id.is_none_or(|e| !live.contains(&e)))
        .map(|i| i.id)
        .collect();
    if !doomed.is_empty() {
        cmds.push(PlayerCommand::RemoveFromPlaylistBatch(doomed.clone()));
    }

    // Entries the queue has never seen.
    let known: HashMap<i64, QueueItemId> = items
        .iter()
        .filter_map(|i| i.playlist_entry_id.map(|e| (e, i.id)))
        .collect();
    let missing: Vec<&queries::PlaylistEntry> = entries
        .iter()
        .filter(|e| !known.contains_key(&e.id))
        .collect();
    let mut added = HashMap::new();
    // The queue's order once the removals and additions have landed.
    let mut landed: Vec<QueueItemId> = items
        .iter()
        .map(|i| i.id)
        .filter(|id| !doomed.contains(id))
        .collect();
    if !missing.is_empty() {
        let track_ids: Vec<i64> = missing.iter().map(|e| e.track.id).collect();
        let rows = queries::tracks_by_ids(&db.conn, &track_ids).unwrap_or_default();
        let mut new_items = crate::helpers::playlist_items_for_tracks(db, &rows);
        for (item, entry) in new_items.iter_mut().zip(&missing) {
            item.playlist_entry_id = Some(entry.id);
            added.insert(entry.id, item.id);
        }
        if !new_items.is_empty() {
            landed.extend(new_items.iter().map(|i| i.id));
            cmds.push(PlayerCommand::AddToPlaylist(new_items));
        }
    }

    // Then the order, which is what puts the new arrivals in their places —
    // they were appended, because that is the only thing an add can do.
    let order: Vec<QueueItemId> = entries
        .iter()
        .filter_map(|e| known.get(&e.id).or_else(|| added.get(&e.id)).copied())
        .collect();
    if !order.is_empty() && order != landed {
        cmds.push(PlayerCommand::ReorderPlaylist(order));
    }

    // One playlist edit is one step of the queue's undo.
    if cmds.is_empty() {
        return;
    }
    send(PlayerCommand::BeginUndoBatch);
    for cmd in cmds {
        send(cmd);
    }
    send(PlayerCommand::EndUndoBatch);
}

/// Reconcile playlists with the server, both directions.
///
/// Unlike favourites, a playlist has an order, so this is not a union. Each
/// side's change is judged against its own record: the server's `changed`
/// against the stamp it had at the last sync, the local `changed_at` against
/// the one that sync covered. Only one side moved: that side wins. Both moved:
/// last writer wins on `changed`. Neither: nothing is fetched at all.
///
/// Playlists that have never been to the server are created there. Ones the
/// server no longer has are dropped locally: deleting a playlist on Navidrome
/// and having it reappear on the next sync would make deletion impossible.
/// Missing from the listing is not enough for that, since a listing can come
/// back short or empty: the server is asked for each one, and only one it
/// answers "not found" for (error 70) is dropped. Playlists tied to another
/// server or account are first made local again, so signing in somewhere else
/// never reads them as deleted.
///
/// A server copy can name songs the library does not have — ones a library
/// sync has not reached, or ones the server lists in no album. The local copy
/// holds the rest; a push puts those songs back where they were (see
/// [`keep_unknown`]), so koan never deletes on the server an entry it could
/// not show, and the songs fill in here once the library has them (see
/// [`fill_missing_songs`]).
pub fn reconcile_playlists(
    db: &Database,
    client: &SubsonicClient,
    url: &str,
    username: &str,
) -> PlaylistSync {
    let mut out = PlaylistSync::default();
    let account = account_key(url, username);

    let remote = match client.get_playlists() {
        Ok(lists) => lists,
        Err(e) => {
            log::warn!("could not fetch playlists from the server: {e}");
            return out;
        }
    };

    match queries::detach_playlists_from_other_accounts(&db.conn, &account) {
        Ok(0) => {}
        Ok(n) => log::info!("{n} playlists belonged to another server; keeping them as local"),
        Err(e) => {
            log::warn!("could not check which server playlists belong to: {e}");
            return out;
        }
    }

    // Only playlists this user owns are ours to write back. A public playlist
    // belonging to someone else is still worth having locally, but pushing our
    // copy of it would be editing their playlist.
    let mut seen_remote_ids = Vec::new();

    for summary in &remote {
        seen_remote_ids.push(summary.id.clone());
        let local = match queries::playlist_by_remote_id(&db.conn, &summary.id) {
            Ok(local) => local,
            Err(e) => {
                log::warn!("could not look up playlist {}: {e}", summary.name);
                continue;
            }
        };
        // A read-only playlist (a smart one on the server) is pulled and
        // never pushed, whoever owns it.
        let ours = !summary.readonly
            && summary
                .owner
                .as_deref()
                .is_none_or(|owner| owner == username);

        if let Some(local) = &local {
            let server_moved = summary.changed.as_deref() != local.remote_changed.as_deref();
            let local_moved = ours && local.unsynced();
            if local_moved
                && (!server_moved || newer(&local.changed_at, summary.changed.as_deref()))
            {
                if push(db, client, &account, local.id).is_ok() {
                    out.pushed += 1;
                }
                continue;
            }
            if !server_moved && !local_moved {
                continue;
            }
        }

        let full = match client.get_playlist(&summary.id) {
            Ok(full) => full,
            Err(e) => {
                log::warn!("could not fetch playlist {}: {e}", summary.id);
                continue;
            }
        };

        let remote_song_ids: Vec<String> = full.entry.iter().map(|s| s.id.clone()).collect();
        let track_ids = match queries::track_ids_for_remote_ids(&db.conn, &remote_song_ids) {
            Ok(ids) => ids,
            Err(e) => {
                log::warn!("could not read playlist {}: {e}", summary.name);
                continue;
            }
        };
        let unknown = track_ids.iter().filter(|t| t.is_none()).count();
        if unknown > 0 {
            log::info!(
                "playlist {}: {unknown} of {} songs are not in the library; \
                 they stay on the server",
                summary.name,
                track_ids.len()
            );
        }
        let record = queries::ServerSongs::from_lookup(remote_song_ids, &track_ids);
        let track_ids: Vec<i64> = track_ids.into_iter().flatten().collect();

        // All of it or none: a copy renamed but not refilled, or refilled but
        // not marked synced, would push back as an edit nobody made.
        let stored = queries::atomically(&db.conn, || {
            let id = match &local {
                Some(local) => local.id,
                None => queries::create_playlist(
                    &db.conn,
                    queries::LOCAL_USER,
                    &summary.name,
                    summary.comment.as_deref(),
                )?,
            };
            queries::rename_playlist(&db.conn, id, &summary.name)?;
            queries::set_playlist_readonly(&db.conn, id, summary.readonly)?;
            queries::set_playlist_remote(
                &db.conn,
                id,
                &summary.id,
                summary.owner.as_deref(),
                summary.public,
                &account,
            )?;
            queries::merge_server_tracks(&db.conn, id, &track_ids)?;
            queries::set_playlist_server_songs(&db.conn, id, &record)?;
            // The rename stamped the local copy as changed; this is the
            // server's copy, so what is here now is what the server has.
            queries::mark_playlist_synced(&db.conn, id, summary.changed.as_deref(), None)
        });
        match stored {
            Ok(()) => out.pulled += 1,
            Err(e) => log::warn!("could not store playlist {}: {e}", summary.name),
        }
    }

    // A playlist we hold a server id for that the server no longer lists was
    // deleted there.
    let held = match queries::list_playlists(&db.conn, queries::LOCAL_USER) {
        Ok(lists) => lists,
        Err(e) => {
            log::warn!("could not list playlists to check for deletions: {e}");
            Vec::new()
        }
    };
    for local in &held {
        let Some(remote_id) = local.remote_id.as_deref() else {
            continue;
        };
        if seen_remote_ids.iter().any(|seen| seen == remote_id) {
            continue;
        }
        match client.get_playlist(remote_id) {
            Err(SubsonicError::Api { code: 70, .. }) => {
                if let Err(e) = queries::delete_playlist(&db.conn, local.id) {
                    log::warn!("could not delete playlist {}: {e}", local.name);
                }
            }
            Ok(_) => log::info!(
                "playlist {} was missing from the listing but still exists",
                local.name
            ),
            Err(e) => log::warn!(
                "could not confirm playlist {} was deleted ({e}); keeping it",
                local.name
            ),
        }
    }

    for local in
        queries::playlists_without_remote(&db.conn, queries::LOCAL_USER).unwrap_or_default()
    {
        if push(db, client, &account, local.id).is_ok() {
            out.pushed += 1;
        }
    }

    fill_missing_songs(db);
    out
}

/// Put the songs a server copy named that the library lacked into their
/// places once the library has them.
///
/// The record (see [`queries::ServerSongs`]) is the server's copy as of the
/// last pull or push; a playlist whose copy has moved on either side since is
/// pulled or pushed afresh, which records again. So this needs no request:
/// what the server holds is already known, only the library has changed.
///
/// A playlist edited here since is left alone: the edit is what its next push
/// sends, and the push records afresh. The check is made under the push lock
/// and in the write transaction, so no edit or push lands between it and the
/// refill.
fn fill_missing_songs(db: &Database) {
    let ids = match queries::playlists_missing_songs(&db.conn) {
        Ok(ids) => ids,
        Err(e) => {
            log::warn!("could not read the playlists missing songs: {e}");
            return;
        }
    };
    for id in ids {
        let lock = push_lock(id);
        let _held = lock.lock();
        let filled = queries::atomically(&db.conn, || -> Result<(), DbError> {
            let synced = queries::get_playlist(&db.conn, id)?.is_some_and(|p| !p.unsynced());
            let Some(record) = queries::playlist_server_songs(&db.conn, id)?.filter(|_| synced)
            else {
                return Ok(());
            };
            let track_ids = queries::track_ids_for_remote_ids(&db.conn, &record.songs)?;
            let now = queries::ServerSongs::from_lookup(record.songs.clone(), &track_ids);
            let still: HashSet<&str> = now.missing.iter().map(String::as_str).collect();
            if record.missing.iter().any(|s| !still.contains(s.as_str())) {
                let track_ids: Vec<i64> = track_ids.into_iter().flatten().collect();
                queries::merge_server_tracks(&db.conn, id, &track_ids)?;
            }
            if now != record {
                queries::set_playlist_server_songs(&db.conn, id, &now)?;
            }
            Ok(())
        });
        if let Err(e) = filled {
            log::warn!("could not fill in playlist {id}: {e}");
        }
    }
}

/// What a playlist's `remote_id` is relative to: one account on one server.
fn account_key(url: &str, username: &str) -> String {
    format!("{username}@{}", url.trim_end_matches('/'))
}

/// One lock per playlist, held for the length of a push.
///
/// Pushes are fired from every edit, and two in flight at once would race: both
/// could see no server id and create two playlists there, or land out of
/// order and leave the server holding the older contents. Held, each push
/// reads the row only once the one before it has written its answer back.
fn push_lock(id: i64) -> std::sync::Arc<parking_lot::Mutex<()>> {
    static LOCKS: std::sync::OnceLock<
        parking_lot::Mutex<std::collections::HashMap<i64, std::sync::Arc<parking_lot::Mutex<()>>>>,
    > = std::sync::OnceLock::new();
    LOCKS
        .get_or_init(Default::default)
        .lock()
        .entry(id)
        .or_default()
        .clone()
}

/// Send a playlist's name and contents to the server, in order.
///
/// `createPlaylist` with a `playlistId` replaces the contents wholesale, which
/// is the only Subsonic call that can express a reorder — so a push is always
/// the whole list rather than a diff.
fn push(db: &Database, client: &SubsonicClient, account: &str, id: i64) -> Result<(), ()> {
    let lock = push_lock(id);
    let _held = lock.lock();
    // A server id from another account names someone else's playlist here.
    if queries::detach_playlists_from_other_accounts(&db.conn, account).is_err() {
        return Err(());
    }

    let Ok(Some(local)) = queries::get_playlist(&db.conn, id) else {
        return Err(());
    };
    // A smart playlist here, or a read-only one there: neither side's copy
    // is for the other to overwrite.
    if local.readonly {
        return Err(());
    }
    let remote_id = local.remote_id.as_deref();
    let song_ids = match queries::remote_ids_for_playlist(&db.conn, id) {
        Ok(ids) => ids,
        Err(e) => {
            log::warn!("could not read playlist '{}' to push it: {e}", local.name);
            return Err(());
        }
    };

    // A playlist made entirely of local files has nothing the server could
    // point at. Creating an empty one there would be worse than not creating
    // it, and emptying one there is only right when it is empty here too.
    if song_ids.is_empty() && (remote_id.is_none() || local.track_count > 0) {
        if remote_id.is_some() {
            log::warn!(
                "playlist '{}' holds nothing the server has; not emptying the server's copy",
                local.name
            );
        }
        return Err(());
    }

    // The push replaces the server's copy wholesale, so a song there that
    // this copy never held would be deleted by it without anyone having
    // chosen to. That is one the library does not know, or one it learnt of
    // after this copy was pulled without it. Those go back in where they were.
    let record = match queries::playlist_server_songs(&db.conn, id) {
        Ok(record) => record.unwrap_or_default(),
        Err(e) => {
            log::warn!("could not read playlist '{}' to push it: {e}", local.name);
            return Err(());
        }
    };
    let held: HashSet<String> = song_ids.iter().cloned().collect();
    let never_held: HashSet<&str> = record
        .missing
        .iter()
        .filter(|s| !held.contains(*s))
        .map(String::as_str)
        .collect();
    let song_ids = match remote_id {
        None => song_ids,
        Some(remote_id) => {
            let server = client
                .get_playlist(remote_id)
                .map_err(|e| e.to_string())
                .and_then(|full| {
                    let ids: Vec<String> = full.entry.into_iter().map(|s| s.id).collect();
                    let known = queries::track_ids_for_remote_ids(&db.conn, &ids)
                        .map_err(|e| e.to_string())?;
                    Ok((ids, known))
                });
            match server {
                Ok((ids, known)) => {
                    let known: Vec<bool> = ids
                        .iter()
                        .zip(&known)
                        .map(|(id, track)| track.is_some() && !never_held.contains(id.as_str()))
                        .collect();
                    keep_unknown(&ids, &known, song_ids)
                }
                Err(e) => {
                    log::warn!(
                        "could not read playlist '{}' on the server before pushing: {e}",
                        local.name
                    );
                    return Err(());
                }
            }
        }
    };

    // The name has to travel on its own. Navidrome's `createPlaylist` with a
    // `playlistId` replaces the songs and ignores the `name` it is handed, so a
    // rename pushed that way changes nothing. `updatePlaylist` is the call that
    // carries metadata; `createPlaylist` is the one that carries order. A push
    // needs both.
    if let Some(remote_id) = remote_id
        && let Err(e) = client.update_playlist(
            remote_id,
            Some(&local.name),
            local.comment.as_deref(),
            Some(local.public),
        )
    {
        log::warn!(
            "could not rename playlist '{}' on the server: {e}",
            local.name
        );
    }

    match client.create_playlist(remote_id, &local.name, &song_ids) {
        Ok(created) => {
            let new_id = created
                .as_ref()
                .map(|c| c.playlist.id.clone())
                .or_else(|| remote_id.map(str::to_string));
            if let Some(new_id) = new_id {
                let changed = created.as_ref().and_then(|c| c.playlist.changed.clone());
                let owner = created.as_ref().and_then(|c| c.playlist.owner.clone());
                let recorded = queries::atomically(&db.conn, || {
                    queries::set_playlist_remote(
                        &db.conn,
                        id,
                        &new_id,
                        owner.as_deref(),
                        local.public,
                        account,
                    )?;
                    queries::set_playlist_server_songs(
                        &db.conn,
                        id,
                        &queries::ServerSongs {
                            missing: song_ids
                                .iter()
                                .filter(|s| !held.contains(*s))
                                .cloned()
                                .collect(),
                            songs: song_ids.clone(),
                        },
                    )?;
                    queries::mark_playlist_synced(
                        &db.conn,
                        id,
                        changed.as_deref(),
                        Some(local.revision),
                    )
                });
                if let Err(e) = recorded {
                    log::warn!(
                        "playlist '{}' was pushed but its server id was not recorded: {e}",
                        local.name
                    );
                    return Err(());
                }
            }
            Ok(())
        }
        Err(e) => {
            log::warn!(
                "could not push playlist '{}' to the server: {e}",
                local.name
            );
            Err(())
        }
    }
}

/// `local`, the song ids a push sends, with the songs of the server's copy
/// `server` that the library does not know (`known` false) put back: each
/// after the nearest song before it on the server that `local` still holds,
/// or first when there is none. The library never held them, so no edit here
/// can have removed them.
fn keep_unknown(server: &[String], known: &[bool], local: Vec<String>) -> Vec<String> {
    let mut after: HashMap<&str, Vec<String>> = HashMap::new();
    let mut head = Vec::new();
    let mut anchor: Option<&str> = None;
    for (id, &known) in server.iter().zip(known) {
        if known {
            if local.iter().any(|l| l == id) {
                anchor = Some(id);
            }
        } else {
            match anchor {
                Some(a) => after.entry(a).or_default().push(id.clone()),
                None => head.push(id.clone()),
            }
        }
    }
    let mut out = head;
    for id in local {
        let follow = after.remove(id.as_str());
        out.push(id);
        out.extend(follow.into_iter().flatten());
    }
    out
}

/// Whether `local` was changed after the server's copy was.
///
/// Only consulted when both sides changed since the last sync. Both are
/// ISO 8601 in UTC — SQLite's `datetime('now')` on our side, the server's own
/// stamp on theirs — near enough that comparing the digits works, once
/// SQLite's space is made a `T`. A server that sends no timestamp at all
/// cannot be shown to be newer, so ours wins and the push settles it.
fn newer(local: &str, remote: Option<&str>) -> bool {
    let Some(remote) = remote else { return true };
    let normalise = |s: &str| s.replace(' ', "T").trim_end_matches('Z').to_string();
    normalise(local) > normalise(remote)
}

/// Push a playlist to the server in the background, if there is one.
///
/// Fire and forget on its own thread, the way favourites are: the local copy is
/// already written, and a slow server should not hold up the edit that caused
/// this. A failure leaves the local copy unsynced, which is exactly what
/// [`reconcile_playlists`] resolves on the next sync.
///
/// The thread takes its own connection rather than borrowing the caller's:
/// a `rusqlite::Connection` is not `Sync`, and the answer has to be written
/// back — the new server id — so it needs one of its own.
pub fn push_to_remote(id: i64) {
    let cfg = Config::load().unwrap_or_default();
    if !cfg.remote.enabled {
        return;
    }
    let Some(client) = subsonic_client(&cfg) else {
        return;
    };
    let account = account_key(&cfg.remote.url, &cfg.remote.username);
    std::thread::Builder::new()
        .name("koan-playlist-sync".into())
        .spawn(move || {
            let Ok(db) = crate::db::pool::shared().get() else {
                return;
            };
            let Ok(Some(list)) = queries::get_playlist(&db.conn, id) else {
                return;
            };
            // The upstream server has one account, and it is the local user's.
            if !matches!(
                queries::auth::is_local_user(&db.conn, list.user_id),
                Ok(true)
            ) {
                return;
            }
            let _ = push(&db, &client, &account, id);
        })
        .ok();
}

/// Delete a playlist on the server. Nothing to do for one that never went.
pub fn delete_on_remote(remote_id: String) {
    let cfg = Config::load().unwrap_or_default();
    if !cfg.remote.enabled {
        return;
    }
    let Some(client) = subsonic_client(&cfg) else {
        return;
    };
    std::thread::Builder::new()
        .name("koan-playlist-sync".into())
        .spawn(move || {
            if let Err(e) = client.delete_playlist(&remote_id) {
                log::warn!("could not delete playlist {remote_id} on the server: {e}");
            }
        })
        .ok();
}

/// What an export wrote, and what it could not.
#[derive(Debug, Default, Clone, Copy)]
pub struct ExportSummary {
    pub written: usize,
    /// Tracks with no file on this machine. A playlist file is a list of
    /// paths, and a remote track that has never been downloaded has none.
    pub skipped: usize,
}

/// Write a playlist as an extended M3U8.
///
/// Absolute paths, UTF-8, `#EXTINF` per entry — the format every player still
/// reads. Remote tracks that have not been downloaded are left out rather than
/// written as stream URLs: a Subsonic stream URL carries the credentials that
/// authorise it, and a playlist file is something people mail to each other.
pub fn export_m3u8(
    db: &Database,
    playlist_id: i64,
    dest: &Path,
) -> Result<ExportSummary, std::io::Error> {
    let name = queries::get_playlist(&db.conn, playlist_id)
        .ok()
        .flatten()
        .map(|p| p.name)
        .unwrap_or_default();
    let tracks = queries::playlist_tracks(&db.conn, playlist_id).unwrap_or_default();

    let mut out = ExportSummary::default();
    let mut file = std::fs::File::create(dest)?;
    writeln!(file, "#EXTM3U")?;
    if !name.is_empty() {
        writeln!(file, "#PLAYLIST:{name}")?;
    }

    for track in &tracks {
        let path = track
            .path
            .as_deref()
            .or(track.cached_path.as_deref())
            .map(PathBuf::from)
            .filter(|p| p.exists());
        let Some(path) = path else {
            out.skipped += 1;
            continue;
        };
        let seconds = track.duration_ms.unwrap_or(0) / 1000;
        writeln!(
            file,
            "#EXTINF:{seconds},{} - {}",
            track.artist_name, track.title
        )?;
        writeln!(file, "{}", path.display())?;
        out.written += 1;
    }

    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::queries::{TrackMeta, upsert_track};

    fn meta(title: &str, path: &Path) -> TrackMeta {
        TrackMeta {
            title: title.into(),
            artist: "Artist".into(),
            album_artist: Some("Artist".into()),
            album: "Album".into(),
            date: None,
            disc: None,
            track_number: None,
            genre: None,
            label: None,
            duration_ms: Some(185_000),
            codec: Some("FLAC".into()),
            sample_rate: None,
            bit_depth: None,
            channels: None,
            bitrate: None,
            size_bytes: None,
            mtime: None,
            path: Some(path.to_string_lossy().into_owned()),
            source: "local".into(),
            remote_id: None,
            remote_url: None,
            album_remote_id: None,
            artist_remote_id: None,
            mbid: None,
            album_mbid: None,
            album_added_at: None,
            credits: Default::default(),
        }
    }

    /// The queue is locked while it is still exactly the playlist, and stops
    /// being the moment it is not. Everything else about following follows from
    /// this one answer.
    #[test]
    fn a_queue_is_locked_only_while_it_is_still_the_playlist() {
        use crate::player::state::{ItemState, PlaylistItem, QueueItemId, SharedPlayerState};

        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let a = upsert_track(&db.conn, &meta("A", &dir.path().join("a.flac"))).unwrap();
        let b = upsert_track(&db.conn, &meta("B", &dir.path().join("b.flac"))).unwrap();

        let id =
            queries::create_playlist(&db.conn, crate::db::queries::LOCAL_USER, "Evening", None)
                .unwrap();
        let entries = queries::add_tracks(&db.conn, id, &[a, b]).unwrap();

        let state = SharedPlayerState::new();
        let queued = |entry: Option<i64>| PlaylistItem {
            uid: None,
            id: QueueItemId::new(),
            db_id: Some(a),
            playlist_entry_id: entry,
            path: dir.path().join("a.flac"),
            title: "A".into(),
            artist: "Artist".into(),
            album_artist: "Artist".into(),
            album: "Album".into(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            state: ItemState::Ready,
            played: false,
        };

        assert_eq!(
            queue_lock(&db, &state),
            None,
            "an empty queue is not locked"
        );

        state.add_items(vec![queued(Some(entries[0])), queued(Some(entries[1]))]);
        assert_eq!(
            queue_lock(&db, &state),
            Some(QueueLock::Playlist(id)),
            "the queue is the playlist"
        );

        // Something that never came from the playlist — played next, dropped
        // in.
        state.add_items(vec![queued(None)]);
        assert_eq!(queue_lock(&db, &state), None);
    }

    /// Reordering the queue by hand ends the lock, which is the whole point of
    /// deriving it: there is no flag anyone has to remember to clear.
    #[test]
    fn rearranging_the_queue_ends_the_lock() {
        use crate::player::state::{ItemState, PlaylistItem, QueueItemId, SharedPlayerState};

        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let a = upsert_track(&db.conn, &meta("A", &dir.path().join("a.flac"))).unwrap();
        let b = upsert_track(&db.conn, &meta("B", &dir.path().join("b.flac"))).unwrap();
        let id =
            queries::create_playlist(&db.conn, crate::db::queries::LOCAL_USER, "Evening", None)
                .unwrap();
        let entries = queries::add_tracks(&db.conn, id, &[a, b]).unwrap();

        let state = SharedPlayerState::new();
        let items: Vec<PlaylistItem> = entries
            .iter()
            .map(|entry| PlaylistItem {
                uid: None,
                id: QueueItemId::new(),
                db_id: Some(a),
                playlist_entry_id: Some(*entry),
                path: dir.path().join("a.flac"),
                title: "A".into(),
                artist: "Artist".into(),
                album_artist: "Artist".into(),
                album: "Album".into(),
                year: None,
                codec: None,
                track_number: None,
                disc: None,
                duration_ms: None,
                state: ItemState::Ready,
                played: false,
            })
            .collect();
        let ids: Vec<QueueItemId> = items.iter().map(|i| i.id).collect();
        state.add_items(items);
        assert_eq!(queue_lock(&db, &state), Some(QueueLock::Playlist(id)));

        state.reorder_to(&[ids[1], ids[0]]);
        assert_eq!(
            queue_lock(&db, &state),
            None,
            "same tracks, different order — no longer the playlist"
        );

        // And the playlist catching up locks it again. Nothing had to be reset.
        queries::reorder_entries(&db.conn, id, &[entries[1], entries[0]]).unwrap();
        assert_eq!(queue_lock(&db, &state), Some(QueueLock::Playlist(id)));
    }

    /// One playlist edit followed by the queue is one step of the queue's undo,
    /// and a removal that leaves the order as it was sends no reorder.
    #[test]
    fn following_an_edit_is_one_undo_step() {
        use crate::player::state::{ItemState, PlaylistItem, QueueItemId, SharedPlayerState};

        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let a = upsert_track(&db.conn, &meta("A", &dir.path().join("a.flac"))).unwrap();
        let b = upsert_track(&db.conn, &meta("B", &dir.path().join("b.flac"))).unwrap();
        let c = upsert_track(&db.conn, &meta("C", &dir.path().join("c.flac"))).unwrap();
        let id =
            queries::create_playlist(&db.conn, crate::db::queries::LOCAL_USER, "Evening", None)
                .unwrap();
        let entries = queries::add_tracks(&db.conn, id, &[a, b, c]).unwrap();

        let state = SharedPlayerState::new();
        let items: Vec<PlaylistItem> = entries
            .iter()
            .map(|entry| PlaylistItem {
                uid: None,
                id: QueueItemId::new(),
                db_id: Some(a),
                playlist_entry_id: Some(*entry),
                path: dir.path().join("a.flac"),
                title: "A".into(),
                artist: "Artist".into(),
                album_artist: "Artist".into(),
                album: "Album".into(),
                year: None,
                codec: None,
                track_number: None,
                disc: None,
                duration_ms: None,
                state: ItemState::Ready,
                played: false,
            })
            .collect();
        let ids: Vec<QueueItemId> = items.iter().map(|i| i.id).collect();
        state.add_items(items);

        let follow = |was_locked| {
            let sent = std::cell::RefCell::new(Vec::new());
            follow_edit(&db, &state, id, was_locked, &|cmd| {
                sent.borrow_mut().push(cmd)
            });
            sent.into_inner()
        };

        assert!(follow(true).is_empty(), "nothing changed, nothing sent");

        queries::remove_entries(&db.conn, id, &[entries[1]]).unwrap();
        let sent = follow(true);
        assert!(
            matches!(
                sent.as_slice(),
                [
                    PlayerCommand::BeginUndoBatch,
                    PlayerCommand::RemoveFromPlaylistBatch(gone),
                    PlayerCommand::EndUndoBatch,
                ] if gone == &[ids[1]]
            ),
            "{sent:?}"
        );

        state.remove_item(ids[1]);
        queries::reorder_entries(&db.conn, id, &[entries[2], entries[0]]).unwrap();
        let sent = follow(true);
        assert!(
            matches!(
                sent.as_slice(),
                [
                    PlayerCommand::BeginUndoBatch,
                    PlayerCommand::ReorderPlaylist(order),
                    PlayerCommand::EndUndoBatch,
                ] if order == &[ids[2], ids[0]]
            ),
            "{sent:?}"
        );
    }

    /// A record needs no provenance: it *is* an ordered set of tracks, so the
    /// queue being that record is a question about what the queue holds. Which
    /// is why it survives a relaunch, where nothing remembers what was played.
    #[test]
    fn a_queue_holding_exactly_one_record_is_locked_to_it() {
        use crate::player::state::{ItemState, PlaylistItem, QueueItemId, SharedPlayerState};

        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let a = upsert_track(&db.conn, &meta("A", &dir.path().join("a.flac"))).unwrap();
        let b = upsert_track(&db.conn, &meta("B", &dir.path().join("b.flac"))).unwrap();
        let album_id = queries::get_track_row(&db.conn, a)
            .unwrap()
            .unwrap()
            .album_id
            .unwrap();

        let state = SharedPlayerState::new();
        let queued = |track: i64| PlaylistItem {
            uid: None,
            id: QueueItemId::new(),
            db_id: Some(track),
            playlist_entry_id: None,
            path: dir.path().join("a.flac"),
            title: "A".into(),
            artist: "Artist".into(),
            album_artist: "Artist".into(),
            album: "Album".into(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            state: ItemState::Ready,
            played: false,
        };

        state.add_items(vec![queued(a)]);
        assert_eq!(
            queue_lock(&db, &state),
            None,
            "half a record is not the record"
        );

        state.add_items(vec![queued(b)]);
        assert_eq!(queue_lock(&db, &state), Some(QueueLock::Album(album_id)));
    }

    #[test]
    fn export_writes_what_is_on_disk_and_counts_what_is_not() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();

        let present = dir.path().join("here.flac");
        std::fs::write(&present, b"x").unwrap();
        let here = upsert_track(&db.conn, &meta("Here", &present)).unwrap();
        let gone = upsert_track(&db.conn, &meta("Gone", &dir.path().join("gone.flac"))).unwrap();

        let id =
            queries::create_playlist(&db.conn, crate::db::queries::LOCAL_USER, "Evening", None)
                .unwrap();
        queries::add_tracks(&db.conn, id, &[here, gone]).unwrap();

        let dest = dir.path().join("evening.m3u8");
        let summary = export_m3u8(&db, id, &dest).unwrap();
        assert_eq!((summary.written, summary.skipped), (1, 1));

        let written = std::fs::read_to_string(&dest).unwrap();
        assert!(written.starts_with("#EXTM3U\n#PLAYLIST:Evening\n"));
        assert!(written.contains("#EXTINF:185,Artist - Here"));
        assert!(written.contains(&present.display().to_string()));
        assert!(!written.contains("gone.flac"));
    }

    /// A Subsonic server holding playlists and nothing else, one request per
    /// connection. Each `changed` is a counter, so every write moves it.
    #[derive(Default)]
    struct Server {
        lists: Vec<(String, Vec<String>, u32)>,
        fetches: usize,
        creates_without_id: usize,
        /// `getPlaylists` answers with none, as a server answering wrongly.
        hide_listing: bool,
    }

    fn serve(server: std::sync::Arc<parking_lot::Mutex<Server>>) -> String {
        use std::io::{BufRead, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        std::thread::spawn(move || {
            for stream in listener.incoming().flatten() {
                let server = server.clone();
                std::thread::spawn(move || {
                    let mut reader = std::io::BufReader::new(stream.try_clone().unwrap());
                    let mut request = String::new();
                    reader.read_line(&mut request).unwrap();
                    let mut line = String::new();
                    while reader.read_line(&mut line).unwrap_or(0) > 2 {
                        line.clear();
                    }
                    let target = request.split_whitespace().nth(1).unwrap_or("");
                    let (path, query) = target.split_once('?').unwrap_or((target, ""));
                    let params: Vec<(&str, &str)> = query
                        .split('&')
                        .filter_map(|kv| kv.split_once('='))
                        .collect();
                    let param = |k: &str| params.iter().find(|(n, _)| *n == k).map(|(_, v)| *v);
                    let body = respond(&server, path.rsplit('/').next().unwrap(), &params, param);
                    let mut stream = stream;
                    let _ = write!(
                        stream,
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{body}",
                        body.len()
                    );
                });
            }
        });
        url
    }

    fn respond<'a>(
        server: &parking_lot::Mutex<Server>,
        endpoint: &str,
        params: &[(&str, &'a str)],
        param: impl Fn(&str) -> Option<&'a str>,
    ) -> String {
        let summary = |(id, songs, changed): &(String, Vec<String>, u32)| {
            format!(
                r#""id":"{id}","name":"{id}","owner":"u","songCount":{},"changed":"{changed}""#,
                songs.len()
            )
        };
        let full = |list: &(String, Vec<String>, u32)| {
            let entries: Vec<String> = list
                .1
                .iter()
                .map(|s| format!(r#"{{"id":"{s}","title":"{s}"}}"#))
                .collect();
            format!(r#"{{{},"entry":[{}]}}"#, summary(list), entries.join(","))
        };
        let ok = |inner: String| format!(r#"{{"subsonic-response":{{"status":"ok"{inner}}}}}"#);
        match endpoint {
            "getPlaylists" => {
                let server = server.lock();
                let lists: Vec<String> = server
                    .lists
                    .iter()
                    .filter(|_| !server.hide_listing)
                    .map(|l| format!("{{{}}}", summary(l)))
                    .collect();
                ok(format!(
                    r#","playlists":{{"playlist":[{}]}}"#,
                    lists.join(",")
                ))
            }
            "getPlaylist" => {
                let mut server = server.lock();
                server.fetches += 1;
                match server
                    .lists
                    .iter()
                    .find(|l| Some(l.0.as_str()) == param("id"))
                {
                    Some(list) => ok(format!(r#","playlist":{}"#, full(list))),
                    None => r#"{"subsonic-response":{"status":"failed","error":{"code":70,"message":"not found"}}}"#.to_string(),
                }
            }
            "createPlaylist" => {
                let songs: Vec<String> = params
                    .iter()
                    .filter(|(k, _)| *k == "songId")
                    .map(|(_, v)| v.to_string())
                    .collect();
                // Wide enough for two pushes to overlap if nothing stops them.
                std::thread::sleep(std::time::Duration::from_millis(50));
                let mut server = server.lock();
                let id = match param("playlistId") {
                    Some(id) => id.to_string(),
                    None => {
                        server.creates_without_id += 1;
                        format!("p{}", server.lists.len() + 1)
                    }
                };
                server.lists.retain(|l| l.0 != id);
                let changed = server.lists.iter().map(|l| l.2).max().unwrap_or(0) + 100;
                server.lists.push((id, songs, changed));
                ok(format!(
                    r#","playlist":{}"#,
                    full(server.lists.last().unwrap())
                ))
            }
            _ => ok(String::new()),
        }
    }

    fn remote_meta(title: &str, remote_id: &str) -> TrackMeta {
        TrackMeta {
            path: None,
            source: "remote".into(),
            remote_id: Some(remote_id.into()),
            album: title.into(),
            ..meta(title, Path::new(""))
        }
    }

    fn entries(db: &Database, id: i64) -> Vec<(i64, i64)> {
        queries::playlist_entries(&db.conn, id)
            .unwrap()
            .into_iter()
            .map(|e| (e.id, e.track.id))
            .collect()
    }

    #[test]
    fn a_sync_keeps_local_only_entries_and_fetches_nothing_unchanged() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let r2 = upsert_track(&db.conn, &remote_meta("Two", "s2")).unwrap();
        let local = upsert_track(&db.conn, &meta("Here", &dir.path().join("l.flac"))).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![("p1".into(), vec!["s1".into(), "s2".into()], 1)],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");

        let first = reconcile_playlists(&db, &client, &url, "u");
        assert_eq!(first.pulled, 1);
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;
        assert_eq!(
            entries(&db, id).iter().map(|e| e.1).collect::<Vec<_>>(),
            [r1, r2]
        );

        // A local file joins; the push carries only what the server can name.
        queries::add_tracks(&db.conn, id, &[local]).unwrap();
        let second = reconcile_playlists(&db, &client, &url, "u");
        assert_eq!((second.pushed, second.pulled), (1, 0));
        assert_eq!(server.lock().lists[0].1, ["s1", "s2"]);

        let before = entries(&db, id);
        assert_eq!(before.len(), 3);
        let fetches = server.lock().fetches;
        let third = reconcile_playlists(&db, &client, &url, "u");
        assert_eq!((third.pushed, third.pulled), (0, 0));
        assert_eq!(
            server.lock().fetches,
            fetches,
            "nothing moved, nothing fetched"
        );
        assert_eq!(entries(&db, id), before);

        // An edit on the server comes down without the local file or the
        // surviving entry's id.
        {
            let mut server = server.lock();
            server.lists[0].1 = vec!["s2".into()];
            server.lists[0].2 += 1;
        }
        let fourth = reconcile_playlists(&db, &client, &url, "u");
        assert_eq!(fourth.pulled, 1);
        assert_eq!(entries(&db, id), [before[1], before[2]]);
    }

    /// Forgetting the server takes its tracks out of every playlist; signing
    /// back in and syncing the library brings them back, and the playlists
    /// are pulled whole again even though the server's copies never changed.
    #[test]
    fn a_forgotten_server_refills_its_playlists_on_the_next_sync() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        upsert_track(&db.conn, &remote_meta("Two", "s2")).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![("p1".into(), vec!["s1".into(), "s2".into()], 1)],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        reconcile_playlists(&db, &client, &url, "u");
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;
        assert_eq!(entries(&db, id).len(), 2);

        crate::helpers::forget_remote(&db).unwrap();
        assert!(entries(&db, id).is_empty());

        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let r2 = upsert_track(&db.conn, &remote_meta("Two", "s2")).unwrap();
        let sync = reconcile_playlists(&db, &client, &url, "u");
        assert_eq!((sync.pulled, sync.pushed), (1, 0));
        assert_eq!(
            entries(&db, id).iter().map(|e| e.1).collect::<Vec<_>>(),
            [r1, r2]
        );
        assert_eq!(
            server.lock().lists[0].1,
            ["s1", "s2"],
            "the server copy is untouched"
        );
    }

    /// A song on the server's copy that the library does not have is left
    /// out of the local copy and put back, in place, by every push: nothing
    /// here could have removed it.
    #[test]
    fn a_server_song_the_library_lacks_is_never_dropped() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let r2 = upsert_track(&db.conn, &remote_meta("Two", "s2")).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![("p1".into(), vec!["s1".into(), "s9".into()], 1)],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        assert_eq!(reconcile_playlists(&db, &client, &url, "u").pulled, 1);
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;
        assert_eq!(
            entries(&db, id).iter().map(|e| e.1).collect::<Vec<_>>(),
            [r1]
        );

        queries::add_tracks(&db.conn, id, &[r2]).unwrap();
        assert!(push(&db, &client, &account_key(&url, "u"), id).is_ok());
        assert_eq!(server.lock().lists[0].1, ["s1", "s9", "s2"]);

        // The library catches up, and the server's copy comes down whole.
        let r9 = upsert_track(&db.conn, &remote_meta("Nine", "s9")).unwrap();
        server.lock().lists[0].2 += 1;
        assert_eq!(reconcile_playlists(&db, &client, &url, "u").pulled, 1);
        assert_eq!(
            entries(&db, id).iter().map(|e| e.1).collect::<Vec<_>>(),
            [r1, r9, r2]
        );
    }

    fn missing(db: &Database, id: i64) -> Option<Vec<String>> {
        queries::playlist_server_songs(&db.conn, id)
            .unwrap()
            .map(|r| r.missing)
    }

    /// Songs a pulled playlist named before the library had them fill in, in
    /// the server's order, on the sync after the library gains them, without
    /// the server being asked for the playlist again.
    #[test]
    fn songs_the_library_lacked_fill_in_when_they_arrive() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let r2 = upsert_track(&db.conn, &remote_meta("Two", "s2")).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![(
                "p1".into(),
                vec!["s1".into(), "s9".into(), "s2".into(), "s8".into()],
                1,
            )],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        assert_eq!(reconcile_playlists(&db, &client, &url, "u").pulled, 1);
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;
        let before = entries(&db, id);
        assert_eq!(before.iter().map(|e| e.1).collect::<Vec<_>>(), [r1, r2]);
        assert_eq!(missing(&db, id).unwrap(), ["s9", "s8"]);

        // One of the two arrives: it goes in its place, the entries already
        // there keep theirs, and the other is still missing.
        let r9 = upsert_track(&db.conn, &remote_meta("Nine", "s9")).unwrap();
        let fetches = server.lock().fetches;
        let sync = reconcile_playlists(&db, &client, &url, "u");
        assert_eq!((sync.pulled, sync.pushed), (0, 0));
        let now = entries(&db, id);
        assert_eq!(now.iter().map(|e| e.1).collect::<Vec<_>>(), [r1, r9, r2]);
        assert_eq!((now[0], now[2]), (before[0], before[1]));
        assert_eq!(missing(&db, id).unwrap(), ["s8"]);

        let r8 = upsert_track(&db.conn, &remote_meta("Eight", "s8")).unwrap();
        reconcile_playlists(&db, &client, &url, "u");
        assert_eq!(
            entries(&db, id).iter().map(|e| e.1).collect::<Vec<_>>(),
            [r1, r9, r2, r8]
        );
        assert_eq!(missing(&db, id), None);
        assert_eq!(server.lock().fetches, fetches, "the server was not asked");

        // Filling in took the server's copy, which is no edit to push.
        let sync = reconcile_playlists(&db, &client, &url, "u");
        assert_eq!((sync.pulled, sync.pushed), (0, 0));
        assert!(
            !queries::get_playlist(&db.conn, id)
                .unwrap()
                .unwrap()
                .unsynced()
        );
    }

    /// An edit on the server replaces what is missing with what its new copy
    /// lacks.
    #[test]
    fn a_server_edit_replaces_the_missing_songs() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![("p1".into(), vec!["s1".into(), "s9".into()], 1)],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        reconcile_playlists(&db, &client, &url, "u");
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;
        assert_eq!(missing(&db, id).unwrap(), ["s9"]);

        {
            let mut server = server.lock();
            server.lists[0].1 = vec!["s8".into(), "s1".into()];
            server.lists[0].2 += 1;
        }
        assert_eq!(reconcile_playlists(&db, &client, &url, "u").pulled, 1);
        assert_eq!(missing(&db, id).unwrap(), ["s8"]);

        // The song only the old copy named is not wanted any more.
        upsert_track(&db.conn, &remote_meta("Nine", "s9")).unwrap();
        reconcile_playlists(&db, &client, &url, "u");
        assert_eq!(
            entries(&db, id).iter().map(|e| e.1).collect::<Vec<_>>(),
            [r1]
        );

        {
            let mut server = server.lock();
            server.lists[0].1 = vec!["s1".into()];
            server.lists[0].2 += 1;
        }
        reconcile_playlists(&db, &client, &url, "u");
        assert_eq!(missing(&db, id), None);
    }

    /// A playlist edited here before its missing songs arrive keeps the edit,
    /// and the push neither drops those songs from the server nor stops them
    /// filling in here.
    #[test]
    fn a_local_edit_keeps_the_missing_songs() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let r2 = upsert_track(&db.conn, &remote_meta("Two", "s2")).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![("p1".into(), vec!["s1".into(), "s9".into()], 1)],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        reconcile_playlists(&db, &client, &url, "u");
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;
        queries::add_tracks(&db.conn, id, &[r2]).unwrap();

        let r9 = upsert_track(&db.conn, &remote_meta("Nine", "s9")).unwrap();
        assert_eq!(reconcile_playlists(&db, &client, &url, "u").pushed, 1);
        assert_eq!(server.lock().lists[0].1, ["s1", "s9", "s2"]);
        assert_eq!(
            entries(&db, id).iter().map(|e| e.1).collect::<Vec<_>>(),
            [r1, r9, r2]
        );
        assert_eq!(missing(&db, id), None);
    }

    /// A missing song added here by hand once the library has it is pushed
    /// once, not once for the server's copy and again for this one.
    #[test]
    fn a_missing_song_added_here_is_pushed_once() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![("p1".into(), vec!["s1".into(), "s9".into()], 1)],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        reconcile_playlists(&db, &client, &url, "u");
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;

        let r9 = upsert_track(&db.conn, &remote_meta("Nine", "s9")).unwrap();
        queries::add_tracks(&db.conn, id, &[r9]).unwrap();
        assert_eq!(reconcile_playlists(&db, &client, &url, "u").pushed, 1);
        assert_eq!(server.lock().lists[0].1, ["s1", "s9"]);
        assert_eq!(missing(&db, id), None);
    }

    #[test]
    fn unknown_songs_go_back_after_the_song_before_them() {
        let ids = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        let server = ids(&["x", "a", "y", "b", "z", "c"]);
        let known = [false, true, false, true, false, true];
        // `b` removed and `d` added here: `z` follows `a`, the nearest
        // survivor before it.
        assert_eq!(
            keep_unknown(&server, &known, ids(&["c", "a", "d"])),
            ids(&["x", "c", "a", "y", "z", "d"])
        );
        assert_eq!(
            keep_unknown(&server, &known, Vec::new()),
            ids(&["x", "y", "z"])
        );
    }

    /// A copy holding entries none of which the server can name is not
    /// pushed as an empty list over the server's. One emptied on purpose is.
    #[test]
    fn only_an_empty_playlist_empties_the_server_copy() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let local = upsert_track(&db.conn, &meta("Here", &dir.path().join("l.flac"))).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![("p1".into(), vec!["s1".into()], 1)],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        let account = account_key(&url, "u");
        reconcile_playlists(&db, &client, &url, "u");
        let id = queries::playlist_by_remote_id(&db.conn, "p1")
            .unwrap()
            .unwrap()
            .id;

        let only = entries(&db, id);
        queries::add_tracks(&db.conn, id, &[local]).unwrap();
        queries::remove_entries(&db.conn, id, &[only[0].0]).unwrap();
        assert!(push(&db, &client, &account, id).is_err());
        assert_eq!(server.lock().lists[0].1, ["s1"]);

        let rest = entries(&db, id);
        queries::remove_entries(&db.conn, id, &[rest[0].0]).unwrap();
        assert!(push(&db, &client, &account, id).is_ok());
        assert!(server.lock().lists[0].1.is_empty());
    }

    /// A playlist missing from the listing is deleted here only once the
    /// server says it does not have it: a listing that comes back empty
    /// deletes nothing.
    #[test]
    fn only_a_playlist_the_server_says_is_gone_is_deleted() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server {
            lists: vec![
                ("p1".into(), vec!["s1".into()], 1),
                ("p2".into(), vec!["s1".into()], 2),
            ],
            ..Default::default()
        }));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        reconcile_playlists(&db, &client, &url, "u");
        let held = || {
            queries::list_playlists(&db.conn, queries::LOCAL_USER)
                .unwrap()
                .len()
        };
        assert_eq!(held(), 2);

        server.lock().hide_listing = true;
        reconcile_playlists(&db, &client, &url, "u");
        assert_eq!(held(), 2, "nothing deleted on an empty listing");

        {
            let mut server = server.lock();
            server.hide_listing = false;
            server.lists.remove(0);
        }
        reconcile_playlists(&db, &client, &url, "u");
        assert_eq!(held(), 1, "one deleted on the server is deleted here");
    }

    #[test]
    fn another_account_keeps_the_playlists_and_pushes_them_as_new() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::open(&dir.path().join("koan.db")).unwrap();
        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let id = queries::create_playlist(&db.conn, queries::LOCAL_USER, "Road", None).unwrap();
        queries::add_tracks(&db.conn, id, &[r1]).unwrap();
        queries::set_playlist_remote(&db.conn, id, "old-1", Some("u"), false, "u@http://old")
            .unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server::default()));
        let url = serve(server.clone());
        let client = SubsonicClient::new(&url, "u", "pw");
        let sync = reconcile_playlists(&db, &client, &url, "u");

        let list = queries::get_playlist(&db.conn, id).unwrap().expect("kept");
        assert_eq!(list.track_count, 1);
        assert_eq!(sync.pushed, 1);
        assert_eq!(list.remote_id.as_deref(), Some("p1"));
    }

    #[test]
    fn concurrent_pushes_create_one_server_playlist() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("koan.db");
        let db = Database::open(&path).unwrap();
        let r1 = upsert_track(&db.conn, &remote_meta("One", "s1")).unwrap();
        let id = queries::create_playlist(&db.conn, queries::LOCAL_USER, "Road", None).unwrap();
        queries::add_tracks(&db.conn, id, &[r1]).unwrap();

        let server = std::sync::Arc::new(parking_lot::Mutex::new(Server::default()));
        let url = serve(server.clone());
        let pushes: Vec<_> = (0..2)
            .map(|_| {
                let (path, url) = (path.clone(), url.clone());
                std::thread::spawn(move || {
                    let db = Database::open(&path).unwrap();
                    let client = SubsonicClient::new(&url, "u", "pw");
                    push(&db, &client, &account_key(&url, "u"), id)
                })
            })
            .collect();
        for p in pushes {
            p.join().unwrap().unwrap();
        }
        assert_eq!(server.lock().creates_without_id, 1);
        assert_eq!(server.lock().lists.len(), 1);
    }
}