redseat-api 0.14.0

Rust client for Redseat media servers
Documentation
//! What the user watched and where they stopped: the per-user fields of movies and
//! episodes (`watched`, `progress`, `progress_modified`).
//!
//! 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;
use std::sync::{Mutex, PoisonError};

use serde::de::DeserializeOwned;

use super::store::{Changes, FileLinks, SyncKind};
use super::sync::{PAGE_OVERLAP, fetch_page};
use super::{Inner, Mirror, PAGE_SIZE, not_connected};
use crate::client::now_ms;
use crate::error::{Error, Result};
use crate::library::LibraryApi;
use crate::types::ItemWithRelations;
use crate::types::episode::Episode;
use crate::types::library::LibraryType;
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 ([`Inner::write_fetched`]).
#[derive(Default)]
pub(super) struct ViewingWrites {
    /// Changes under way, and changes started so far.
    counts: Mutex<(usize, u64)>,
    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.
    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.
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`]). 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,
    ) -> Result<()> {
        let _write = self.viewing.write.lock().await;
        if !self.viewing.quiet_since(started) {
            self.keep_viewing(library, &mut changes).await?;
        }
        self.write(library, generation, changes).await
    }

    async fn keep_viewing(&self, library: &str, changes: &mut Changes) -> Result<()> {
        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;
                }
            }
        }
        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;
                }
            }
        }
        Ok(())
    }

    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.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.
                self.inner.write(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, on the server then in the copy.
    pub async fn set_movie_watched(&self, library: &str, movie: &str, watched: bool) -> Result<()> {
        let _pending = self.inner.viewing.begin();
        let date = watched.then(now_ms);
        self.connected(library)?
            .set_movie_watched(movie, date.unwrap_or(0))
            .await?;
        self.patch_movie(library, movie, |movie| movie.watched = date)
            .await
    }

    /// Saves where the user stopped in a movie (milliseconds), on the server then in
    /// the copy.
    pub async fn set_movie_progress(
        &self,
        library: &str,
        movie: &str,
        progress: u64,
    ) -> Result<()> {
        let _pending = self.inner.viewing.begin();
        self.connected(library)?
            .set_movie_progress(movie, progress)
            .await?;
        self.patch_movie(library, movie, |movie| {
            movie.progress = Some(progress);
            movie.progress_modified = Some(now_ms().max(0) as u64);
        })
        .await
    }

    /// Marks an episode watched now, or not watched, on the server then in the copy.
    pub async fn set_episode_watched(
        &self,
        library: &str,
        episode: &Episode,
        watched: bool,
    ) -> Result<()> {
        let _pending = self.inner.viewing.begin();
        let date = watched.then(now_ms);
        let Episode {
            serie,
            season,
            number,
            ..
        } = episode;
        self.connected(library)?
            .set_episode_watched(serie, *season, *number, date.unwrap_or(0))
            .await?;
        self.patch_episode(library, &episode.id(), |episode| episode.watched = date)
            .await
    }

    /// Saves where the user stopped in an episode (milliseconds), on the server then
    /// in the copy.
    pub async fn set_episode_progress(
        &self,
        library: &str,
        episode: &Episode,
        progress: u64,
    ) -> Result<()> {
        let _pending = self.inner.viewing.begin();
        let Episode {
            serie,
            season,
            number,
            ..
        } = episode;
        self.connected(library)?
            .set_episode_progress(serie, *season, *number, progress)
            .await?;
        self.patch_episode(library, &episode.id(), |episode| {
            episode.progress = Some(progress);
            episode.progress_modified = Some(now_ms().max(0) as u64);
        })
        .await
    }

    /// The library's connection, or the error saying there is none.
    fn connected(&self, library: &str) -> Result<LibraryApi> {
        self.inner.api(library).ok_or_else(not_connected)
    }

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

    /// Changes a stored movie: read, changed and written under the viewing lock, so
    /// neither a refresh page nor another change of the user's comes in between.
    async fn patch_movie(
        &self,
        library: &str,
        movie: &str,
        patch: impl FnOnce(&mut Movie),
    ) -> Result<()> {
        let _write = self.inner.viewing.write.lock().await;
        if let Some(mut stored) = self.movie(library, movie).await? {
            patch(&mut stored.item);
            let generation = self.generation(library).await?;
            (self.inner)
                .write(library, generation, Changes::movie(stored))
                .await?;
        }
        Ok(())
    }

    /// Changes a stored episode, like [`Self::patch_movie`].
    async fn patch_episode(
        &self,
        library: &str,
        id: &str,
        patch: impl FnOnce(&mut Episode),
    ) -> Result<()> {
        let _write = self.inner.viewing.write.lock().await;
        if let Some(mut stored) = self.episode(library, id).await? {
            patch(&mut stored);
            let generation = self.generation(library).await?;
            (self.inner)
                .write(library, generation, Changes::episode(stored))
                .await?;
        }
        Ok(())
    }
}