redseat-api 0.4.0

Rust client for Redseat media servers
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
//! [`MirrorStore`] on SQLite: one file per server.
//!
//! One table per kind of item. Each row has the columns that queries and the sync
//! need (library, id, dates, type, rating...) and the item itself as JSON of its shared
//! type (`data`): a new server field needs no migration, only a new indexed column
//! does. Media relations (tags, people, series, movies, books) also go in link tables
//! for the filters. The schema version is SQLite's `user_version`.

use std::path::Path;
use std::sync::{Arc, Mutex, PoisonError};

use rusqlite::types::Value as SqlValue;
use rusqlite::{Connection, OptionalExtension, Transaction, params, params_from_iter};
use serde::Serialize;

use super::store::{Changes, MirrorStore, SyncKind, SyncState, ThumbRecord};
use crate::client::now_ms;
use crate::error::{Error, Result};
use crate::library::MediaItem;
use crate::types::ItemWithRelations;
use crate::types::library::ServerLibraryForRead;
use crate::types::media::{MediaQuery, RsSort, SqlOrder};

/// The schema version this crate writes. A file with a newer one is refused.
pub const SCHEMA_VERSION: usize = MIGRATIONS.len();

/// The migrations, in order: the version after migration `i` is `i + 1`.
const MIGRATIONS: &[&str] = &[
    // 1: libraries, sync state, items, media links, thumbnails.
    "
    CREATE TABLE libraries (id TEXT PRIMARY KEY NOT NULL, position INTEGER NOT NULL, data TEXT NOT NULL);
    CREATE TABLE sync_state (library TEXT PRIMARY KEY NOT NULL, state TEXT NOT NULL);

    CREATE TABLE medias (
        library TEXT NOT NULL, id TEXT NOT NULL,
        type TEXT, name TEXT, created INTEGER, added INTEGER, modified INTEGER NOT NULL,
        rating REAL, size INTEGER,
        gen INTEGER NOT NULL, data TEXT NOT NULL,
        PRIMARY KEY (library, id));
    CREATE INDEX medias_modified ON medias(library, modified);
    CREATE INDEX medias_added ON medias(library, added);
    CREATE INDEX medias_created ON medias(library, created);
    CREATE INDEX medias_type ON medias(library, type);

    CREATE TABLE media_tags (library TEXT NOT NULL, media TEXT NOT NULL, tag TEXT NOT NULL, conf INTEGER);
    CREATE INDEX media_tags_media ON media_tags(library, media);
    CREATE INDEX media_tags_tag ON media_tags(library, tag);
    CREATE TABLE media_people (library TEXT NOT NULL, media TEXT NOT NULL, person TEXT NOT NULL, conf INTEGER);
    CREATE INDEX media_people_media ON media_people(library, media);
    CREATE INDEX media_people_person ON media_people(library, person);
    CREATE TABLE media_series (library TEXT NOT NULL, media TEXT NOT NULL, serie TEXT NOT NULL,
        season INTEGER, episode INTEGER, episode_to INTEGER);
    CREATE INDEX media_series_media ON media_series(library, media);
    CREATE INDEX media_series_serie ON media_series(library, serie);
    CREATE TABLE media_movies (library TEXT NOT NULL, media TEXT NOT NULL, movie TEXT NOT NULL);
    CREATE INDEX media_movies_media ON media_movies(library, media);
    CREATE INDEX media_movies_movie ON media_movies(library, movie);
    CREATE TABLE media_books (library TEXT NOT NULL, media TEXT NOT NULL, book TEXT NOT NULL);
    CREATE INDEX media_books_media ON media_books(library, media);
    CREATE INDEX media_books_book ON media_books(library, book);

    CREATE TABLE tags (library TEXT NOT NULL, id TEXT NOT NULL, name TEXT, parent TEXT,
        modified INTEGER NOT NULL, gen INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (library, id));
    CREATE INDEX tags_parent ON tags(library, parent);
    CREATE TABLE people (library TEXT NOT NULL, id TEXT NOT NULL, name TEXT,
        modified INTEGER NOT NULL, gen INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (library, id));
    CREATE TABLE series (library TEXT NOT NULL, id TEXT NOT NULL, name TEXT,
        modified INTEGER NOT NULL, gen INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (library, id));
    CREATE TABLE movies (library TEXT NOT NULL, id TEXT NOT NULL, name TEXT,
        modified INTEGER NOT NULL, gen INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (library, id));
    CREATE TABLE episodes (library TEXT NOT NULL, id TEXT NOT NULL, name TEXT,
        serie TEXT NOT NULL, season INTEGER NOT NULL, number INTEGER NOT NULL,
        modified INTEGER NOT NULL, gen INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (library, id));
    CREATE INDEX episodes_serie ON episodes(library, serie, season, number);
    CREATE TABLE books (library TEXT NOT NULL, id TEXT NOT NULL, name TEXT,
        modified INTEGER NOT NULL, gen INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (library, id));

    CREATE TABLE thumbs (library TEXT NOT NULL, media TEXT NOT NULL, size INTEGER NOT NULL,
        version TEXT NOT NULL, accessed INTEGER NOT NULL, PRIMARY KEY (library, media));
    CREATE INDEX thumbs_accessed ON thumbs(accessed);
    ",
];

