redseat-api 0.17.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
//! What the user watched and where they stopped: the per-user fields of movies and
//! episodes (`watched`, `progress`, `progress_modified`), and a media's `progress`.
//!
//! The server keeps them per user, and changing them does not change an item's
//! `modified`: a sync from a watermark never brings them again. So a screen that shows
//! them reads them again from the server when it opens ([`Mirror::refresh_viewing`]),
//! and what this app changes is written to the copy at once.

use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, PoisonError};

use serde::de::DeserializeOwned;

use super::actions::{Action, RebasedUndo, Undo};
use super::store::{Changes, FileLinks, SyncKind, Written};
use super::sync::{PAGE_OVERLAP, fetch_page};
use super::{Inner, Mirror, MirrorEvent, PAGE_SIZE, not_connected};
use crate::client::now_ms;
use crate::error::{Error, Result};
use crate::library::MediaItem;
use crate::types::ItemWithRelations;
use crate::types::episode::Episode;
use crate::types::library::LibraryType;
use crate::types::media::Media;
use crate::types::movie::Movie;

/// Pages read at most by [`Mirror::refresh_viewing`]: a server that ignores `offset`
/// would otherwise be read forever.
const MAX_PAGES: usize = 1000;
/// Reads of one page by [`Mirror::refresh_viewing`] while the user's own changes keep
/// coming: past them the page is left as it is, for the next refresh.
const MAX_PAGE_READS: usize = 3;

/// The user's own watched and progress changes, in any library: rare enough to count
/// together. A page read from the server before one of them reached it may hold the
/// old value. So what is written from a page read since `started` checks, under
/// `write` (which the changes' own writes to the copy take too), that no change
/// started since nor is under way: else a refresh reads the page again, and a sync or
/// an event keeps the stored watched and progress, a media's progress too
/// ([`Inner::write_fetched`]). A
/// deletion of medias the server did counts as a change started too: a page read
/// before it leaves them out (`Queue::drop_deleted`).
#[derive(Default)]
pub(super) struct ViewingWrites {
    /// Changes under way, and changes started so far.
    counts: Mutex<(usize, u64)>,
    pub(super) write: tokio::sync::Mutex<()>,
}

impl ViewingWrites {
    fn counts(&self) -> std::sync::MutexGuard<'_, (usize, u64)> {
        self.counts.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Changes under way, and started so far.
    fn seen(&self) -> (usize, u64) {
        *self.counts()
    }

    /// The changes started so far: noted before a page is read.
    pub(super) fn started(&self) -> u64 {
        self.seen().1
    }

    /// No change started since `started`, nor is under way.
    fn quiet_since(&self, started: u64) -> bool {
        self.seen() == (0, started)
    }

    /// A change starts; it ends when the guard drops, done or failed.
    pub(super) fn begin(&self) -> Pending<'_> {
        let mut counts = self.counts();
        counts.0 += 1;
        counts.1 += 1;
        Pending { writes: self }
    }
}

/// A change of the user's under way.
pub(super) struct Pending<'a> {
    writes: &'a ViewingWrites,
}

impl Drop for Pending<'_> {
    fn drop(&mut self) {
        let mut counts = self.writes.counts();
        counts.0 = counts.0.saturating_sub(1);
    }
}

impl Inner {
    /// Writes a page of a sync or an event read from the server since `started`
    /// ([`ViewingWrites::started`]); the medias `relations_kept` keep the copy's
    /// relations (sent without them). If a change of the user's started since, or is
    /// under way, its movies and episodes keep the stored watched and progress: the
    /// page may be older than the change.
    pub(super) async fn write_fetched(
        &self,
        library: &str,
        generation: i64,
        mut changes: Changes,
        started: u64,
        relations_kept: Vec<String>,
    ) -> Result<()> {
        let _write = self.viewing.write.lock().await;
        if !relations_kept.is_empty() {
            self.keep_relations(library, &mut changes, relations_kept)
                .await?;
        }
        if !self.viewing.quiet_since(started) {
            self.keep_viewing(library, &mut changes).await?;
        }
        // Nor does it undo a change of the user's not sent yet, or bring back a media
        // deleted since.
        self.queue.drop_deleted(library, &mut changes, started);
        self.write_rebased(library, generation, changes).await
    }

