redseat-api 0.12.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
//! A server through its local copy, as the screens show it: [`ServerCopy`].

use std::borrow::Borrow;
use std::collections::{BTreeMap, HashMap};
use std::future::Future;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use futures_util::future::{AbortHandle, Either, abortable, select};
use tokio::sync::{Notify, broadcast};

use super::details::Names;
use super::reveal::Reveal;
use super::text;
use crate::client::AuthorizedUrl;
use crate::error::{Error, Result};
use crate::library::MediaItem;
use crate::mirror::runtime::{Task, spawn, timeout};
use crate::mirror::{
    BoxFuture, ConnectionState, ItemIds, ItemImage, LibrarySyncState, Mirror, MirrorEvent, Related,
    Runtime, SyncKind,
};
use crate::server::ServerApi;
use crate::types::ItemWithRelations;
use crate::types::book::Book;
use crate::types::episode::Episode;
use crate::types::library::{LibraryType, ServerLibraryForRead};
use crate::types::media::{MediaFileQuery, MediaQuery, RsSort, SqlOrder};
use crate::types::movie::Movie;
use crate::types::person::Person;
use crate::types::serie::Serie;
use crate::types::tag::Tag;

/// Changes arriving within this of the first are announced together (a sync's pages):
/// a screen reads a library again at most about four times a second.
pub const BURST: Duration = Duration::from_millis(250);

/// How long [`ServerCopy::ready`] waits for a server never connected before.
pub const FIRST_WAIT: Duration = Duration::from_secs(10);

/// Medias past which a sync shows its progress instead of the grid.
pub const BIG_SYNC: u64 = 500;

/// How long reading the server's address and token may take.
const BASE_WAIT: Duration = Duration::from_secs(10);

/// Past this many ids of one kind in a burst, a change gives [`Ids::Many`] instead.
pub const MAX_IDS: usize = 1000;

/// The items of one kind a [`Change::Library`] touched.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ids {
    /// These items were added, updated or removed (the net change over the burst).
    Listed(ItemIds),
    /// More than [`MAX_IDS`] (a sync of many items): read them all again.
    Many,
}

impl Ids {
    fn merge(&mut self, later: ItemIds) {
        if let Ids::Listed(ids) = self {
            ids.merge(later);
            if ids.len() > MAX_IDS {
                *self = Ids::Many;
            }
        }
    }
}

/// What changed in a [`ServerCopy`]: read it again.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
    /// The server: its library list, its connection ([`ServerCopy::reach`]) or its
    /// address and token ([`ServerCopy::base`]).
    Server,
    /// A library: its count or its sync ([`ServerCopy::library`]), and the items of
    /// each kind that changed (`items`; empty when only its sync moved on).
    ///
    /// A grid can patch its cells from the ids when every updated media is one it shows
    /// and keeps its date. An updated media it does not show may have moved into view
    /// (a new date), and an added or removed one moves those after it: it then reads
    /// the medias it shows again. While the
    /// library syncs its grid holds still instead ([`LibraryView`]), and the sync's end
    /// brings a new revision. Removals count under their own kind, never
    /// [`SyncKind::Deleted`].
    Library {
        library: String,
        items: BTreeMap<SyncKind, Ids>,
    },
    /// Changes were missed: everything may have changed.
    All,
}

impl Change {
    /// The library a [`Change::Library`] is about.
    pub fn library(&self) -> Option<&str> {
        match self {
            Change::Library { library, .. } => Some(library),
            _ => None,
        }
    }

    /// The items of `kind` that changed, for a view showing that kind: `None` when
    /// none did, [`Ids::Many`] after [`Change::All`].
    pub fn ids(&self, kind: SyncKind) -> Option<Ids> {
        match self {
            Change::Library { items, .. } => items.get(&kind).cloned(),
            Change::All => Some(Ids::Many),
            Change::Server => None,
        }
    }

    /// Whether items of `kind` may have changed: listed in a [`Change::Library`], or
    /// [`Change::All`].
    pub fn touches(&self, kind: SyncKind) -> bool {
        match self {
            Change::Library { items, .. } => items.contains_key(&kind),
            Change::All => true,
            Change::Server => false,
        }
    }
}