const MEDIA_LINK_TABLES: [&str; 5] = [
    "media_tags",
    "media_people",
    "media_series",
    "media_movies",
    "media_books",
];

fn storage(error: impl std::fmt::Display) -> Error {
    Error::storage(format!("local copy: {error}"))
}

/// The table of a kind; `None` for the deletions list.
fn table(kind: SyncKind) -> Option<&'static str> {
    Some(match kind {
        SyncKind::Tags => "tags",
        SyncKind::People => "people",
        SyncKind::Series => "series",
        SyncKind::Movies => "movies",
        SyncKind::Episodes => "episodes",
        SyncKind::Books => "books",
        SyncKind::Medias => "medias",
        SyncKind::Deleted => return None,
    })
}

/// Brings a database to [`SCHEMA_VERSION`].
fn migrate(conn: &mut Connection) -> Result<()> {
    let version: usize = conn
        .query_row("PRAGMA user_version", [], |row| row.get(0))
        .map_err(storage)?;
    if version > SCHEMA_VERSION {
        return Err(storage(format!(
            "schema version {version} is newer than this app's {SCHEMA_VERSION}"
        )));
    }
    for (index, sql) in MIGRATIONS.iter().enumerate().skip(version) {
        let mut run = || -> rusqlite::Result<()> {
            let tx = conn.transaction()?;
            tx.execute_batch(sql)?;
            tx.pragma_update(None, "user_version", index + 1)?;
            tx.commit()
        };
        run().map_err(storage)?;
    }
    Ok(())
}

fn configure(conn: &Connection) -> rusqlite::Result<()> {
    conn.busy_timeout(std::time::Duration::from_secs(10))?;
    conn.pragma_update(None, "journal_mode", "WAL")?;
    conn.pragma_update(None, "synchronous", "NORMAL")?;
    conn.pragma_update(None, "foreign_keys", "OFF")?;
    Ok(())
}

/// [`MirrorStore`] on a SQLite file. Writes go through one connection and reads
/// through another, so reads are not held up by a sync (WAL mode).
#[derive(Clone)]
pub struct SqliteStore {
    writer: Arc<Mutex<Connection>>,
    reader: Arc<Mutex<Connection>>,
}

impl std::fmt::Debug for SqliteStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SqliteStore").finish_non_exhaustive()
    }
}

impl SqliteStore {
    /// Opens (or creates) the database at `path`, with its folder, and migrates it.
    pub fn open(path: &Path) -> Result<Self> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(storage)?;
        }
        let mut writer = Connection::open(path).map_err(storage)?;
        configure(&writer).map_err(storage)?;
        migrate(&mut writer)?;
        let reader = Connection::open(path).map_err(storage)?;
        reader
            .busy_timeout(std::time::Duration::from_secs(10))
            .map_err(storage)?;
        Ok(SqliteStore {
            writer: Arc::new(Mutex::new(writer)),
            reader: Arc::new(Mutex::new(reader)),
        })
    }

    /// A database in memory, for tests.
    pub fn open_in_memory() -> Result<Self> {
        let mut conn = Connection::open_in_memory().map_err(storage)?;
        migrate(&mut conn)?;
        let conn = Arc::new(Mutex::new(conn));
        Ok(SqliteStore {
            writer: conn.clone(),
            reader: conn,
        })
    }

    async fn run<T: Send + 'static>(
        conn: &Arc<Mutex<Connection>>,
        f: impl FnOnce(&mut Connection) -> rusqlite::Result<T> + Send + 'static,
    ) -> Result<T> {
        let conn = conn.clone();
        tokio::task::spawn_blocking(move || {
            let mut conn = conn.lock().unwrap_or_else(PoisonError::into_inner);
            f(&mut conn)
        })
        .await
        .map_err(storage)?
        .map_err(storage)
    }

    async fn write<T: Send + 'static>(
        &self,
        f: impl FnOnce(&Transaction<'_>) -> rusqlite::Result<T> + Send + 'static,
    ) -> Result<T> {
        Self::run(&self.writer, move |conn| {
            let tx = conn.transaction()?;
            let value = f(&tx)?;
            tx.commit()?;
            Ok(value)
        })
        .await
    }

    async fn read<T: Send + 'static>(
        &self,
        f: impl FnOnce(&Connection) -> rusqlite::Result<T> + Send + 'static,
    ) -> Result<T> {
        Self::run(&self.reader, move |conn| f(conn)).await
    }
}