    /// Writes what the server sent with the actions waiting applied again
    /// ([`super::queue::Queue::rebase`]), and keeps their undo against it where the
    /// copy took it. Under the copy's write lock.
    pub(super) async fn write_rebased(
        &self,
        library: &str,
        generation: i64,
        mut changes: Changes,
    ) -> Result<()> {
        let (mut changed, undos) = self.queue.rebase(library, &mut changes, &[]);
        let current = self.current(library, &changes, &undos).await?;
        changed.extend(self.queue.accept(&current, undos));
        let removals = changes.removed.clone();
        let mut written = Written::default();
        if !changes.is_empty() {
            written = self.store.apply(library, generation, changes).await?;
        }
        // An item the server removed: the actions waiting on it are moot, dropped
        // (discarding a deletion would bring back what is gone).
        let gone = self.queue.gone(library, &removals, &written);
        if !gone.is_empty() {
            (self.store)
                .remove_actions(library, generation, gone.clone(), Changes::default())
                .await?;
            self.queue.drop_actions(&gone);
            changed.retain(|a| !gone.contains(&a.id));
        }
        if !changed.is_empty() {
            self.store.update_actions(changed).await?;
        }
        self.told(library, written).await?;
        if !gone.is_empty() {
            self.emit(MirrorEvent::Actions {
                library: library.to_owned(),
            });
        }
        Ok(())
    }

    /// The items of `undos` that `changes` has not older than the copy's (or the copy
    /// lacks): what the server sent for them is its current value, even when the copy
    /// keeps its own item because it is the same once the actions are made again.
    pub(super) async fn current(
        &self,
        library: &str,
        changes: &Changes,
        undos: &[RebasedUndo],
    ) -> Result<HashSet<(SyncKind, String)>> {
        let mut sent: HashMap<(SyncKind, String), i64> = HashMap::new();
        for media in &changes.medias {
            sent.insert(
                (SyncKind::Medias, media.item.id.clone()),
                media.item.modified.unwrap_or(0),
            );
        }
        for movie in &changes.movies {
            let modified = i64::try_from(movie.item.modified).unwrap_or(i64::MAX);
            sent.insert((SyncKind::Movies, movie.item.id.clone()), modified);
        }
        for episode in &changes.episodes {
            let modified = i64::try_from(episode.modified).unwrap_or(i64::MAX);
            sent.insert((SyncKind::Episodes, episode.id()), modified);
        }
        let mut wanted: HashMap<SyncKind, Vec<String>> = HashMap::new();
        for (_, kind, item, _) in undos {
            if sent.contains_key(&(*kind, item.clone())) {
                wanted.entry(*kind).or_default().push(item.clone());
            }
        }
        let mut stored: HashMap<(SyncKind, String), i64> = HashMap::new();
        for (kind, ids) in wanted {
            for value in self.store.items_by_id(library, kind, ids).await? {
                let modified = value["modified"].as_i64().unwrap_or(0);
                let id = match kind {
                    SyncKind::Episodes => serde_json::from_value::<Episode>(value)
                        .map(|e| e.id())
                        .unwrap_or_default(),
                    _ => value["id"].as_str().unwrap_or_default().to_owned(),
                };
                stored.insert((kind, id), modified);
            }
        }
        Ok((sent.into_iter())
            .filter(|(key, modified)| stored.get(key).is_none_or(|kept| modified >= kept))
            .map(|(key, _)| key)
            .collect())
    }