/// Told each [`Change`], at the end of its burst ([`BURST`]), on the runtime's
/// threads: a UI hands it to its own thread. Any closure taking a `&Change`.
#[cfg(not(target_arch = "wasm32"))]
pub trait OnChange: Fn(&Change) + Send + Sync + 'static {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Fn(&Change) + Send + Sync + 'static> OnChange for T {}
/// Told each [`Change`], at the end of its burst ([`BURST`]). Any closure taking a
/// `&Change`.
#[cfg(target_arch = "wasm32")]
pub trait OnChange: Fn(&Change) + 'static {}
#[cfg(target_arch = "wasm32")]
impl<T: Fn(&Change) + 'static> OnChange for T {}

/// The listener a copy keeps.
#[cfg(not(target_arch = "wasm32"))]
type Listener = Arc<dyn Fn(&Change) + Send + Sync>;
#[cfg(target_arch = "wasm32")]
type Listener = Arc<dyn Fn(&Change)>;

/// How the copy reaches its server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reach {
    /// [`ServerCopy::connect`] was not called, or [`ServerCopy::disconnect`] was.
    Disconnected,
    /// Getting the server's address and token, or its events.
    Connecting,
    /// Following the server's events: the copy is kept in sync.
    Connected,
    /// The server cannot be reached. With `retry`, the connection could not be made
    /// and [`ServerCopy::connect`] must be called again (a Retry button); without, the
    /// event stream broke and the copy reconnects by itself.
    Offline { reason: String, retry: bool },
}

/// A library as its grid shows it.
///
/// While it syncs, the grid does not follow the copy (thousands of medias at a time
/// would make it jump): `count` and `revision` stay those shown. `revision` is new at
/// the first read, when a sync ended and when the count changed: the grid then reads
/// its medias again. Another change that leaves the count ([`Change::Library`] while
/// not syncing) changes medias in place: the grid reads the ones it shows again, or only
/// those its ids name.
#[derive(Debug, Clone)]
pub struct LibraryView {
    pub library: ServerLibraryForRead,
    pub count: u64,
    pub revision: u64,
    /// Queued or syncing.
    pub syncing: bool,
    /// A first sync, or one bringing more than [`BIG_SYNC`] medias: its progress shows
    /// instead of the grid.
    pub copying: bool,
    /// What the sync is doing ([`text::sync_progress`]), while `copying`; else "".
    pub sync_detail: String,
    /// The sync's progress in percent, while `copying` and when the server gave a total.
    pub sync_percent: Option<f64>,
}

/// The order of the grid: newest first.
pub fn grid_query() -> MediaQuery {
    MediaQuery {
        sort: RsSort::Created,
        order: SqlOrder::DESC,
        ..Default::default()
    }
}

/// Library types in the sidebar's order.
const TYPE_ORDER: [LibraryType; 6] = [
    LibraryType::Photos,
    LibraryType::Movies,
    LibraryType::Shows,
    LibraryType::Books,
    LibraryType::Iptv,
    LibraryType::Other,
];

/// Sorts libraries in the sidebar's order: by type, then by name.
pub fn sort_libraries<L: Borrow<ServerLibraryForRead>>(libraries: &mut [L]) {
    let rank = |kind: &LibraryType| TYPE_ORDER.iter().position(|k| k == kind);
    libraries.sort_by_cached_key(|l| {
        let l = l.borrow();
        (rank(&l.kind), l.name.to_lowercase())
    });
}

/// `text` as a URL path segment: what is not unreserved is %-escaped.
fn escaped(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for byte in text.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(byte as char)
            }
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

/// A media's thumbnail on the server at `base` (no trailing slash), as
/// `LibraryApi::get_thumb_raw` asks for it, with its version: with `v` the media's
/// current `thumbv` (0 when it has none), the server lets it be cached for a year. The
/// token goes in the request's `Authorization` header, not here.
pub fn thumb_url(base: &str, library: &str, media: &str, version: u64) -> String {
    format!(
        "{base}/libraries/{}/medias/{}/image?size=thumb&v={version}",
        escaped(library),
        escaped(media),
    )
}