fn to_json<T: Serialize>(value: &T) -> rusqlite::Result<String> {
    serde_json::to_string(value).map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))
}

fn from_json<T: serde::de::DeserializeOwned>(text: &str) -> rusqlite::Result<T> {
    serde_json::from_str(text).map_err(|e| {
        rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(e))
    })
}

/// An item row: the shared columns, plus those of its table.
struct Row<'a> {
    id: &'a str,
    name: Option<&'a str>,
    modified: i64,
    data: String,
    extra: Vec<(&'static str, SqlValue)>,
}

/// Writes an item unless the stored one is newer; the stored one then only gets the
/// stamp. Returns whether the item was written.
fn upsert(
    tx: &Transaction<'_>,
    table: &str,
    library: &str,
    generation: i64,
    row: Row<'_>,
) -> rusqlite::Result<bool> {
    let mut columns = vec!["library", "id", "name", "modified", "gen", "data"];
    columns.extend(row.extra.iter().map(|(name, _)| *name));
    let placeholders: Vec<String> = (1..=columns.len()).map(|i| format!("?{i}")).collect();
    let updates: Vec<String> = columns[2..]
        .iter()
        .map(|c| format!("{c} = excluded.{c}"))
        .collect();
    let sql = format!(
        "INSERT INTO {table} ({}) VALUES ({}) ON CONFLICT(library, id) DO UPDATE SET {} \
         WHERE excluded.modified >= {table}.modified",
        columns.join(", "),
        placeholders.join(", "),
        updates.join(", ")
    );
    let mut values: Vec<SqlValue> = vec![
        SqlValue::Text(library.to_owned()),
        SqlValue::Text(row.id.to_owned()),
        row.name
            .map_or(SqlValue::Null, |n| SqlValue::Text(n.to_owned())),
        SqlValue::Integer(row.modified),
        SqlValue::Integer(generation),
        SqlValue::Text(row.data),
    ];
    values.extend(row.extra.into_iter().map(|(_, value)| value));
    let written = tx.prepare_cached(&sql)?.execute(params_from_iter(values))? > 0;
    if !written {
        tx.prepare_cached(&format!(
            "UPDATE {table} SET gen = ?1 WHERE library = ?2 AND id = ?3"
        ))?
        .execute(params![generation, library, row.id])?;
    }
    Ok(written)
}

fn int(value: Option<i64>) -> SqlValue {
    value.map_or(SqlValue::Null, SqlValue::Integer)
}

fn u64_value(value: Option<u64>) -> SqlValue {
    value
        .and_then(|v| i64::try_from(v).ok())
        .map_or(SqlValue::Null, SqlValue::Integer)
}

fn delete_media_links(tx: &Transaction<'_>, library: &str, media: &str) -> rusqlite::Result<()> {
    for link in MEDIA_LINK_TABLES {
        tx.prepare_cached(&format!(
            "DELETE FROM {link} WHERE library = ?1 AND media = ?2"
        ))?
        .execute(params![library, media])?;
    }
    Ok(())
}

/// Whether the library is in the mirror. Writes for a library that is not are dropped:
/// a sync still running when its library was removed must not bring its rows back.
/// Checked in the writing transaction, so a removal and a write cannot interleave.
fn library_stored(tx: &Transaction<'_>, library: &str) -> rusqlite::Result<bool> {
    tx.prepare_cached("SELECT 1 FROM libraries WHERE id = ?1")?
        .exists([library])
}