    /// Gives the medias `ids` (sent without their relations) the copy's relations,
    /// without what the actions waiting did: `rebase` makes it again. Under the copy's
    /// write lock, so the copy and the queue agree.
    async fn keep_relations(
        &self,
        library: &str,
        changes: &mut Changes,
        ids: Vec<String>,
    ) -> Result<()> {
        let stored: HashMap<String, MediaItem> = (self
            .stored::<MediaItem>(library, SyncKind::Medias, ids)
            .await?
            .into_iter())
        .map(|media| (media.item.id.clone(), media))
        .collect();
        for media in changes.medias.iter_mut().filter(|m| m.relations.is_none()) {
            // A media whose deletion waits: the deletion's media stands in.
            let kept = (stored.get(&media.item.id).cloned())
                .or_else(|| self.queue.deleted_media(library, &media.item.id));
            let Some(kept) = kept else {
                continue;
            };
            media.relations = kept.relations;
            let id = media.item.id.clone();
            (self.queue).undo_waiting(library, SyncKind::Medias, &id, &[], |undo| {
                if matches!(undo, Undo::Relations(_)) {
                    undo.undo_media(media)
                }
            });
        }
        Ok(())
    }

    async fn keep_viewing(&self, library: &str, changes: &mut Changes) -> Result<()> {
        if !changes.medias.is_empty() {
            let ids = changes.medias.iter().map(|m| m.item.id.clone()).collect();
            let stored: HashMap<String, Media> = (self
                .stored::<MediaItem>(library, SyncKind::Medias, ids)
                .await?
                .into_iter())
            .map(|media| (media.item.id.clone(), media.item))
            .collect();
            for media in &mut changes.medias {
                if let Some(stored) = stored.get(&media.item.id) {
                    media.item.progress = stored.progress;
                }
            }
            // The copy's progress without the actions waiting: `rebase` makes them
            // again. The page's other fields are the server's.
            for media in &mut changes.medias {
                let id = media.item.id.clone();
                (self.queue).undo_waiting(library, SyncKind::Medias, &id, &[], |undo| {
                    if matches!(undo, Undo::MediaProgress(_)) {
                        undo.undo_media(media)
                    }
                });
            }
        }
        if !changes.movies.is_empty() {
            let ids = changes.movies.iter().map(|m| m.item.id.clone()).collect();
            let stored: HashMap<String, Movie> = (self
                .stored::<ItemWithRelations<Movie>>(library, SyncKind::Movies, ids)
                .await?
                .into_iter())
            .map(|movie| (movie.item.id.clone(), movie.item))
            .collect();
            for movie in &mut changes.movies {
                if let Some(stored) = stored.get(&movie.item.id) {
                    movie.item.watched = stored.watched;
                    movie.item.progress = stored.progress;
                    movie.item.progress_modified = stored.progress_modified;
                }
                let id = movie.item.id.clone();
                (self.queue).undo_waiting(library, SyncKind::Movies, &id, &[], |undo| {
                    undo.undo_movie(&mut movie.item)
                });
            }
        }
        if !changes.episodes.is_empty() {
            let ids = changes.episodes.iter().map(Episode::id).collect();
            let stored: HashMap<String, Episode> = (self
                .stored::<Episode>(library, SyncKind::Episodes, ids)
                .await?
                .into_iter())
            .map(|episode| (episode.id(), episode))
            .collect();
            for episode in &mut changes.episodes {
                if let Some(stored) = stored.get(&episode.id()) {
                    episode.watched = stored.watched;
                    episode.progress = stored.progress;
                    episode.progress_modified = stored.progress_modified;
                }
                let id = episode.id();
                (self.queue).undo_waiting(library, SyncKind::Episodes, &id, &[], |undo| {
                    undo.undo_episode(episode)
                });
            }
        }
        Ok(())
    }

    pub(super) async fn stored<T: DeserializeOwned>(
        &self,
        library: &str,
        kind: SyncKind,
        ids: Vec<String>,
    ) -> Result<Vec<T>> {
        let values = self.store.items_by_id(library, kind, ids).await?;
        (values.into_iter())
            .map(|value| {
                serde_json::from_value(value).map_err(|e| {
                    Error::storage(format!("local copy: unreadable {}: {e}", kind.name()))
                })
            })
            .collect()
    }
}

impl Mirror {
    /// What the medias of a library are the files of: which movies and episodes can
    /// be played.
    pub async fn file_links(&self, library: &str) -> Result<FileLinks> {
        self.inner.store.file_links(library).await
    }

