redseat-api 0.4.0

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

use std::collections::BTreeMap;

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 {
    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
    }
}

/// 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,
}

/// 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.
    async fn apply(&self, library: &str, generation: i64, changes: Changes) -> Result<()>;
    /// 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 number of items of a kind.
    async fn count(&self, library: &str, kind: SyncKind) -> Result<u64>;

    /// 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`.
    async fn thumbs_over(&self, limit: u64) -> Result<Vec<ThumbRecord>>;
}