fn write_media(
    tx: &Transaction<'_>,
    library: &str,
    generation: i64,
    media: &MediaItem,
) -> rusqlite::Result<()> {
    let item = &media.item;
    let written = upsert(
        tx,
        "medias",
        library,
        generation,
        Row {
            id: &item.id,
            name: Some(&item.name),
            modified: item.modified.unwrap_or(0),
            data: to_json(media)?,
            extra: vec![
                ("type", SqlValue::Text(item.kind.to_string())),
                ("created", int(item.created)),
                ("added", int(item.added)),
                (
                    "rating",
                    item.rating
                        .map_or(SqlValue::Null, |r| SqlValue::Real(r.into())),
                ),
                ("size", u64_value(item.size)),
            ],
        },
    )?;
    if !written {
        return Ok(());
    }
    delete_media_links(tx, library, &item.id)?;
    let Some(relations) = &media.relations else {
        return Ok(());
    };
    for tag in relations.tags.iter().flatten() {
        tx.prepare_cached(
            "INSERT INTO media_tags (library, media, tag, conf) VALUES (?1, ?2, ?3, ?4)",
        )?
        .execute(params![library, item.id, tag.id, tag.conf])?;
    }
    for person in relations.people.iter().flatten() {
        tx.prepare_cached(
            "INSERT INTO media_people (library, media, person, conf) VALUES (?1, ?2, ?3, ?4)",
        )?
        .execute(params![library, item.id, person.id, person.conf])?;
    }
    for serie in relations.series.iter().flatten() {
        tx.prepare_cached(
            "INSERT INTO media_series (library, media, serie, season, episode, episode_to) \
             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
        )?
        .execute(params![
            library,
            item.id,
            serie.id,
            serie.season,
            serie.episode,
            serie.episode_to
        ])?;
    }
    for movie in relations.movies.iter().flatten() {
        tx.prepare_cached("INSERT INTO media_movies (library, media, movie) VALUES (?1, ?2, ?3)")?
            .execute(params![library, item.id, movie])?;
    }
    for book in relations.books.iter().flatten() {
        tx.prepare_cached("INSERT INTO media_books (library, media, book) VALUES (?1, ?2, ?3)")?
            .execute(params![library, item.id, book])?;
    }
    Ok(())
}

/// An item with relations whose new version has none (a live event) keeps the stored
/// ones.
fn keep_relations<T: Serialize + serde::de::DeserializeOwned>(
    tx: &Transaction<'_>,
    table: &str,
    library: &str,
    id: &str,
    item: &mut ItemWithRelations<T>,
) -> rusqlite::Result<()> {
    if item.relations.is_some() {
        return Ok(());
    }
    let stored: Option<String> = tx
        .prepare_cached(&format!(
            "SELECT data FROM {table} WHERE library = ?1 AND id = ?2"
        ))?
        .query_row(params![library, id], |row| row.get(0))
        .optional()?;
    if let Some(stored) = stored {
        let value: serde_json::Value = from_json(&stored)?;
        if let Some(relations) = value.get("relations") {
            item.relations = serde_json::from_value(relations.clone()).ok();
        }
    }
    Ok(())
}

/// Removes an item, unless it was modified after `date`.
fn remove(
    tx: &Transaction<'_>,
    library: &str,
    kind: SyncKind,
    id: &str,
    date: Option<i64>,
) -> rusqlite::Result<()> {
    let Some(table) = table(kind) else {
        return Ok(());
    };
    let removed = tx
        .prepare_cached(&format!(
            "DELETE FROM {table} WHERE library = ?1 AND id = ?2 AND modified <= ?3"
        ))?
        .execute(params![library, id, date.unwrap_or(i64::MAX)])?;
    if removed > 0 && kind == SyncKind::Medias {
        delete_media_links(tx, library, id)?;
    }
    Ok(())
}

fn apply_changes(
    tx: &Transaction<'_>,
    library: &str,
    generation: i64,
    changes: Changes,
) -> rusqlite::Result<()> {
    for tag in &changes.tags {
        upsert(
            tx,
            "tags",
            library,
            generation,
            Row {
                id: &tag.id,
                name: Some(&tag.name),
                modified: tag.modified as i64,
                data: to_json(tag)?,
                extra: vec![(
                    "parent",
                    tag.parent.clone().map_or(SqlValue::Null, SqlValue::Text),
                )],
            },
        )?;
    }
    for person in &changes.people {
        upsert(
            tx,
            "people",
            library,
            generation,
            Row {
                id: &person.id,
                name: Some(&person.name),
                modified: person.modified as i64,
                data: to_json(person)?,
                extra: Vec::new(),
            },
        )?;
    }
    for mut serie in changes.series {
        let id = serie.item.id.clone();
        keep_relations(tx, "series", library, &id, &mut serie)?;
        upsert(
            tx,
            "series",
            library,
            generation,
            Row {
                id: &serie.item.id,
                name: Some(&serie.item.name),
                modified: serie.item.modified as i64,
                data: to_json(&serie)?,
                extra: Vec::new(),
            },
        )?;
    }
    for mut movie in changes.movies {
        let id = movie.item.id.clone();
        keep_relations(tx, "movies", library, &id, &mut movie)?;
        upsert(
            tx,
            "movies",
            library,
            generation,
            Row {
                id: &movie.item.id,
                name: Some(&movie.item.name),
                modified: movie.item.modified as i64,
                data: to_json(&movie)?,
                extra: Vec::new(),
            },
        )?;
    }
    for episode in &changes.episodes {
        let id = episode.id();
        upsert(
            tx,
            "episodes",
            library,
            generation,
            Row {
                id: &id,
                name: episode.name.as_deref(),
                modified: episode.modified as i64,
                data: to_json(episode)?,
                extra: vec![
                    ("serie", SqlValue::Text(episode.serie.clone())),
                    ("season", SqlValue::Integer(episode.season.into())),
                    ("number", SqlValue::Integer(episode.number.into())),
                ],
            },
        )?;
    }
    for mut book in changes.books {
        let id = book.item.id.clone();
        keep_relations(tx, "books", library, &id, &mut book)?;
        upsert(
            tx,
            "books",
            library,
            generation,
            Row {
                id: &book.item.id,
                name: Some(&book.item.name),
                modified: book.item.modified as i64,
                data: to_json(&book)?,
                extra: Vec::new(),
            },
        )?;
    }
    for media in &changes.medias {
        write_media(tx, library, generation, media)?;
    }
    for removal in &changes.removed {
        remove(tx, library, removal.kind, &removal.id, removal.date)?;
    }
    Ok(())
}

