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
//! The sync of one library and the live events. Port of the phone app's
//! `syncLibraryContent`, `runLibraryMediaSync`, `syncDeletedItems` (`sync.ts`) and
//! `process*Events` (`sse-sync.ts`).

use std::sync::Arc;

use super::store::{Changes, Removal, SyncKind, SyncState, ThumbRecord};
use super::{Inner, LibrarySyncState, MirrorEvent, OVERLAP_MS, PAGE_SIZE, SyncProgress};
use crate::client::now_ms;
use crate::error::{Error, Result};
use crate::events::ServerEvent;
use crate::library::LibraryApi;
use crate::types::ElementAction;
use crate::types::book::BookQuery;
use crate::types::deleted::DeletedQuery;
use crate::types::element_type::ElementType;
use crate::types::episode::EpisodeQuery;
use crate::types::library::LibrarySocketMessage;
use crate::types::media::{Media, MediaQuery, RsSort, SqlOrder};
use crate::types::movie::MovieQuery;
use crate::types::person::PeopleQuery;
use crate::types::serie::SerieQuery;
use crate::types::tag::TagQuery;

/// One page of a list.
struct Page {
    changes: Changes,
    len: usize,
    /// The ids, in order: the first identifies the page (to notice a server that
    /// ignores `offset`), the last must be in the next page (see `PAGE_OVERLAP`).
    ids: Vec<String>,
    /// The largest `modified` (or deletion date) in it.
    max: i64,
}

/// Items each page of a list reads again from the previous one. Lists page by
/// position: an item deleted or moved on the server between two pages shifts the
/// rest, which would skip one. Reading the end of the previous page again absorbs up
/// to this many shifts, and the previous page's last item must be in the new page.
const PAGE_OVERLAP: u32 = 50;
/// Scans of a list started again when it shifted more than `PAGE_OVERLAP`, before
/// the sync fails (and is retried later).
const MAX_SCAN_RESTARTS: usize = 3;

impl Page {
    fn new<T>(
        items: Vec<T>,
        id: impl Fn(&T) -> String,
        modified: impl Fn(&T) -> i64,
        into: impl FnOnce(Vec<T>) -> Changes,
    ) -> Page {
        Page {
            len: items.len(),
            ids: items.iter().map(&id).collect(),
            max: items.iter().map(&modified).max().unwrap_or(0),
            changes: into(items),
        }
    }
}

/// `after` for a watermark: the watermark minus the overlap. `None` without one.
fn after(watermark: Option<i64>) -> Option<i64> {
    watermark
        .filter(|w| *w > 0)
        .map(|w| (w - OVERLAP_MS).max(0))
}

/// The kind a deletion is about.
fn deleted_kind(kind: &ElementType) -> Option<SyncKind> {
    Some(match kind {
        ElementType::Media => SyncKind::Medias,
        ElementType::Tag => SyncKind::Tags,
        ElementType::Person => SyncKind::People,
        ElementType::Serie => SyncKind::Series,
        ElementType::Movie => SyncKind::Movies,
        ElementType::Episode => SyncKind::Episodes,
        ElementType::Book => SyncKind::Books,
        _ => return None,
    })
}

/// The version of a media's thumbnail: a new thumbnail changes it.
pub(super) fn thumb_version(media: &Media) -> String {
    format!(
        "{}:{}",
        media.thumbv.unwrap_or(0),
        media.thumbsize.unwrap_or(0)
    )
}

