redseat-api 0.8.0

Rust client for Redseat media servers
Documentation
//! Reads of single items by id, and of what a media is linked to.

use serde::de::DeserializeOwned;

use super::Mirror;
use super::store::SyncKind;
use crate::error::{Error, Result};
use crate::library::MediaItem;
use crate::types::ItemWithRelations;
use crate::types::book::Book;
use crate::types::episode::Episode;
use crate::types::media::{FileEpisode, MediaItemReference};
use crate::types::movie::Movie;
use crate::types::person::Person;
use crate::types::serie::Serie;
use crate::types::tag::Tag;

/// What a media is linked to, read from the copy: its people, tags, series (with the
/// episode), movies and books. An item the copy does not have yet is left out.
#[derive(Debug, Clone, Default)]
pub struct Related {
    pub people: Vec<Person>,
    pub tags: Vec<Tag>,
    pub series: Vec<RelatedEpisode>,
    pub movies: Vec<ItemWithRelations<Movie>>,
    pub books: Vec<ItemWithRelations<Book>>,
}

/// A series a media belongs to, where in it, and that episode when the copy has it.
#[derive(Debug, Clone)]
pub struct RelatedEpisode {
    pub serie: ItemWithRelations<Serie>,
    pub at: FileEpisode,
    pub episode: Option<Episode>,
}

impl Mirror {
    /// The items of `kind` whose ids are in `ids`, in that order; ids the copy does not
    /// have are left out.
    pub(super) async fn items_by_id<T: DeserializeOwned>(
        &self,
        library: &str,
        kind: SyncKind,
        ids: Vec<String>,
    ) -> Result<Vec<T>> {
        let values = self.inner.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()
    }

    async fn item<T: DeserializeOwned>(
        &self,
        library: &str,
        kind: SyncKind,
        id: &str,
    ) -> Result<Option<T>> {
        let mut found = self.items_by_id(library, kind, vec![id.to_owned()]).await?;
        Ok(found.pop())
    }

    /// One person of a library.
    pub async fn person(&self, library: &str, id: &str) -> Result<Option<Person>> {
        self.item(library, SyncKind::People, id).await
    }

    /// One tag of a library.
    pub async fn tag(&self, library: &str, id: &str) -> Result<Option<Tag>> {
        self.item(library, SyncKind::Tags, id).await
    }

    /// One series of a library, with its relations.
    pub async fn serie(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Serie>>> {
        self.item(library, SyncKind::Series, id).await
    }

    /// One movie of a library, with its relations.
    pub async fn movie(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Movie>>> {
        self.item(library, SyncKind::Movies, id).await
    }

    /// One episode of a library, by its id ([`Episode::id`]: series, season and
    /// number).
    pub async fn episode(&self, library: &str, id: &str) -> Result<Option<Episode>> {
        self.item(library, SyncKind::Episodes, id).await
    }

    /// One book of a library, with its relations.
    pub async fn book(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Book>>> {
        self.item(library, SyncKind::Books, id).await
    }

    /// What `media` is linked to, in the order the media lists them: one read per
    /// kind it has.
    pub async fn related(&self, library: &str, media: &MediaItem) -> Result<Related> {
        let Some(relations) = &media.relations else {
            return Ok(Related::default());
        };
        let ids = |list: &Option<Vec<MediaItemReference>>| -> Vec<String> {
            list.iter().flatten().map(|r| r.id.clone()).collect()
        };
        let people = ids(&relations.people);
        let tags = ids(&relations.tags);
        let at: Vec<FileEpisode> = relations.series.clone().unwrap_or_default();
        let movies = relations.movies.clone().unwrap_or_default();
        let books = relations.books.clone().unwrap_or_default();

        let mut related = Related::default();
        if !people.is_empty() {
            related.people = self.items_by_id(library, SyncKind::People, people).await?;
        }
        if !tags.is_empty() {
            related.tags = self.items_by_id(library, SyncKind::Tags, tags).await?;
        }
        if !movies.is_empty() {
            related.movies = self.items_by_id(library, SyncKind::Movies, movies).await?;
        }
        if !books.is_empty() {
            related.books = self.items_by_id(library, SyncKind::Books, books).await?;
        }
        if !at.is_empty() {
            let ids = at.iter().map(|a| a.id.clone()).collect();
            let series: Vec<ItemWithRelations<Serie>> =
                self.items_by_id(library, SyncKind::Series, ids).await?;
            let episode_id = |a: &FileEpisode| match (a.season, a.episode) {
                (Some(season), Some(number)) => Some(format!("{}x{season}x{number}", a.id)),
                _ => None,
            };
            let ids = at.iter().filter_map(episode_id).collect();
            let episodes: Vec<Episode> = self.items_by_id(library, SyncKind::Episodes, ids).await?;
            for a in at {
                let Some(serie) = series.iter().find(|s| s.item.id == a.id) else {
                    continue;
                };
                let wanted = episode_id(&a);
                let episode = episodes.iter().find(|e| Some(e.id()) == wanted).cloned();
                related.series.push(RelatedEpisode {
                    serie: serie.clone(),
                    at: a,
                    episode,
                });
            }
        }
        Ok(related)
    }
}