fn remove_library_data(tx: &Transaction<'_>, library: &str) -> rusqlite::Result<()> {
    let tables = [
        "medias", "tags", "people", "series", "movies", "episodes", "books",
    ];
    for table in tables.iter().chain(MEDIA_LINK_TABLES.iter()) {
        tx.execute(
            &format!("DELETE FROM {table} WHERE library = ?1"),
            [library],
        )?;
    }
    tx.execute("DELETE FROM sync_state WHERE library = ?1", [library])?;
    tx.execute("DELETE FROM thumbs WHERE library = ?1", [library])?;
    Ok(())
}

/// The column a media sort orders by.
fn sort_column(sort: &RsSort) -> &'static str {
    match sort {
        RsSort::Modified => "m.modified",
        RsSort::Added => "m.added",
        RsSort::Created => "m.created",
        RsSort::Rating => "m.rating",
        RsSort::Name => "m.name",
        RsSort::Size => "m.size",
    }
}

/// `WHERE` and its parameters for a media query, like the server's: tags include
/// their child tags, several tags, people or series must all match, types any.
fn media_where(library: &str, query: &MediaQuery, with_page_key: bool) -> (String, Vec<SqlValue>) {
    let mut clauses = vec!["m.library = ?".to_owned()];
    let mut values = vec![SqlValue::Text(library.to_owned())];
    let text = |s: &str| SqlValue::Text(s.to_owned());

    if !query.types.is_empty() {
        let marks = vec!["?"; query.types.len()].join(", ");
        clauses.push(format!("m.type IN ({marks})"));
        values.extend(query.types.iter().map(|t| SqlValue::Text(t.to_string())));
    }
    for tag in &query.tags {
        let conf = if query.tags_confidence.is_some() {
            " AND IFNULL(conf, 100) >= ?"
        } else {
            ""
        };
        clauses.push(format!(
            "m.id IN (SELECT media FROM media_tags WHERE library = ? AND tag IN (\
             WITH RECURSIVE sub(id) AS (SELECT ? UNION SELECT t.id FROM tags t JOIN sub \
             ON t.parent = sub.id WHERE t.library = ?) SELECT id FROM sub){conf})"
        ));
        values.extend([text(library), text(tag), text(library)]);
        if let Some(conf) = query.tags_confidence {
            values.push(SqlValue::Integer(conf.into()));
        }
    }
    for person in &query.people {
        clauses.push(
            "m.id IN (SELECT media FROM media_people WHERE library = ? AND person = ?)".to_owned(),
        );
        values.extend([text(library), text(person)]);
    }
    for serie in &query.series {
        // `id`, `id|season` or `id|season|episode`.
        let mut parts = serie.split('|');
        let id = parts.next().unwrap_or_default();
        let mut clause =
            "m.id IN (SELECT media FROM media_series WHERE library = ? AND serie = ?".to_owned();
        values.extend([text(library), text(id)]);
        if let Some(season) = parts.next().and_then(|p| p.parse::<i64>().ok()) {
            clause.push_str(" AND season = ?");
            values.push(SqlValue::Integer(season));
        }
        if let Some(episode) = parts.next().and_then(|p| p.parse::<i64>().ok()) {
            // A file covering several episodes (`episode` to `episode_to`) matches each
            // of them, as on the server.
            clause.push_str(" AND (episode = ? OR (episode <= ? AND episode_to >= ?))");
            values.extend(std::iter::repeat_n(SqlValue::Integer(episode), 3));
        }
        clause.push(')');
        clauses.push(clause);
    }
    if let Some(movie) = &query.movie {
        clauses.push(
            "m.id IN (SELECT media FROM media_movies WHERE library = ? AND movie = ?)".to_owned(),
        );
        values.extend([text(library), text(movie)]);
    }
    if let Some(book) = &query.book {
        clauses.push(
            "m.id IN (SELECT media FROM media_books WHERE library = ? AND book = ?)".to_owned(),
        );
        values.extend([text(library), text(book)]);
    }
    let mut compare = |column: &str, op: &str, value: Option<i64>| {
        if let Some(value) = value {
            clauses.push(format!("{column} {op} ?"));
            values.push(SqlValue::Integer(value));
        }
    };
    compare("m.added", "<", query.added_before);
    compare("m.added", ">", query.added_after);
    compare("m.created", "<", query.created_before);
    compare("m.created", ">", query.created_after);
    compare("m.modified", "<", query.modified_before);
    compare("m.modified", ">", query.modified_after);
    // `before` and `after` apply to the sort's date, or to `modified`.
    let dated = match query.sort {
        RsSort::Added | RsSort::Created | RsSort::Modified => sort_column(&query.sort),
        _ => "m.modified",
    };
    compare(dated, "<", query.before);
    compare(dated, ">", query.after);
    compare(
        "m.size",
        ">=",
        query.min_size.and_then(|v| i64::try_from(v).ok()),
    );
    compare(
        "m.size",
        "<=",
        query.max_size.and_then(|v| i64::try_from(v).ok()),
    );
    compare(
        "json_extract(m.data, '$.duration')",
        ">",
        query.min_duration.and_then(|v| i64::try_from(v).ok()),
    );
    compare(
        "json_extract(m.data, '$.duration')",
        "<",
        query.max_duration.and_then(|v| i64::try_from(v).ok()),
    );
    if let Some(rating) = query.min_rating {
        clauses.push("m.rating >= ?".to_owned());
        values.push(SqlValue::Real(rating.into()));
    }
    if let Some(rating) = query.max_rating {
        clauses.push("m.rating <= ?".to_owned());
        values.push(SqlValue::Real(rating.into()));
    }
    if let Some(search) = &query.text {
        clauses.push("(m.name LIKE ? OR json_extract(m.data, '$.description') LIKE ?)".to_owned());
        let pattern = format!("%{search}%");
        values.extend([text(&pattern), text(&pattern)]);
    }
    if let Some(key) = &query.uploadkey {
        clauses.push("json_extract(m.data, '$.uploadkey') = ?".to_owned());
        values.push(text(key));
    }
    // The server's keyset key, `<sort value>|<id>`, for the date and size sorts.
    if with_page_key
        && let Some((value, id)) = query.page_key.as_deref().and_then(|k| k.split_once('|'))
        && let Ok(value) = value.parse::<i64>()
        && !matches!(query.sort, RsSort::Name | RsSort::Rating)
    {
        let op = if query.order == SqlOrder::DESC {
            "<"
        } else {
            ">"
        };
        let column = sort_column(&query.sort);
        clauses.push(format!(
            "({column} {op} ? OR ({column} = ? AND m.id {op} ?))"
        ));
        values.extend([SqlValue::Integer(value), SqlValue::Integer(value), text(id)]);
    }
    (format!("WHERE {}", clauses.join(" AND ")), values)
}