/// A media's file on the server at `base` (no trailing slash), as
/// `LibraryApi::media_url` gives it. The token goes in the request's `Authorization`
/// header, not here.
pub fn media_file_url(base: &str, library: &str, media: &str, query: &MediaFileQuery) -> String {
    let mut params: Vec<String> = (query.unsupported_mime.iter())
        .map(|mime| format!("unsupportedMime={}", escaped(mime)))
        .collect();
    if let Some(page) = query.page {
        params.push(format!("page={page}"));
    }
    if query.raw {
        params.push("raw=true".to_owned());
    }
    let query = if params.is_empty() {
        String::new()
    } else {
        format!("?{}", params.join("&"))
    };
    format!(
        "{base}/libraries/{}/medias/{}{query}",
        escaped(library),
        escaped(media)
    )
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Where the connection stands, before the mirror's own.
#[derive(Debug, Clone)]
enum Link {
    Idle,
    Connecting,
    Connected,
    Failed(String),
}

/// What a library's grid shows: its revision and count, whether it was syncing, and
/// whether the sync under way is big enough to show its progress instead.
#[derive(Debug, Clone, Copy)]
struct Held {
    revision: u64,
    count: u64,
    syncing: bool,
    big: bool,
    /// Bumped by each mark of the event follower (a sync started, events were missed):
    /// a read that a mark overtook keeps it.
    marks: u64,
}

impl Held {
    /// The library may have changed in a way its count does not show: the next read
    /// brings a new revision.
    fn mark(&mut self) {
        self.syncing = true;
        self.marks += 1;
    }
}

/// The names read per library, until it changes. `generation` counts the changes, so a
/// read that a change overtook is not kept. Each is kept with whether its library was
/// unlocked (its text key known): names read while locked are still encrypted, and
/// are read again once it is.
#[derive(Default)]
struct NamesCache {
    generation: u64,
    libraries: HashMap<String, (bool, Arc<Names>)>,
}

impl NamesCache {
    /// Forgets a library's names, or every library's.
    fn forget(&mut self, library: Option<&str>) {
        self.generation += 1;
        match library {
            Some(library) => {
                self.libraries.remove(library);
            }
            None => self.libraries.clear(),
        }
    }

    /// The names kept for a library, read while it was `unlocked` as it is now.
    fn get(&self, library: &str, unlocked: bool) -> Option<Arc<Names>> {
        (self.libraries.get(library))
            .filter(|(kept_unlocked, _)| *kept_unlocked == unlocked)
            .map(|(_, names)| Arc::clone(names))
    }

    /// Keeps names read from `generation` on, while the library was `unlocked`, unless
    /// a change came since: they may be stale.
    fn keep(&mut self, library: &str, generation: u64, unlocked: bool, names: &Arc<Names>) {
        if self.generation == generation {
            (self.libraries).insert(library.to_owned(), (unlocked, Arc::clone(names)));
        }
    }
}

/// A server through its local copy ([`Mirror`]): reads answer at once from the copy,
/// offline too, while a connection in the background keeps it in sync. What changes is
/// told to the listener given at the start ([`OnChange`]), grouped over [`BURST`].
///
/// A cheap handle: clones share one copy (every screen keeps its own). Dropping the
/// last one stops the background work; the copy stays on disk.
#[derive(Clone)]
pub struct ServerCopy {
    shared: Arc<Shared>,
}

/// What the handles of one copy share.
struct Shared {
    /// Follows the mirror's events.
    follow: Task,
    mirror: Mirror,
    runtime: Arc<dyn Runtime>,
    listener: Listener,
    link: Mutex<Link>,
    /// Bumped by each connect and disconnect: an older connection does not land.
    attempt: AtomicU64,
    /// The connection, with the attempt that made it.
    api: Mutex<Option<(u64, ServerApi)>>,
    /// Stops the connection under way: on a new one, a disconnect or the drop.
    connecting: Mutex<Option<AbortHandle>>,
    base: Mutex<Option<AuthorizedUrl>>,
    /// Woken by every mirror event and connection: what [`Self::ready`] waits on.
    woken: Arc<Notify>,
    revision: Mutex<u64>,
    /// Shared with the event follower, which marks a library whose sync started: a
    /// sync over between two reads still brings a new revision.
    held: Arc<Mutex<HashMap<String, Held>>>,
    names: Arc<Mutex<NamesCache>>,
}

impl std::fmt::Debug for ServerCopy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServerCopy")
            .field("link", &*lock(&self.shared.link))
            .finish_non_exhaustive()
    }
}

impl Drop for Shared {
    fn drop(&mut self) {
        self.follow.abort();
        if let Some(connecting) = lock(&self.connecting).take() {
            connecting.abort();
        }
    }
}