/// What the server sends for one page of a kind other than medias.
async fn fetch_page(
    api: &LibraryApi,
    kind: SyncKind,
    after: Option<i64>,
    offset: u32,
) -> Result<Page> {
    let limit = Some(PAGE_SIZE);
    let offset = Some(offset);
    Ok(match kind {
        SyncKind::Tags => {
            let query = TagQuery {
                after,
                limit,
                offset,
                ..Default::default()
            };
            Page::new(
                api.get_tags(&query).await?,
                |t| t.id.clone(),
                |t| t.modified as i64,
                |tags| Changes {
                    tags,
                    ..Default::default()
                },
            )
        }
        SyncKind::People => {
            let query = PeopleQuery {
                after,
                limit,
                offset,
                ..Default::default()
            };
            Page::new(
                api.get_people(&query).await?,
                |p| p.id.clone(),
                |p| p.modified as i64,
                |people| Changes {
                    people,
                    ..Default::default()
                },
            )
        }
        SyncKind::Series => {
            let query = SerieQuery {
                after,
                limit,
                offset,
                ..Default::default()
            };
            Page::new(
                api.get_series(&query).await?,
                |s| s.item.id.clone(),
                |s| s.item.modified as i64,
                |series| Changes {
                    series,
                    ..Default::default()
                },
            )
        }
        SyncKind::Movies => {
            let query = MovieQuery {
                after,
                limit,
                offset,
                ..Default::default()
            };
            Page::new(
                api.get_movies(&query).await?,
                |m| m.item.id.clone(),
                |m| m.item.modified as i64,
                |movies| Changes {
                    movies,
                    ..Default::default()
                },
            )
        }
        SyncKind::Episodes => {
            let query = EpisodeQuery {
                after,
                limit,
                offset,
                ..Default::default()
            };
            Page::new(
                api.get_episodes(&query).await?,
                |e| e.id(),
                |e| e.modified as i64,
                |episodes| Changes {
                    episodes,
                    ..Default::default()
                },
            )
        }
        SyncKind::Books => {
            let query = BookQuery {
                after,
                limit,
                offset,
                ..Default::default()
            };
            Page::new(
                api.get_books(&query).await?,
                |b| b.item.id.clone(),
                |b| b.item.modified as i64,
                |books| Changes {
                    books,
                    ..Default::default()
                },
            )
        }
        SyncKind::Deleted => {
            let query = DeletedQuery {
                after,
                order: SqlOrder::ASC,
                limit,
                offset,
                ..Default::default()
            };
            let deleted = api.get_deleted(&query).await?;
            Page {
                len: deleted.len(),
                ids: deleted
                    .iter()
                    .map(|d| format!("{}:{}", d.id, d.date))
                    .collect(),
                max: deleted.iter().map(|d| d.date).max().unwrap_or(0),
                changes: Changes {
                    removed: deleted
                        .into_iter()
                        .filter_map(|d| {
                            deleted_kind(&d.kind).map(|kind| Removal {
                                kind,
                                id: d.id,
                                date: Some(d.date),
                            })
                        })
                        .collect(),
                    ..Default::default()
                },
            }
        }
        SyncKind::Medias => {
            return Err(Error::transport("medias are not synced by offset"));
        }
    })
}

impl Inner {
    fn progress(
        &self,
        library: &str,
        kind: SyncKind,
        fetched: u64,
        total: Option<u64>,
        full: bool,
    ) {
        self.set_status(
            library,
            LibrarySyncState::Syncing(SyncProgress {
                library: library.to_owned(),
                kind,
                fetched,
                total,
                full,
            }),
        );
    }

    /// Writes changes, removes the thumbnails of removed medias, and tells.
    async fn write(&self, library: &str, generation: i64, changes: Changes) -> Result<()> {
        if changes.is_empty() {
            return Ok(());
        }
        let kinds = changes.kinds();
        let removed_medias: Vec<String> = changes
            .removed
            .iter()
            .filter(|r| r.kind == SyncKind::Medias)
            .map(|r| r.id.clone())
            .collect();
        self.store.apply(library, generation, changes).await?;
        self.forget_thumbs(library, removed_medias).await?;
        self.emit(MirrorEvent::Changed {
            library: library.to_owned(),
            kinds,
        });
        Ok(())
    }

    async fn forget_thumbs(&self, library: &str, medias: Vec<String>) -> Result<()> {
        if medias.is_empty() {
            return Ok(());
        }
        for media in &medias {
            self.thumbs.remove(library, media).await;
        }
        self.store.remove_thumbs(library, medias).await
    }

    /// Removes what a full sync of `kind` did not bring back.
    async fn sweep(&self, library: &str, kind: SyncKind, generation: i64) -> Result<()> {
        let removed = self.store.sweep(library, kind, generation).await?;
        if removed.is_empty() {
            return Ok(());
        }
        if kind == SyncKind::Medias {
            self.forget_thumbs(library, removed).await?;
        }
        self.emit(MirrorEvent::Changed {
            library: library.to_owned(),
            kinds: vec![kind],
        });
        Ok(())
    }

