redseat-api 0.12.0

Rust client for Redseat media servers
Documentation
//! What the mirror stores, behind [`MirrorStore`]: SQLite (`SqliteStore`, feature `sqlite`) on
//! native targets; another backend (IndexedDB) can implement the same trait.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use serde::{Deserialize, Serialize};

use crate::error::Result;
use crate::library::MediaItem;
use crate::types::ItemWithRelations;
use crate::types::book::Book;
use crate::types::episode::Episode;
use crate::types::library::ServerLibraryForRead;
use crate::types::media::MediaQuery;
use crate::types::movie::Movie;
use crate::types::person::Person;
use crate::types::serie::Serie;
use crate::types::tag::Tag;

/// A kind of item the mirror keeps for each library and syncs on its own, plus the
/// deletions list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SyncKind {
    Tags,
    People,
    Series,
    Movies,
    Episodes,
    Books,
    Medias,
    /// The deletions list (`GET /libraries/:id/deleted`).
    Deleted,
}

impl SyncKind {
    /// Every kind, in the order a library is synced: what medias refer to first, the
    /// deletions last.
    pub const ALL: [SyncKind; 8] = [
        SyncKind::Tags,
        SyncKind::People,
        SyncKind::Series,
        SyncKind::Movies,
        SyncKind::Episodes,
        SyncKind::Books,
        SyncKind::Medias,
        SyncKind::Deleted,
    ];

    /// The kind's name, as in JSON.
    pub fn name(self) -> &'static str {
        match self {
            SyncKind::Tags => "tags",
            SyncKind::People => "people",
            SyncKind::Series => "series",
            SyncKind::Movies => "movies",
            SyncKind::Episodes => "episodes",
            SyncKind::Books => "books",
            SyncKind::Medias => "medias",
            SyncKind::Deleted => "deleted",
        }
    }
}

/// Where the sync of one library stands. Saved after each step; a missing or
/// unreadable one makes the next sync a full repair.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SyncState {
    /// Stamp of every row written since the state was created. A full sync of a kind
    /// removes the rows of that kind with an older stamp: those the server no longer has.
    pub generation: i64,
    /// Per kind, the largest `modified` (the deletion `date` for [`SyncKind::Deleted`])
    /// applied, in Unix milliseconds. A kind without one is synced in full.
    pub watermarks: BTreeMap<SyncKind, i64>,
    /// The media page a full media sync that was interrupted resumes from.
    #[serde(default)]
    pub media_resume: Option<String>,
}

/// Items to write in one library, in one transaction.
#[derive(Debug, Clone, Default)]
pub struct Changes {
    pub medias: Vec<MediaItem>,
    pub tags: Vec<Tag>,
    pub people: Vec<Person>,
    pub series: Vec<ItemWithRelations<Serie>>,
    pub movies: Vec<ItemWithRelations<Movie>>,
    pub episodes: Vec<Episode>,
    pub books: Vec<ItemWithRelations<Book>>,
    /// Items to remove.
    pub removed: Vec<Removal>,
}

/// An item to remove.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Removal {
    pub kind: SyncKind,
    /// For episodes, [`Episode::id`].
    pub id: String,
    /// When the server deleted it, from the deletions list: an item modified after
    /// it came back since and is kept. `None` (a live event): removed anyway.
    pub date: Option<i64>,
}

impl Changes {
    /// One movie to write.
    pub fn movie(movie: ItemWithRelations<Movie>) -> Changes {
        Changes {
            movies: vec![movie],
            ..Default::default()
        }
    }

    /// One episode to write.
    pub fn episode(episode: Episode) -> Changes {
        Changes {
            episodes: vec![episode],
            ..Default::default()
        }
    }

    pub fn is_empty(&self) -> bool {
        self.medias.is_empty()
            && self.tags.is_empty()
            && self.people.is_empty()
            && self.series.is_empty()
            && self.movies.is_empty()
            && self.episodes.is_empty()
            && self.books.is_empty()
            && self.removed.is_empty()
    }

    /// The kinds these changes touch.
    pub fn kinds(&self) -> Vec<SyncKind> {
        let mut kinds = Vec::new();
        let mut add = |kind: SyncKind, present: bool| {
            if present && !kinds.contains(&kind) {
                kinds.push(kind);
            }
        };
        add(SyncKind::Tags, !self.tags.is_empty());
        add(SyncKind::People, !self.people.is_empty());
        add(SyncKind::Series, !self.series.is_empty());
        add(SyncKind::Movies, !self.movies.is_empty());
        add(SyncKind::Episodes, !self.episodes.is_empty());
        add(SyncKind::Books, !self.books.is_empty());
        add(SyncKind::Medias, !self.medias.is_empty());
        for removal in &self.removed {
            add(removal.kind, true);
        }
        kinds
    }
}

/// The ids of one kind that a write changed: added, updated (written again: another
/// field, a newer version, or the same one synced again) and removed.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ItemIds {
    pub added: BTreeSet<String>,
    pub updated: BTreeSet<String>,
    pub removed: BTreeSet<String>,
}

impl ItemIds {
    pub fn is_empty(&self) -> bool {
        self.added.is_empty() && self.updated.is_empty() && self.removed.is_empty()
    }

    /// How many ids, all three sets together.
    pub fn len(&self) -> usize {
        self.added.len() + self.updated.len() + self.removed.len()
    }