impl ServerCopy {
    /// Opens the copy at `options.path` on the tokio runtime this is called in (native
    /// targets). Its reads answer at once; [`Self::connect`] keeps it in sync.
    #[cfg(all(feature = "sqlite", not(target_arch = "wasm32")))]
    pub async fn open(
        options: crate::mirror::MirrorOptions,
        listener: impl OnChange,
    ) -> Result<ServerCopy> {
        if let Some(folder) = options.path.parent() {
            tokio::fs::create_dir_all(folder)
                .await
                .map_err(|error| Error::Storage {
                    message: format!("cannot create the copy's folder: {error}"),
                })?;
        }
        let runtime = Arc::new(tokio::runtime::Handle::current());
        let mirror = Mirror::open(options).await?;
        Ok(ServerCopy::with_mirror(mirror, runtime, listener))
    }

    /// A copy on a mirror the app opened, its background work on `runtime`.
    pub fn with_mirror(
        mirror: Mirror,
        runtime: Arc<dyn Runtime>,
        listener: impl OnChange,
    ) -> ServerCopy {
        let listener: Listener = Arc::new(listener);
        let woken = Arc::new(Notify::new());
        let names = Arc::new(Mutex::new(NamesCache::default()));
        let held = Arc::new(Mutex::new(HashMap::new()));
        // Stopped with the copy: an app may keep a clone of the mirror, whose events
        // would otherwise keep it running.
        let follow = spawn(
            runtime.as_ref(),
            Box::pin(follow(
                mirror.subscribe(),
                Arc::clone(&runtime),
                Arc::clone(&listener),
                Arc::clone(&woken),
                Arc::clone(&held),
                Arc::clone(&names),
            )),
        );
        ServerCopy {
            shared: Arc::new(Shared {
                follow,
                mirror,
                runtime,
                listener,
                link: Mutex::new(Link::Idle),
                attempt: AtomicU64::new(0),
                api: Mutex::default(),
                connecting: Mutex::default(),
                base: Mutex::default(),
                woken,
                revision: Mutex::new(0),
                held,
                names,
            }),
        }
    }

    /// The copy itself, for what this does not cover (passphrases, thumbnails, hidden
    /// libraries...).
    pub fn mirror(&self) -> &Mirror {
        &self.shared.mirror
    }