    /// Syncs one library: every kind, then the deletions.
    pub(super) async fn sync_library(&self, api: &LibraryApi) -> Result<()> {
        let library = api.id();
        let mut state = match self.store.sync_state(library).await? {
            Some(state) => state,
            None => {
                // First sync, or a lost state: one full repair.
                let state = SyncState {
                    generation: now_ms(),
                    ..Default::default()
                };
                self.store.set_sync_state(library, state.clone()).await?;
                state
            }
        };
        for kind in SyncKind::ALL {
            match kind {
                SyncKind::Medias => self.sync_medias(api, &mut state).await?,
                _ => self.sync_list(api, kind, &mut state).await?,
            }
        }
        Ok(())
    }

    /// Syncs a kind paged by `limit` and `offset` (every kind but medias).
    async fn sync_list(
        &self,
        api: &LibraryApi,
        kind: SyncKind,
        state: &mut SyncState,
    ) -> Result<()> {
        let library = api.id();
        let watermark = state.watermarks.get(&kind).copied();
        let full = watermark.is_none();
        let after = after(watermark);
        let mut restarts = 0;
        let max = 'scan: loop {
            let mut max = watermark.unwrap_or(0);
            let mut offset: u32 = 0;
            let mut fetched: u64 = 0;
            // The first and last ids of the previous page.
            let mut previous: Option<(String, String)> = None;
            loop {
                self.progress(library, kind, fetched, None, full);
                let page = fetch_page(api, kind, after, offset).await?;
                let mut fresh = page.len;
                if let Some((first, last)) = &previous {
                    if page.ids.first() == Some(first) {
                        // A server that ignores `offset` sent the first page again.
                        break 'scan max;
                    }
                    match page.ids.iter().position(|id| id == last) {
                        Some(at) => fresh = page.len - at - 1,
                        None => {
                            // Shifted past the overlap: an item may have been skipped.
                            restarts += 1;
                            if restarts > MAX_SCAN_RESTARTS {
                                return Err(Error::malformed(
                                    format!(
                                        "the {} list kept changing during the sync",
                                        kind.name()
                                    ),
                                    None,
                                ));
                            }
                            continue 'scan;
                        }
                    }
                }
                if page.len == 0 {
                    break 'scan max;
                }
                max = max.max(page.max);
                fetched += fresh as u64;
                let len = page.len;
                previous = page.ids.first().cloned().zip(page.ids.last().cloned());
                self.write(library, state.generation, page.changes).await?;
                if len < PAGE_SIZE as usize {
                    break 'scan max;
                }
                offset += len as u32 - PAGE_OVERLAP;
            }
        };
        if full && kind != SyncKind::Deleted {
            self.sweep(library, kind, state.generation).await?;
        }
        state.watermarks.insert(kind, max);
        self.store.set_sync_state(library, state.clone()).await
    }

    /// Syncs the medias, by modified date with the server's page keys, so an
    /// interrupted sync resumes where it stopped.
    async fn sync_medias(&self, api: &LibraryApi, state: &mut SyncState) -> Result<()> {
        let library = api.id();
        let kind = SyncKind::Medias;
        let watermark = state.watermarks.get(&kind).copied();
        let full = watermark.is_none();
        let start = after(watermark);
        // `<modified>|` with an empty id: every media modified at or after it.
        let mut page_key = match start {
            Some(after) => Some(format!("{after}|")),
            None if full => state.media_resume.clone(),
            None => None,
        };
        let count_query = MediaQuery {
            sort: RsSort::Modified,
            after: start,
            ..Default::default()
        };
        let total = api.count_medias(&count_query).await.ok();
        let mut max = watermark.unwrap_or(0);
        let mut fetched: u64 = 0;
        loop {
            self.progress(library, kind, fetched, total, full);
            let query = MediaQuery {
                sort: RsSort::Modified,
                order: SqlOrder::ASC,
                limit: Some(PAGE_SIZE as usize),
                page_key: page_key.clone(),
                ..Default::default()
            };
            let medias = api.get_medias(&query).await?;
            let Some(last) = medias.last() else {
                break;
            };
            let next = format!("{}|{}", last.item.modified.unwrap_or(0), last.item.id);
            if page_key.as_deref() == Some(next.as_str()) {
                return Err(Error::malformed(
                    "the server's media pages do not advance",
                    None,
                ));
            }
            max = max.max(
                medias
                    .iter()
                    .filter_map(|m| m.item.modified)
                    .max()
                    .unwrap_or(0),
            );
            fetched += medias.len() as u64;
            self.write(
                library,
                state.generation,
                Changes {
                    medias,
                    ..Default::default()
                },
            )
            .await?;
            if full {
                state.media_resume = Some(next.clone());
            } else {
                state.watermarks.insert(kind, max);
            }
            self.store.set_sync_state(library, state.clone()).await?;
            page_key = Some(next);
        }
        if full {
            self.sweep(library, kind, state.generation).await?;
            state.media_resume = None;
        }
        state.watermarks.insert(kind, max);
        self.store.set_sync_state(library, state.clone()).await
    }

    /// Applies a live event of a mirrored library.
    pub(super) async fn apply_event(&self, event: ServerEvent) -> Result<()> {
        fn split<T>(
            items: Vec<T>,
            kind: SyncKind,
            action: impl Fn(&T) -> &ElementAction,
            id: impl Fn(&T) -> String,
        ) -> (Vec<T>, Vec<Removal>) {
            let mut kept = Vec::new();
            let mut removed = Vec::new();
            for item in items {
                if *action(&item) == ElementAction::Deleted {
                    removed.push(Removal {
                        kind,
                        id: id(&item),
                        date: None,
                    });
                } else {
                    kept.push(item);
                }
            }
            (kept, removed)
        }

        // A live media update that left its relations out: synced again, to read them.
        let mut catch_up = false;
        let (library, changes) = match event {
            ServerEvent::Library(LibrarySocketMessage { action, library }) => {
                return if action == ElementAction::Deleted {
                    self.remove_library(&library.id).await
                } else {
                    self.put_library(library).await
                };
            }
            ServerEvent::Medias(message) => {
                let (kept, removed) = split(
                    message.medias,
                    SyncKind::Medias,
                    |m| &m.action,
                    |m| m.media.item.id.clone(),
                );
                let mut medias = Vec::with_capacity(kept.len());
                for change in kept {
                    let mut media = change.media;
                    // From the server's database, no relations means none. But some
                    // events (the server's update of several medias) leave them out,
                    // even ones the update added: the stored ones stay, and a sync of
                    // the library reads the real ones back.
                    if media.relations.is_none() {
                        if let Some(stored) =
                            self.store.media(&message.library, &media.item.id).await?
                        {
                            media.relations = stored.relations;
                        }
                        catch_up = true;
                    }
                    medias.push(media);
                }
                (
                    message.library,
                    Changes {
                        medias,
                        removed,
                        ..Default::default()
                    },
                )
            }
            ServerEvent::Tags(message) => {
                let (kept, removed) = split(
                    message.tags,
                    SyncKind::Tags,
                    |t| &t.action,
                    |t| t.tag.id.clone(),
                );
                (
                    message.library,
                    Changes {
                        tags: kept.into_iter().map(|t| t.tag).collect(),
                        removed,
                        ..Default::default()
                    },
                )
            }
            ServerEvent::People(message) => {
                let (kept, removed) = split(
                    message.people,
                    SyncKind::People,
                    |p| &p.action,
                    |p| p.person.id.clone(),
                );
                (
                    message.library,
                    Changes {
                        people: kept.into_iter().map(|p| p.person).collect(),
                        removed,
                        ..Default::default()
                    },
                )
            }
            ServerEvent::Series(message) => {
                let (kept, removed) = split(
                    message.series,
                    SyncKind::Series,
                    |s| &s.action,
                    |s| s.serie.item.id.clone(),
                );
                (
                    message.library,
                    Changes {
                        series: kept.into_iter().map(|s| s.serie).collect(),
                        removed,
                        ..Default::default()
                    },
                )
            }
            ServerEvent::Movies(message) => {
                let (kept, removed) = split(
                    message.movies,
                    SyncKind::Movies,
                    |m| &m.action,
                    |m| m.movie.item.id.clone(),
                );
                (
                    message.library,
                    Changes {
                        movies: kept.into_iter().map(|m| m.movie).collect(),
                        removed,
                        ..Default::default()
                    },
                )
            }
            ServerEvent::Episodes(message) => {
                let (kept, removed) = split(
                    message.episodes,
                    SyncKind::Episodes,
                    |e| &e.action,
                    |e| e.episode.id(),
                );
                (
                    message.library,
                    Changes {
                        episodes: kept.into_iter().map(|e| e.episode).collect(),
                        removed,
                        ..Default::default()
                    },
                )
            }
            ServerEvent::Books(message) => {
                let (kept, removed) = split(
                    message.books,
                    SyncKind::Books,
                    |b| &b.action,
                    |b| b.book.item.id.clone(),
                );
                (
                    message.library,
                    Changes {
                        books: kept.into_iter().map(|b| b.book).collect(),
                        removed,
                        ..Default::default()
                    },
                )
            }
            _ => return Ok(()),
        };
        if self.library(&library).is_none() {
            return Ok(());
        }
        // Stamped like the sync's rows, so a full sync running now keeps them.
        let generation = self
            .store
            .sync_state(&library)
            .await?
            .map_or(0, |state| state.generation);
        self.write(&library, generation, changes).await?;
        if catch_up {
            self.enqueue(&library, false);
        }
        Ok(())
    }

    /// The thumbnail as stored on the server (encrypted in an encrypted library): from
    /// the disk cache, or fetched and cached.
    pub(super) async fn thumb_raw(
        self: &Arc<Self>,
        library: &str,
        media: &Media,
    ) -> Result<Vec<u8>> {
        let version = thumb_version(media);
        if let Some(record) = self.store.thumb(library, &media.id).await?
            && record.version == version
            && let Some(data) = self.thumbs.read(library, &media.id).await
        {
            return Ok(data);
        }
        let api = self.api(library).ok_or_else(super::not_connected)?;
        let data = api.get_thumb_raw(&media.id).await?;
        // A thumbnail that cannot be cached (its file is locked, the disk is full...)
        // is still shown; its record keeps describing what is on disk, and the next
        // read downloads it again.
        if self
            .publish_thumb(library, &media.id, version, &data)
            .await
            .is_ok()
        {
            self.evict_thumbs().await?;
        }
        Ok(data)
    }

    /// Stores a downloaded thumbnail and its version record as one step per media.
    /// Two downloads of different versions can finish in any order; without the lock,
    /// one's file and the other's record could end up together, and old bytes would
    /// pass for the current version. With it, the last publication wins whole: if that
    /// is the older version, the next read of the current one sees the mismatch and
    /// downloads again.
    pub(super) async fn publish_thumb(
        &self,
        library: &str,
        media: &str,
        version: String,
        data: &[u8],
    ) -> Result<()> {
        let _publishing = self.thumbs.publish_lock(library, media).lock().await;
        self.thumbs.write(library, media, data).await?;
        self.store
            .put_thumb(ThumbRecord {
                library: library.to_owned(),
                media: media.to_owned(),
                size: data.len() as u64,
                version,
            })
            .await
    }

    /// Removes the least recently used thumbnails past the size limit.
    async fn evict_thumbs(&self) -> Result<()> {
        let over = self.store.thumbs_over(self.options.thumbs_limit).await?;
        for record in over {
            self.thumbs.remove(&record.library, &record.media).await;
            self.store
                .remove_thumbs(&record.library, vec![record.media])
                .await?;
        }
        Ok(())
    }

    /// A cached encrypted thumbnail of a library, with its media: to check a
    /// passphrase offline.
    pub(super) async fn cached_sample(&self, library: &str) -> Result<Option<(Media, Vec<u8>)>> {
        let query = MediaQuery {
            limit: Some(50),
            ..Default::default()
        };
        for media in self.store.medias(library, query, 0).await? {
            let media = media.item;
            if media.iv.is_none() {
                continue;
            }
            if let Some(record) = self.store.thumb(library, &media.id).await?
                && record.version == thumb_version(&media)
                && let Some(data) = self.thumbs.read(library, &media.id).await
            {
                return Ok(Some((media, data)));
            }
        }
        Ok(None)
    }
}