fn media_order(query: &MediaQuery) -> String {
    let order = if query.order == SqlOrder::ASC {
        "ASC"
    } else {
        "DESC"
    };
    let column = sort_column(&query.sort);
    let collate = if query.sort == RsSort::Name {
        " COLLATE NOCASE"
    } else {
        ""
    };
    if query.sort == RsSort::Rating {
        format!("ORDER BY {column} {order}, m.added DESC, m.id {order}")
    } else {
        format!("ORDER BY {column}{collate} {order}, m.id {order}")
    }
}

fn thumb_record(row: &rusqlite::Row<'_>) -> rusqlite::Result<ThumbRecord> {
    Ok(ThumbRecord {
        library: row.get(0)?,
        media: row.get(1)?,
        size: row.get::<_, i64>(2)?.max(0) as u64,
        version: row.get(3)?,
    })
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl MirrorStore for SqliteStore {
    async fn libraries(&self) -> Result<Vec<ServerLibraryForRead>> {
        self.read(|conn| {
            let mut statement = conn.prepare("SELECT data FROM libraries ORDER BY position")?;
            let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
            rows.map(|data| from_json(&data?)).collect()
        })
        .await
    }

    async fn set_libraries(&self, libraries: Vec<ServerLibraryForRead>) -> Result<Vec<String>> {
        self.write(move |tx| {
            let existing: Vec<String> = {
                let mut statement = tx.prepare("SELECT id FROM libraries")?;
                let rows = statement.query_map([], |row| row.get(0))?;
                rows.collect::<rusqlite::Result<_>>()?
            };
            let removed: Vec<String> = existing
                .into_iter()
                .filter(|id| !libraries.iter().any(|l| &l.id == id))
                .collect();
            for id in &removed {
                remove_library_data(tx, id)?;
            }
            tx.execute("DELETE FROM libraries", [])?;
            for (position, library) in libraries.iter().enumerate() {
                tx.execute(
                    "INSERT INTO libraries (id, position, data) VALUES (?1, ?2, ?3)",
                    params![library.id, position as i64, to_json(library)?],
                )?;
            }
            Ok(removed)
        })
        .await
    }

    async fn put_library(&self, library: ServerLibraryForRead) -> Result<()> {
        self.write(move |tx| {
            tx.execute(
                "INSERT INTO libraries (id, position, data) VALUES (?1, \
                 (SELECT IFNULL(MAX(position), -1) + 1 FROM libraries), ?2) \
                 ON CONFLICT(id) DO UPDATE SET data = excluded.data",
                params![library.id, to_json(&library)?],
            )?;
            Ok(())
        })
        .await
    }

    async fn remove_library(&self, library: &str) -> Result<()> {
        let library = library.to_owned();
        self.write(move |tx| {
            remove_library_data(tx, &library)?;
            tx.execute("DELETE FROM libraries WHERE id = ?1", [&library])?;
            Ok(())
        })
        .await
    }

    async fn sync_state(&self, library: &str) -> Result<Option<SyncState>> {
        let library = library.to_owned();
        let text: Option<String> = self
            .read(move |conn| {
                conn.query_row(
                    "SELECT state FROM sync_state WHERE library = ?1",
                    [&library],
                    |row| row.get(0),
                )
                .optional()
            })
            .await?;
        // An unreadable state is a missing one: the next sync repairs the library.
        Ok(text.and_then(|text| serde_json::from_str(&text).ok()))
    }

    async fn set_sync_state(&self, library: &str, state: SyncState) -> Result<()> {
        let library = library.to_owned();
        self.write(move |tx| {
            if !library_stored(tx, &library)? {
                return Ok(());
            }
            tx.execute(
                "INSERT INTO sync_state (library, state) VALUES (?1, ?2) \
                 ON CONFLICT(library) DO UPDATE SET state = excluded.state",
                params![library, to_json(&state)?],
            )?;
            Ok(())
        })
        .await
    }

    async fn apply(&self, library: &str, generation: i64, changes: Changes) -> Result<()> {
        let library = library.to_owned();
        self.write(move |tx| {
            if !library_stored(tx, &library)? {
                return Ok(());
            }
            apply_changes(tx, &library, generation, changes)
        })
        .await
    }

    async fn sweep(&self, library: &str, kind: SyncKind, generation: i64) -> Result<Vec<String>> {
        let Some(table) = table(kind) else {
            return Ok(Vec::new());
        };
        let library = library.to_owned();
        self.write(move |tx| {
            let ids: Vec<String> = {
                let mut statement = tx.prepare(&format!(
                    "SELECT id FROM {table} WHERE library = ?1 AND gen < ?2"
                ))?;
                let rows = statement.query_map(params![library, generation], |row| row.get(0))?;
                rows.collect::<rusqlite::Result<_>>()?
            };
            for id in &ids {
                remove(tx, &library, kind, id, None)?;
            }
            Ok(ids)
        })
        .await
    }

    async fn medias(
        &self,
        library: &str,
        query: MediaQuery,
        offset: usize,
    ) -> Result<Vec<MediaItem>> {
        let library = library.to_owned();
        self.read(move |conn| {
            let (filter, mut values) = media_where(&library, &query, true);
            let limit = query
                .limit
                .and_then(|l| i64::try_from(l).ok())
                .unwrap_or(-1);
            values.push(SqlValue::Integer(limit));
            values.push(SqlValue::Integer(i64::try_from(offset).unwrap_or(i64::MAX)));
            let sql = format!(
                "SELECT m.data FROM medias m {filter} {} LIMIT ? OFFSET ?",
                media_order(&query)
            );
            let mut statement = conn.prepare_cached(&sql)?;
            let rows =
                statement.query_map(params_from_iter(values), |row| row.get::<_, String>(0))?;
            rows.map(|data| from_json(&data?)).collect()
        })
        .await
    }

    async fn count_medias(&self, library: &str, query: MediaQuery) -> Result<u64> {
        let library = library.to_owned();
        self.read(move |conn| {
            let (filter, values) = media_where(&library, &query, false);
            let count: i64 = conn
                .prepare_cached(&format!("SELECT COUNT(*) FROM medias m {filter}"))?
                .query_row(params_from_iter(values), |row| row.get(0))?;
            Ok(count.max(0) as u64)
        })
        .await
    }

    async fn media(&self, library: &str, id: &str) -> Result<Option<MediaItem>> {
        let (library, id) = (library.to_owned(), id.to_owned());
        self.read(move |conn| {
            let data: Option<String> = conn
                .prepare_cached("SELECT data FROM medias WHERE library = ?1 AND id = ?2")?
                .query_row(params![library, id], |row| row.get(0))
                .optional()?;
            data.map(|data| from_json(&data)).transpose()
        })
        .await
    }

    async fn items(
        &self,
        library: &str,
        kind: SyncKind,
        serie: Option<String>,
    ) -> Result<Vec<serde_json::Value>> {
        let Some(table) = table(kind) else {
            return Ok(Vec::new());
        };
        let library = library.to_owned();
        self.read(move |conn| {
            let mut sql = format!("SELECT data FROM {table} WHERE library = ?1");
            let mut values = vec![SqlValue::Text(library)];
            if kind == SyncKind::Episodes {
                if let Some(serie) = serie {
                    sql.push_str(" AND serie = ?2");
                    values.push(SqlValue::Text(serie));
                }
                sql.push_str(" ORDER BY serie, season, number");
            } else if kind == SyncKind::Medias {
                sql.push_str(" ORDER BY modified DESC, id DESC");
            } else {
                sql.push_str(" ORDER BY name COLLATE NOCASE, id");
            }
            let mut statement = conn.prepare_cached(&sql)?;
            let rows =
                statement.query_map(params_from_iter(values), |row| row.get::<_, String>(0))?;
            rows.map(|data| from_json(&data?)).collect()
        })
        .await
    }

    async fn count(&self, library: &str, kind: SyncKind) -> Result<u64> {
        let Some(table) = table(kind) else {
            return Ok(0);
        };
        let library = library.to_owned();
        self.read(move |conn| {
            let count: i64 = conn.query_row(
                &format!("SELECT COUNT(*) FROM {table} WHERE library = ?1"),
                [library],
                |row| row.get(0),
            )?;
            Ok(count.max(0) as u64)
        })
        .await
    }

    async fn thumb(&self, library: &str, media: &str) -> Result<Option<ThumbRecord>> {
        let (library, media) = (library.to_owned(), media.to_owned());
        self.write(move |tx| {
            tx.prepare_cached("UPDATE thumbs SET accessed = ?1 WHERE library = ?2 AND media = ?3")?
                .execute(params![now_ms(), library, media])?;
            tx.prepare_cached(
                "SELECT library, media, size, version FROM thumbs WHERE library = ?1 AND media = ?2",
            )?
            .query_row(params![library, media], thumb_record)
            .optional()
        })
        .await
    }

    async fn put_thumb(&self, record: ThumbRecord) -> Result<()> {
        self.write(move |tx| {
            if !library_stored(tx, &record.library)? {
                return Ok(());
            }
            tx.prepare_cached(
                "INSERT INTO thumbs (library, media, size, version, accessed) VALUES (?1, ?2, ?3, ?4, ?5) \
                 ON CONFLICT(library, media) DO UPDATE SET size = excluded.size, \
                 version = excluded.version, accessed = excluded.accessed",
            )?
            .execute(params![
                record.library,
                record.media,
                i64::try_from(record.size).unwrap_or(i64::MAX),
                record.version,
                now_ms()
            ])?;
            Ok(())
        })
        .await
    }

    async fn remove_thumbs(&self, library: &str, medias: Vec<String>) -> Result<()> {
        let library = library.to_owned();
        self.write(move |tx| {
            for media in &medias {
                tx.prepare_cached("DELETE FROM thumbs WHERE library = ?1 AND media = ?2")?
                    .execute(params![library, media])?;
            }
            Ok(())
        })
        .await
    }

    async fn thumbs_size(&self) -> Result<u64> {
        self.read(|conn| {
            let size: i64 =
                conn.query_row("SELECT IFNULL(SUM(size), 0) FROM thumbs", [], |row| {
                    row.get(0)
                })?;
            Ok(size.max(0) as u64)
        })
        .await
    }

    async fn thumbs_over(&self, limit: u64) -> Result<Vec<ThumbRecord>> {
        self.read(move |conn| {
            let total: i64 =
                conn.query_row("SELECT IFNULL(SUM(size), 0) FROM thumbs", [], |row| {
                    row.get(0)
                })?;
            let mut excess = (total.max(0) as u64).saturating_sub(limit);
            let mut over = Vec::new();
            if excess == 0 {
                return Ok(over);
            }
            let mut statement = conn.prepare(
                "SELECT library, media, size, version FROM thumbs ORDER BY accessed ASC, rowid ASC",
            )?;
            let rows = statement.query_map([], thumb_record)?;
            for record in rows {
                let record = record?;
                excess = excess.saturating_sub(record.size.max(1));
                over.push(record);
                if excess == 0 {
                    break;
                }
            }
            Ok(over)
        })
        .await
    }
}