    /// Connects the copy with the server `connecting` gives, in the background: every
    /// library then syncs, the open one first, and the server's live events apply.
    /// Calling it again (Retry) replaces the connection.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn connect<E: std::fmt::Display + 'static>(
        &self,
        connecting: impl Future<Output = std::result::Result<ServerApi, E>> + Send + 'static,
    ) {
        self.start_connect(Box::pin(async move {
            connecting.await.map_err(|error| error.to_string())
        }));
    }

    /// Connects the copy with the server `connecting` gives, in the background: every
    /// library then syncs, the open one first, and the server's live events apply.
    /// Calling it again (Retry) replaces the connection.
    #[cfg(target_arch = "wasm32")]
    pub fn connect<E: std::fmt::Display + 'static>(
        &self,
        connecting: impl Future<Output = std::result::Result<ServerApi, E>> + 'static,
    ) {
        self.start_connect(Box::pin(async move {
            connecting.await.map_err(|error| error.to_string())
        }));
    }

    fn start_connect(&self, connecting: BoxFuture<std::result::Result<ServerApi, String>>) {
        let (connecting, handle) = abortable(connecting);
        let attempt = {
            // The link's lock orders connections and disconnects: see `disconnect`.
            let mut link = lock(&self.shared.link);
            *link = Link::Connecting;
            if let Some(previous) = lock(&self.shared.connecting).replace(handle) {
                previous.abort();
            }
            self.shared.attempt.fetch_add(1, Ordering::SeqCst) + 1
        };
        // Not kept alive by its connection: a dropped copy stops it.
        let copy = Arc::downgrade(&self.shared);
        let listener = Arc::clone(&self.shared.listener);
        self.shared.runtime.spawn(Box::pin(async move {
            listener(&Change::Server);
            let Ok(result) = connecting.await else {
                return;
            };
            let Some(shared) = copy.upgrade() else {
                return;
            };
            let copy = ServerCopy { shared };
            let connected = {
                // Checked and installed under the link's lock: a disconnect or a new
                // connection lands before or after, never in between.
                let mut link = lock(&copy.shared.link);
                if copy.shared.attempt.load(Ordering::SeqCst) != attempt {
                    return;
                }
                match result {
                    Ok(api) => {
                        copy.shared.mirror.connect(api.clone());
                        *lock(&copy.shared.api) = Some((attempt, api));
                        *link = Link::Connected;
                        true
                    }
                    Err(reason) => {
                        // No connection is left from before: a failed one never
                        // coexists with a live one.
                        *link = Link::Failed(reason);
                        lock(&copy.shared.api).take();
                        lock(&copy.shared.base).take();
                        copy.shared.mirror.disconnect();
                        false
                    }
                }
            };
            if connected {
                copy.refresh_base().await;
            }
            copy.shared.woken.notify_waiters();
            (copy.shared.listener)(&Change::Server);
        }));
    }

    /// Stops following the server, or connecting to it; the copy stays and answers
    /// offline. Told as a [`Change::Server`].
    pub fn disconnect(&self) {
        {
            let mut link = lock(&self.shared.link);
            self.shared.attempt.fetch_add(1, Ordering::SeqCst);
            if let Some(connecting) = lock(&self.shared.connecting).take() {
                connecting.abort();
            }
            *link = Link::Idle;
            lock(&self.shared.api).take();
            lock(&self.shared.base).take();
            self.shared.mirror.disconnect();
        }
        self.shared.woken.notify_waiters();
        // From the runtime, as every change: never inside the app's own call.
        let listener = Arc::clone(&self.shared.listener);
        self.shared
            .runtime
            .spawn(Box::pin(async move { listener(&Change::Server) }));
    }

    /// The server's connection, once made.
    pub fn api(&self) -> Option<ServerApi> {
        lock(&self.shared.api).clone().map(|(_, api)| api)
    }

    /// How the copy reaches its server.
    pub fn reach(&self) -> Reach {
        match &*lock(&self.shared.link) {
            Link::Idle => Reach::Disconnected,
            Link::Connecting => Reach::Connecting,
            Link::Failed(reason) => Reach::Offline {
                reason: reason.clone(),
                retry: true,
            },
            Link::Connected => match self.shared.mirror.status().connection {
                ConnectionState::Connected => Reach::Connected,
                ConnectionState::Offline(reason) => Reach::Offline {
                    reason,
                    retry: false,
                },
                ConnectionState::Connecting | ConnectionState::Disconnected => Reach::Connecting,
            },
        }
    }

    /// Whether a wait for the server would wait for nothing: not connecting, or it
    /// cannot be reached now.
    fn unreachable(&self) -> bool {
        matches!(self.reach(), Reach::Disconnected | Reach::Offline { .. })
    }

    /// For a server never connected before: waits until its libraries are known (with
    /// `library`, until that one is), the server cannot be reached, or [`FIRST_WAIT`]
    /// passed. At once when the copy has them already.
    pub async fn ready(&self, library: Option<&str>) {
        let known = async || match library {
            // Connected, the library list was read: a library not in it is gone.
            Some(library) => {
                matches!(self.shared.mirror.library(library).await, Ok(Some(_)))
                    || self.shared.mirror.status().connection == ConnectionState::Connected
            }
            None => {
                !self
                    .shared
                    .mirror
                    .libraries()
                    .await
                    .unwrap_or_default()
                    .is_empty()
                    || self.shared.mirror.status().connection == ConnectionState::Connected
            }
        };
        let wait = async {
            loop {
                let woken = self.shared.woken.notified();
                if known().await || self.unreachable() {
                    return;
                }
                woken.await;
            }
        };
        timeout(self.shared.runtime.as_ref(), FIRST_WAIT, wait).await;
    }

    /// The libraries in the sidebar's order ([`sort_libraries`]), hidden ones included
    /// (`hidden` set): an app shows those only once revealed.
    pub async fn libraries(&self) -> Result<Vec<ServerLibraryForRead>> {
        let mut libraries = self.shared.mirror.libraries().await?;
        sort_libraries(&mut libraries);
        Ok(libraries)
    }

    /// Whether a library syncs (queued or under way).
    pub fn syncing(&self, library: &str) -> bool {
        matches!(
            self.shared.mirror.status().libraries.get(library),
            Some(LibrarySyncState::Queued | LibrarySyncState::Syncing(_))
        )
    }

    /// What the sync of the library on screen, or of the others, is doing, for a
    /// status bar ([`text::sync_summary`]).
    pub fn sync_summary(&self, library: Option<&str>) -> Option<String> {
        text::sync_summary(&self.shared.mirror.status(), library)
    }

    /// The library the person is looking at, which syncs first; `None` for none. Only a
    /// change counts: setting it queues the library's sync again. Reads never set it, so
    /// several screens can read several libraries.
    pub fn focus(&self, library: Option<&str>) {
        if self.shared.mirror.priority().as_deref() != library {
            self.shared.mirror.set_priority(library);
        }
    }

    /// A library as its grid shows it (see [`LibraryView`]). A server never connected
    /// before is waited for ([`Self::ready`]). It does not make the library sync first:
    /// see [`Self::focus`].
    pub async fn library(&self, library: &str) -> Result<LibraryView> {
        self.ready(Some(library)).await;
        let found = self
            .shared
            .mirror
            .library(library)
            .await?
            .ok_or_else(|| Error::NotFound {
                message: format!("No library {library} on this server."),
                path: None,
            })?;
        let state = self.shared.mirror.status().libraries.get(library).cloned();
        let syncing = matches!(
            state,
            Some(LibrarySyncState::Queued | LibrarySyncState::Syncing(_))
        );
        let held = lock(&self.shared.held).get(library).copied();
        let marks = held.map_or(0, |held| held.marks);
        let shown = match held {
            Some(held) if syncing => held,
            _ => {
                let count = self.count(library, &grid_query()).await?;
                let revision = match held {
                    // Nothing a `Change::Library` does not bring.
                    Some(held) if !held.syncing && held.count == count => held.revision,
                    _ => {
                        let mut revision = lock(&self.shared.revision);
                        *revision += 1;
                        *revision
                    }
                };
                Held {
                    revision,
                    count,
                    syncing: false,
                    big: false,
                    marks,
                }
            }
        };
        // A first copy, or a sync of many medias. Not an empty library syncing again.
        let big = syncing
            && (shown.big
                || matches!(&state, Some(LibrarySyncState::Syncing(p))
                    if p.kind == SyncKind::Medias && p.total.unwrap_or(0) > BIG_SYNC)
                || !self.shared.mirror.synced_once(library).await?);
        {
            let mut held = lock(&self.shared.held);
            // A mark that came during the reads above is kept.
            let current = held.get(library).map_or(marks, |held| held.marks);
            held.insert(
                library.into(),
                Held {
                    big,
                    syncing: syncing || current != marks,
                    marks: current,
                    ..shown
                },
            );
        }
        let (detail, percent) = text::sync_progress(state.as_ref());
        Ok(LibraryView {
            library: found,
            count: shown.count,
            revision: shown.revision,
            syncing,
            copying: big,
            sync_detail: if big { detail } else { String::new() },
            sync_percent: percent.filter(|_| big),
        })
    }

    /// How many medias of a library match `query`, from the copy.
    pub async fn count(&self, library: &str, query: &MediaQuery) -> Result<u64> {
        self.shared.mirror.count_medias(library, query).await
    }

    /// One media of a library, from the copy: a cell an updated id names.
    pub async fn media(&self, library: &str, id: &str) -> Result<Option<MediaItem>> {
        let media = self.shared.mirror.media(library, id).await?;
        Ok(self.reveal(library, media))
    }

    /// `limit` medias of a library matching `query` from position `offset`, in its
    /// order, from the copy. The grid's query is [`grid_query`].
    pub async fn medias(
        &self,
        library: &str,
        query: &MediaQuery,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<MediaItem>> {
        let medias = (self.shared.mirror)
            .medias_at(library, query, offset, limit)
            .await?;
        Ok(self.reveal(library, medias))
    }

    /// What a media is linked to (people, tags, series and episode, movies, books),
    /// from the copy: what a zoomed media shows.
    pub async fn related(&self, library: &str, media: &MediaItem) -> Result<Related> {
        let related = self.shared.mirror.related(library, media).await?;
        Ok(self.reveal(library, related))
    }

    /// The people of a library, by name, from the copy.
    pub async fn people(&self, library: &str) -> Result<Vec<Person>> {
        let items = self.shared.mirror.people(library).await?;
        Ok(self.reveal(library, items))
    }

    /// One person of a library, from the copy.
    pub async fn person(&self, library: &str, id: &str) -> Result<Option<Person>> {
        let items = self.shared.mirror.person(library, id).await?;
        Ok(self.reveal(library, items))
    }

    /// A small image of a person or a series (portrait, poster) for a list or a
    /// picker, cached with the thumbnails: see [`Mirror::item_image`]. `None` when it
    /// has none.
    pub async fn item_image(&self, library: &str, item: ItemImage<'_>) -> Result<Option<Vec<u8>>> {
        self.shared.mirror.item_image(library, item).await
    }

    /// The tags of a library, by name, from the copy.
    pub async fn tags(&self, library: &str) -> Result<Vec<Tag>> {
        let items = self.shared.mirror.tags(library).await?;
        Ok(self.reveal(library, items))
    }

    /// One tag of a library, from the copy.
    pub async fn tag(&self, library: &str, id: &str) -> Result<Option<Tag>> {
        let items = self.shared.mirror.tag(library, id).await?;
        Ok(self.reveal(library, items))
    }

    /// The series of a library, by name, from the copy.
    pub async fn series(&self, library: &str) -> Result<Vec<ItemWithRelations<Serie>>> {
        let items = self.shared.mirror.series(library).await?;
        Ok(self.reveal(library, items))
    }

    /// One series of a library, from the copy.
    pub async fn serie(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Serie>>> {
        let items = self.shared.mirror.serie(library, id).await?;
        Ok(self.reveal(library, items))
    }

    /// The episodes of a library (of one series when `serie` is given), by series,
    /// season and number, from the copy.
    pub async fn episodes(&self, library: &str, serie: Option<&str>) -> Result<Vec<Episode>> {
        self.shared.mirror.episodes(library, serie).await
    }

    /// One episode of a library, by its id ([`Episode::id`]), from the copy.
    pub async fn episode(&self, library: &str, id: &str) -> Result<Option<Episode>> {
        self.shared.mirror.episode(library, id).await
    }

    /// The movies of a library, by name, from the copy.
    pub async fn movies(&self, library: &str) -> Result<Vec<ItemWithRelations<Movie>>> {
        let items = self.shared.mirror.movies(library).await?;
        Ok(self.reveal(library, items))
    }

    /// One movie of a library, from the copy.
    pub async fn movie(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Movie>>> {
        let items = self.shared.mirror.movie(library, id).await?;
        Ok(self.reveal(library, items))
    }

    /// The books of a library, by name, from the copy.
    pub async fn books(&self, library: &str) -> Result<Vec<ItemWithRelations<Book>>> {
        let items = self.shared.mirror.books(library).await?;
        Ok(self.reveal(library, items))
    }

    /// One book of a library, from the copy.
    pub async fn book(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Book>>> {
        let items = self.shared.mirror.book(library, id).await?;
        Ok(self.reveal(library, items))
    }

    /// The names of a library's people and tags, from the copy, kept until the library
    /// changes or is unlocked (its passphrase set: they come decrypted). A failure is
    /// not kept: the next call reads them again.
    pub async fn names(&self, library: &str) -> Result<Arc<Names>> {
        let unlocked = self.shared.mirror.text_key(library).is_some();
        let generation = {
            let cache = lock(&self.shared.names);
            if let Some(names) = cache.get(library, unlocked) {
                return Ok(names);
            }
            cache.generation
        };
        let people = self.people(library).await?;
        let tags = self.tags(library).await?;
        let names = Arc::new(Names::new(people, tags));
        lock(&self.shared.names).keep(library, generation, unlocked, &names);
        Ok(names)
    }

    /// `value` with the names of an encrypted library decrypted, once its passphrase is
    /// set (see [`Reveal`]); as stored otherwise.
    fn reveal<T: Reveal>(&self, library: &str, mut value: T) -> T {
        if let Some(key) = self.shared.mirror.text_key(library) {
            value.reveal(&key);
        }
        value
    }

    /// The server's base URL (no trailing slash) and a token, once connected: where
    /// files are downloaded from (thumbnails, full-size photos, videos), the token in an
    /// `Authorization` header.
    pub fn base(&self) -> Option<AuthorizedUrl> {
        lock(&self.shared.base).clone()
    }

    /// Sets the base URL and token (a fake server's).
    pub fn set_base(&self, base: AuthorizedUrl) {
        *lock(&self.shared.base) = Some(base);
    }

    /// Reads the base URL and token again: the client renews the token as it nears its
    /// end. Without a connection, or past 10 seconds, nothing changes. A new base is
    /// told as a [`Change::Server`].
    pub async fn refresh_base(&self) {
        let Some((attempt, api)) = lock(&self.shared.api).clone() else {
            return;
        };
        // A read of a connection replaced since (a new one, a disconnect) is dropped: it
        // would bring back the old server's address and token.
        let read = timeout(
            self.shared.runtime.as_ref(),
            BASE_WAIT,
            api.client().authorized_url("", &[]),
        );
        if let Some(Ok(mut base)) = read.await
            && self.shared.attempt.load(Ordering::SeqCst) == attempt
        {
            base.url = base.url.trim_end_matches('/').to_owned();
            let changed = lock(&self.shared.base).replace(base.clone()) != Some(base);
            if changed {
                // Screens that keep the base read it again.
                let listener = Arc::clone(&self.shared.listener);
                self.shared
                    .runtime
                    .spawn(Box::pin(async move { listener(&Change::Server) }));
            }
        }
    }

    /// Gets a new token, then reads the base URL and token again: the server refused the
    /// last one (a 401 on a download). Within 10 seconds, or nothing changes.
    pub async fn renew_base(&self) {
        if let Some(api) = self.api() {
            // Without a new token, the current one stays: the caller tries again later.
            let renew = api.client().renew_token();
            let _ = timeout(self.shared.runtime.as_ref(), BASE_WAIT, renew).await;
        }
        self.refresh_base().await;
    }

    /// Where a media's file is read with `query`: its URL (no token) and token. The
    /// server's own when connected (`LibraryApi::media_url`), else the base URL's with
    /// the same path and query. `fresh` gets a new token first (the server refused the last one).
    /// `None` while the server cannot be reached.
    pub async fn locate(
        &self,
        library: &str,
        media: &str,
        query: &MediaFileQuery,
        fresh: bool,
    ) -> Option<AuthorizedUrl> {
        if fresh {
            self.renew_base().await;
        }
        if let Some(api) = self.shared.mirror.library_api(library)
            && let Some(Ok(url)) = timeout(
                self.shared.runtime.as_ref(),
                BASE_WAIT,
                api.media_url(media, query),
            )
            .await
        {
            return Some(url);
        }
        let base = self.base()?;
        Some(AuthorizedUrl {
            url: media_file_url(&base.url, library, media, query),
            ..base
        })
    }
}

/// Follows the mirror's events until it goes (its sender closes): each wakes the
/// waiters at once; what changed is told at the end of its burst.
async fn follow(
    mut received: broadcast::Receiver<MirrorEvent>,
    runtime: Arc<dyn Runtime>,
    listener: Listener,
    woken: Arc<Notify>,
    held: Arc<Mutex<HashMap<String, Held>>>,
    names: Arc<Mutex<NamesCache>>,
) {
    let (mut server, mut all) = (false, false);
    let mut libraries = BTreeMap::<String, BTreeMap<SyncKind, Ids>>::new();
    let mut timer: Option<BoxFuture<()>> = None;
    loop {
        let event = match timer.take() {
            Some(running) => match select(Box::pin(received.recv()), running).await {
                Either::Left((event, running)) => {
                    timer = Some(running);
                    event
                }
                Either::Right(((), _)) => {
                    if all {
                        listener(&Change::All);
                    } else {
                        if server {
                            listener(&Change::Server);
                        }
                        for (library, mut items) in std::mem::take(&mut libraries) {
                            // An item added then removed within the burst: nothing.
                            items.retain(
                                |_, ids| !matches!(ids, Ids::Listed(ids) if ids.is_empty()),
                            );
                            listener(&Change::Library { library, items });
                        }
                    }
                    (server, all) = (false, false);
                    libraries.clear();
                    continue;
                }
            },
            None => received.recv().await,
        };
        match event {
            Ok(MirrorEvent::Changed { library, changes }) => {
                if changes.contains_key(&SyncKind::People) || changes.contains_key(&SyncKind::Tags)
                {
                    lock(&names).forget(Some(&library));
                }
                let items = libraries.entry(library).or_default();
                for (kind, ids) in changes {
                    (items.entry(kind))
                        .or_insert_with(|| Ids::Listed(ItemIds::default()))
                        .merge(ids);
                }
            }
            Ok(MirrorEvent::Sync { library, state }) => {
                if matches!(
                    state,
                    LibrarySyncState::Queued | LibrarySyncState::Syncing(_)
                ) && let Some(shown) = lock(&held).get_mut(&library)
                {
                    shown.mark();
                }
                libraries.entry(library).or_default();
            }
            Ok(MirrorEvent::Libraries | MirrorEvent::Connection(_)) => server = true,
            Err(broadcast::error::RecvError::Lagged(_)) => {
                lock(&names).forget(None);
                // A sync may have been missed: every library brings a new revision.
                lock(&held).values_mut().for_each(Held::mark);
                all = true;
            }
            Err(broadcast::error::RecvError::Closed) => break,
        }
        if timer.is_none() {
            timer = Some(runtime.sleep(BURST));
        }
        woken.notify_waiters();
    }
}

#[cfg(all(test, feature = "sqlite"))]
mod tests;