    /// Adds what a `later` write changed: the net change of both, each id in one set
    /// at most. Added then removed is nothing; removed then added again is updated.
    pub fn merge(&mut self, later: ItemIds) {
        for id in later.added {
            if self.removed.remove(&id) || self.updated.contains(&id) {
                self.updated.insert(id);
            } else {
                self.added.insert(id);
            }
        }
        for id in later.updated {
            if !self.added.contains(&id) {
                self.removed.remove(&id);
                self.updated.insert(id);
            }
        }
        for id in later.removed {
            if !self.added.remove(&id) {
                self.updated.remove(&id);
                self.removed.insert(id);
            }
        }
    }
}

/// What a write changed, by kind: only the kinds it changed. Removals count under their
/// own kind, never under [`SyncKind::Deleted`].
pub type Written = BTreeMap<SyncKind, ItemIds>;

/// A thumbnail in the disk cache.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThumbRecord {
    pub library: String,
    pub media: String,
    /// Bytes on disk.
    pub size: u64,
    /// The media's thumbnail version when it was fetched: a different one means the
    /// server made a new thumbnail.
    pub version: String,
}

/// What a library's medias are the files of: which movies and episodes can be played.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FileLinks {
    /// The movies with at least one media.
    pub movies: HashSet<String>,
    /// For each series, the episodes of its medias: one span per media and season.
    pub episodes: HashMap<String, Vec<EpisodeSpan>>,
}

/// The episodes of one media: `first` to `last` of `season` (one episode when equal).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EpisodeSpan {
    pub season: u32,
    pub first: u32,
    pub last: u32,
}

impl FileLinks {
    /// Whether a media is the file of this episode, alone or with others.
    pub fn has_episode(&self, serie: &str, season: u32, number: u32) -> bool {
        (self.episodes.get(serie).into_iter().flatten())
            .any(|span| span.season == season && (span.first..=span.last).contains(&number))
    }
}

/// Storage of a mirror: one server's libraries. Every call is one transaction.
///
/// Items are kept as the shared types, so new server fields need no change here.
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
pub trait MirrorStore: crate::transport::MaybeSend {
    /// The libraries, in the server's order.
    async fn libraries(&self) -> Result<Vec<ServerLibraryForRead>>;
    /// Replaces the library list. The data of libraries no longer in it is removed;
    /// their ids are returned.
    async fn set_libraries(&self, libraries: Vec<ServerLibraryForRead>) -> Result<Vec<String>>;
    /// Adds or replaces one library, keeping its data.
    async fn put_library(&self, library: ServerLibraryForRead) -> Result<()>;
    /// Removes a library and its data. From then on, `set_sync_state`, `apply` and
    /// `put_thumb` for it write nothing (checked atomically with the write), so a sync
    /// still running when its library was removed cannot bring its data back.
    async fn remove_library(&self, library: &str) -> Result<()>;

    /// The sync state of a library. `None` when missing or unreadable.
    async fn sync_state(&self, library: &str) -> Result<Option<SyncState>>;
    async fn set_sync_state(&self, library: &str, state: SyncState) -> Result<()>;

    /// Writes items, stamped with `generation`. An item older (by `modified`) than the
    /// stored one only gets the stamp: a live event may have brought a newer version.
    /// A stamp never goes down: a write that read an older generation (a refresh that
    /// started before a full sync) must not leave a row for that sync to sweep.
    /// Returns the ids written and removed (not the ones only stamped).
    async fn apply(&self, library: &str, generation: i64, changes: Changes) -> Result<Written>;
    /// Removes the items of `kind` stamped before `generation`, after a full sync of
    /// that kind. Returns their ids.
    async fn sweep(&self, library: &str, kind: SyncKind, generation: i64) -> Result<Vec<String>>;

    /// Medias matching `query`, skipping `offset` of them.
    async fn medias(
        &self,
        library: &str,
        query: MediaQuery,
        offset: usize,
    ) -> Result<Vec<MediaItem>>;
    /// The number of medias matching `query` (without its page key and limit).
    async fn count_medias(&self, library: &str, query: MediaQuery) -> Result<u64>;
    async fn media(&self, library: &str, id: &str) -> Result<Option<MediaItem>>;
    /// The items of a kind other than medias, as JSON of their shared type. Episodes
    /// only of `serie` when given.
    async fn items(
        &self,
        library: &str,
        kind: SyncKind,
        serie: Option<String>,
    ) -> Result<Vec<serde_json::Value>>;
    /// The items of a kind (medias included) whose ids are in `ids`, as JSON of their
    /// shared type, in the order of `ids`. An id the copy does not have is left out.
    async fn items_by_id(
        &self,
        library: &str,
        kind: SyncKind,
        ids: Vec<String>,
    ) -> Result<Vec<serde_json::Value>>;
    /// The number of items of a kind.
    async fn count(&self, library: &str, kind: SyncKind) -> Result<u64>;
    /// What the medias of a library are the files of (their movies and episodes).
    async fn file_links(&self, library: &str) -> Result<FileLinks>;

    /// A cached thumbnail, marked as just used.
    async fn thumb(&self, library: &str, media: &str) -> Result<Option<ThumbRecord>>;
    async fn put_thumb(&self, record: ThumbRecord) -> Result<()>;
    async fn remove_thumbs(&self, library: &str, medias: Vec<String>) -> Result<()>;
    /// The total size of the cached thumbnails.
    async fn thumbs_size(&self) -> Result<u64>;
    /// The least recently used thumbnails to remove so the total fits in `limit`.
    /// Never an empty entry (an item without an image): it frees nothing.
    async fn thumbs_over(&self, limit: u64) -> Result<Vec<ThumbRecord>>;
}