    /// Reads the movies of a movies library, or the episodes of a shows library, again
    /// from the server, and writes those whose per-user fields changed (watched on
    /// another device, a new resume position): they come as a change of the library,
    /// like a sync's. Nothing for other libraries. Needs the server. Never writes over
    /// a change of the user's made meanwhile (see [`ViewingWrites`]).
    pub async fn refresh_viewing(&self, library: &str) -> Result<()> {
        let kind = match self.inner.library(library).map(|l| l.kind) {
            Some(LibraryType::Movies) => SyncKind::Movies,
            Some(LibraryType::Shows) => SyncKind::Episodes,
            _ => return Ok(()),
        };
        let api = self.inner.api(library).ok_or_else(not_connected)?;
        let generation = self.inner.generation(library).await?;
        let mut offset: u32 = 0;
        let mut first: Option<String> = None;
        let viewing = &self.inner.viewing;
        for _ in 0..MAX_PAGES {
            let mut reads = 0;
            let (page, written) = loop {
                let started = viewing.started();
                let page = fetch_page(&api, kind, None, offset).await?;
                let write = viewing.write.lock().await;
                reads += 1;
                if viewing.quiet_since(started) {
                    break (page, Some(write));
                }
                // A change of the user's came meanwhile: this page may be older.
                if reads >= MAX_PAGE_READS {
                    break (page, None);
                }
            };
            // A server that ignores `offset` sends the first page again.
            if offset > 0 && page.ids.first() == first.as_ref() {
                break;
            }
            first = first.or_else(|| page.ids.first().cloned());
            let len = page.len;
            if written.is_some() {
                // Only what differs is written and told: the same item is left alone.
                // A change of the user's not sent yet stays.
                (self.inner.write_rebased(library, generation, page.changes)).await?;
            }
            drop(written);
            if len < PAGE_SIZE as usize {
                break;
            }
            offset += len as u32 - PAGE_OVERLAP;
        }
        Ok(())
    }

    /// Marks a movie watched now, or not watched: in the copy at once, on the server
    /// when it can be reached ([`Mirror::queue`]).
    pub async fn set_movie_watched(&self, library: &str, movie: &str, watched: bool) -> Result<()> {
        let action = Action::MovieWatched {
            movie: movie.to_owned(),
            date: watched.then(now_ms),
        };
        self.queue(library, vec![action]).await
    }

    /// Saves where the user stopped in a movie (milliseconds): in the copy at once, on
    /// the server when it can be reached.
    pub async fn set_movie_progress(
        &self,
        library: &str,
        movie: &str,
        progress: u64,
    ) -> Result<()> {
        let action = Action::MovieProgress {
            movie: movie.to_owned(),
            progress,
        };
        self.queue(library, vec![action]).await
    }

    /// Marks an episode watched now, or not watched: in the copy at once, on the
    /// server when it can be reached.
    pub async fn set_episode_watched(
        &self,
        library: &str,
        episode: &Episode,
        watched: bool,
    ) -> Result<()> {
        let action = Action::EpisodeWatched {
            serie: episode.serie.clone(),
            season: episode.season,
            number: episode.number,
            date: watched.then(now_ms),
        };
        self.queue(library, vec![action]).await
    }

    /// Saves where the user stopped in an episode (milliseconds): in the copy at once,
    /// on the server when it can be reached.
    pub async fn set_episode_progress(
        &self,
        library: &str,
        episode: &Episode,
        progress: u64,
    ) -> Result<()> {
        let action = Action::EpisodeProgress {
            serie: episode.serie.clone(),
            season: episode.season,
            number: episode.number,
            progress,
        };
        self.queue(library, vec![action]).await
    }
}

impl Inner {
    /// The generation the library's rows are stamped with: a full sync running now
    /// keeps what is written with it.
    pub(super) async fn generation(&self, library: &str) -> Result<i64> {
        let state = self.store.sync_state(library).await?;
        Ok(state.map_or(0, |state| state.generation))
    }
}