use std::cmp::Reverse;
use std::collections::{HashMap, HashSet};
use crate::library::MediaItem;
use crate::mirror::FileLinks;
use crate::types::ItemWithRelations;
use crate::types::episode::Episode;
use crate::types::media::FileType;
use crate::types::movie::Movie;
use crate::types::serie::{Serie, SerieStatus};
use crate::types::tag::Tag;
use super::ServerCopy;
use super::text;
use crate::client::now_ms;
use crate::error::Result;
use crate::types::library::LibraryType;
use crate::types::media::{MediaQuery, RsSort, SqlOrder};
pub const SHELF_LIMIT: usize = 20;
pub const FEATURED_LIMIT: usize = 6;
pub const RESUME_WINDOW: i64 = 10 * DAY;
pub const GENRE_SHELVES: usize = 4;
const GENRE_MIN: usize = 3;
const NEARLY_DONE: f32 = 0.95;
pub const WATCHED_AT: f64 = 0.9;
const DAY: i64 = 24 * 3600 * 1000;
const MINUTE: u64 = 60 * 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CatalogKind {
Movies,
Shows,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Title {
Movie(Movie),
Show(Serie),
}
impl Title {
pub fn id(&self) -> &str {
match self {
Title::Movie(movie) => &movie.id,
Title::Show(serie) => &serie.id,
}
}
pub fn name(&self) -> &str {
match self {
Title::Movie(movie) => &movie.name,
Title::Show(serie) => &serie.name,
}
}
pub fn year(&self) -> Option<u16> {
match self {
Title::Movie(movie) => movie.year,
Title::Show(serie) => serie.year,
}
}
pub fn overview(&self) -> Option<&str> {
match self {
Title::Movie(movie) => movie.overview.as_deref(),
Title::Show(serie) => serie.overview.as_deref(),
}
.filter(|overview| !overview.trim().is_empty())
}
pub fn imdb_rating(&self) -> Option<f32> {
match self {
Title::Movie(movie) => movie.imdb_rating,
Title::Show(serie) => serie.imdb_rating,
}
.filter(|rating| *rating > 0.)
}
pub fn added(&self) -> u64 {
match self {
Title::Movie(movie) => movie.added,
Title::Show(serie) => serie.added,
}
}
pub fn has_backdrop(&self) -> bool {
let (background, card) = match self {
Title::Movie(movie) => (movie.backgroundv, movie.cardv),
Title::Show(serie) => (serie.backgroundv, serie.cardv),
};
background > 0 || card > 0
}
pub fn eyebrow(&self) -> &'static str {
match self {
Title::Movie(_) => "Movie",
Title::Show(_) => "TV Show",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Playable {
Movie(String),
Episode {
serie: String,
season: u32,
number: u32,
},
}
impl Playable {
pub fn episode(episode: &Episode) -> Playable {
Playable::Episode {
serie: episode.serie.clone(),
season: episode.season,
number: episode.number,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Play {
pub target: Playable,
pub start: u64,
pub label: String,
}
impl Play {
pub fn resumes(&self) -> bool {
self.start > 0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShelfStyle {
Landscape,
Poster,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShelfKind {
ContinueWatching,
UpNext,
RecentlyAdded,
Unwatched,
TopRated,
Genre(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Tile {
pub title: Title,
pub episode: Option<Episode>,
pub subtitle: String,
pub progress: Option<f32>,
pub watched: bool,
pub available: bool,
pub play: Option<Play>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Shelf {
pub kind: ShelfKind,
pub heading: String,
pub style: ShelfStyle,
pub tiles: Vec<Tile>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Featured {
pub title: Title,
pub meta: String,
pub imdb: Option<String>,
pub progress: Option<f32>,
pub play: Option<Play>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Home {
pub featured: Vec<Featured>,
pub shelves: Vec<Shelf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TitleSort {
#[default]
Name,
Added,
Released,
Rating,
}
impl TitleSort {
pub const ALL: [TitleSort; 4] = [
TitleSort::Name,
TitleSort::Added,
TitleSort::Released,
TitleSort::Rating,
];
pub fn label(self) -> &'static str {
match self {
TitleSort::Name => "Title",
TitleSort::Added => "Recently Added",
TitleSort::Released => "Release Date",
TitleSort::Rating => "IMDb Rating",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WatchedFilter {
#[default]
All,
Unwatched,
Watched,
}
impl WatchedFilter {
pub const ALL: [WatchedFilter; 3] = [
WatchedFilter::All,
WatchedFilter::Unwatched,
WatchedFilter::Watched,
];
pub fn label(self) -> &'static str {
match self {
WatchedFilter::All => "All",
WatchedFilter::Unwatched => "Unwatched",
WatchedFilter::Watched => "Watched",
}
}
}
#[derive(Debug, Clone)]
struct Entry {
title: Title,
genres: Vec<String>,
available: bool,
episodes: Vec<Episode>,
}
#[derive(Debug, Clone)]
pub struct Catalog {
kind: CatalogKind,
entries: Vec<Entry>,
genres: HashMap<String, String>,
links: FileLinks,
now: i64,
}
impl Catalog {
pub fn movies(
movies: Vec<ItemWithRelations<Movie>>,
tags: &[Tag],
links: FileLinks,
now: i64,
) -> Catalog {
let entries = movies
.into_iter()
.map(|movie| Entry {
genres: tag_ids(movie.relations.as_ref()),
available: links.movies.contains(&movie.item.id),
title: Title::Movie(movie.item),
episodes: Vec::new(),
})
.collect();
Catalog::new(CatalogKind::Movies, entries, tags, links, now)
}
pub fn shows(
series: Vec<ItemWithRelations<Serie>>,
episodes: Vec<Episode>,
tags: &[Tag],
links: FileLinks,
now: i64,
) -> Catalog {
let mut by_serie: HashMap<String, Vec<Episode>> = HashMap::new();
for episode in episodes {
by_serie
.entry(episode.serie.clone())
.or_default()
.push(episode);
}
let entries = series
.into_iter()
.map(|serie| {
let episodes = by_serie.remove(&serie.item.id).unwrap_or_default();
show_entry(serie, episodes, &links)
})
.collect();
Catalog::new(CatalogKind::Shows, entries, tags, links, now)
}
fn new(
kind: CatalogKind,
entries: Vec<Entry>,
tags: &[Tag],
links: FileLinks,
now: i64,
) -> Catalog {
let genres = (tags.iter())
.map(|tag| (tag.id.clone(), tag.name.clone()))
.collect();
Catalog {
kind,
entries,
genres,
links,
now,
}
}
pub fn kind(&self) -> CatalogKind {
self.kind
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn home(&self) -> Home {
match self.kind {
CatalogKind::Movies => self.movies_home(),
CatalogKind::Shows => self.shows_home(),
}
}
pub fn titles(&self, order: TitleSort, filter: WatchedFilter) -> Vec<Tile> {
let mut entries: Vec<&Entry> = (self.entries.iter())
.filter(|entry| match filter {
WatchedFilter::All => true,
WatchedFilter::Unwatched => !self.finished(entry),
WatchedFilter::Watched => self.finished(entry),
})
.collect();
let name = |entry: &&Entry| entry.title.name().to_lowercase();
match order {
TitleSort::Name => entries.sort_by_cached_key(name),
TitleSort::Added => entries.sort_by_key(|e| Reverse(e.title.added())),
TitleSort::Released => entries.sort_by_cached_key(|e| {
let airdate = match &e.title {
Title::Movie(movie) => movie.airdate,
Title::Show(_) => None,
};
(
e.title.year().is_none(),
Reverse(e.title.year()),
Reverse(airdate),
name(e),
)
}),
TitleSort::Rating => entries.sort_by_cached_key(|e| {
let rating = e.title.imdb_rating().map(|r| (r * 100.) as i64);
(rating.is_none(), Reverse(rating), name(e))
}),
}
entries.into_iter().map(|e| self.poster(e)).collect()
}
fn finished(&self, entry: &Entry) -> bool {
match &entry.title {
Title::Movie(movie) => is_watched(movie.watched),
Title::Show(_) => {
let mut aired = (entry.episodes.iter())
.filter(|e| e.season > 0 && aired(e, self.now))
.peekable();
aired.peek().is_some() && aired.all(|e| is_watched(e.watched))
}
}
}
fn poster(&self, entry: &Entry) -> Tile {
let (watched, progress) = match &entry.title {
Title::Movie(movie) => (is_watched(movie.watched), movie_progress(movie)),
Title::Show(_) => (false, None),
};
Tile {
title: entry.title.clone(),
episode: None,
subtitle: (entry.title.year())
.map(|year| year.to_string())
.unwrap_or_default(),
progress,
watched,
available: entry.available,
play: None,
}
}
fn movies_home(&self) -> Home {
let movie = |entry: &Entry| match &entry.title {
Title::Movie(movie) => Some(movie.clone()),
Title::Show(_) => None,
};
let mut resumed: Vec<(&Entry, Movie)> = (self.entries.iter())
.filter_map(|entry| Some((entry, movie(entry)?)))
.filter(|(entry, movie)| {
entry.available
&& movie_progress(movie).is_some()
&& movie
.progress_modified
.is_none_or(|at| at as i64 >= self.now - RESUME_WINDOW)
})
.collect();
resumed
.sort_by_key(|(_, movie)| Reverse(movie.progress_modified.unwrap_or(movie.modified)));
let continuing = (resumed.into_iter())
.take(SHELF_LIMIT)
.map(|(entry, movie)| Tile {
subtitle: movie_left(&movie),
progress: movie_progress(&movie),
watched: false,
available: true,
play: Some(movie_play(&movie)),
episode: None,
title: entry.title.clone(),
})
.collect();
let recent = self.by_added(|_| true);
let unwatched = self.by_added(|entry| !self.finished(entry));
let mut shelves = vec![
self.shelf(
ShelfKind::ContinueWatching,
ShelfStyle::Landscape,
continuing,
),
self.posters(ShelfKind::RecentlyAdded, &recent),
self.posters(ShelfKind::Unwatched, &unwatched),
self.posters(ShelfKind::TopRated, &self.top_rated()),
];
shelves.extend(self.genre_shelves());
shelves.retain(|shelf| !shelf.tiles.is_empty());
let featured = interleave(&unwatched, &recent)
.filter(|entry| entry.available && entry.title.has_backdrop())
.take(FEATURED_LIMIT)
.filter_map(|entry| {
let movie = movie(entry)?;
Some(Featured {
meta: self.meta(entry),
imdb: imdb(entry.title.imdb_rating()),
progress: movie_progress(&movie),
play: Some(movie_play(&movie)),
title: entry.title.clone(),
})
})
.collect();
Home { featured, shelves }
}
fn shows_home(&self) -> Home {
let mut next: Vec<(i64, Tile)> = (self.entries.iter())
.filter_map(|entry| {
let regular: Vec<&Episode> =
(entry.episodes.iter()).filter(|e| e.season > 0).collect();
let started =
(regular.iter()).any(|e| is_watched(e.watched) || e.progress.unwrap_or(0) > 0);
if !started {
return None;
}
let episode = next_episode(®ular)?;
if !aired(episode, self.now) || !self.has_file(episode) {
return None;
}
let last_watched = (regular.iter())
.filter_map(|e| e.watched.filter(|w| *w > 0))
.max()
.unwrap_or(0);
let recency = last_watched
.max(episode.progress_modified.unwrap_or(0) as i64)
.max(episode.airdate.unwrap_or(0));
Some((recency, self.episode_tile(entry, episode)))
})
.collect();
next.sort_by_key(|(recency, _)| Reverse(*recency));
let up_next = (next.into_iter())
.take(SHELF_LIMIT)
.map(|(_, tile)| tile)
.collect();
let recent = self.by_added(|_| true);
let mut shelves = vec![
self.shelf(ShelfKind::UpNext, ShelfStyle::Landscape, up_next),
self.posters(ShelfKind::RecentlyAdded, &recent),
self.posters(ShelfKind::TopRated, &self.top_rated()),
];
shelves.extend(self.genre_shelves());
shelves.retain(|shelf| !shelf.tiles.is_empty());
let featured = (recent.iter().copied())
.filter(|entry| entry.available && entry.title.has_backdrop())
.take(FEATURED_LIMIT)
.map(|entry| Featured {
meta: self.meta(entry),
imdb: imdb(entry.title.imdb_rating()),
progress: None,
play: self.show_play(entry),
title: entry.title.clone(),
})
.collect();
Home { featured, shelves }
}
fn episode_tile(&self, entry: &Entry, episode: &Episode) -> Tile {
let progress = episode_progress(episode);
let state = match episode_left(episode) {
Some(left) => left,
None if progress.is_some() => "Resume".to_owned(),
None => "Next episode".to_owned(),
};
Tile {
title: entry.title.clone(),
subtitle: format!("{} · {state}", episode_label(episode)),
progress,
watched: false,
available: true,
play: Some(episode_play(episode)),
episode: Some(episode.clone()),
}
}
fn show_play(&self, entry: &Entry) -> Option<Play> {
let regular: Vec<&Episode> = (entry.episodes.iter()).filter(|e| e.season > 0).collect();
next_episode(®ular)
.filter(|episode| self.has_file(episode))
.map(episode_play)
}
fn has_file(&self, episode: &Episode) -> bool {
(self.links).has_episode(&episode.serie, episode.season, episode.number)
}
fn by_added(&self, keep: impl Fn(&Entry) -> bool) -> Vec<&Entry> {
let mut entries: Vec<&Entry> = self.entries.iter().filter(|e| keep(e)).collect();
entries.sort_by_key(|e| Reverse(e.title.added()));
entries
}
fn top_rated(&self) -> Vec<&Entry> {
let mut entries: Vec<&Entry> = (self.entries.iter())
.filter(|e| e.title.imdb_rating().is_some())
.collect();
entries.sort_by_key(|e| Reverse((e.title.imdb_rating().unwrap_or(0.) * 100.) as i64));
entries
}
fn genre_shelves(&self) -> Vec<Shelf> {
let mut counts: HashMap<&str, usize> = HashMap::new();
for entry in &self.entries {
for genre in &entry.genres {
*counts.entry(genre).or_default() += 1;
}
}
let mut genres: Vec<(&str, usize)> = (counts.into_iter())
.filter(|(id, count)| *count >= GENRE_MIN && self.genres.contains_key(*id))
.collect();
genres.sort_by_key(|(id, count)| (Reverse(*count), self.genres[*id].to_lowercase()));
(genres.into_iter())
.take(GENRE_SHELVES)
.map(|(id, _)| {
let titles = self.by_added(|entry| entry.genres.iter().any(|g| g == id));
let mut shelf = self.posters(ShelfKind::Genre(id.to_owned()), &titles);
shelf.heading = self.genres[id].clone();
shelf
})
.collect()
}
fn posters(&self, kind: ShelfKind, entries: &[&Entry]) -> Shelf {
let tiles = (entries.iter())
.take(SHELF_LIMIT)
.map(|entry| self.poster(entry))
.collect();
self.shelf(kind, ShelfStyle::Poster, tiles)
}
fn shelf(&self, kind: ShelfKind, style: ShelfStyle, tiles: Vec<Tile>) -> Shelf {
let heading = match (&kind, self.kind) {
(ShelfKind::ContinueWatching, _) => "Continue Watching",
(ShelfKind::UpNext, _) => "Up Next",
(ShelfKind::RecentlyAdded, CatalogKind::Movies) => "Recently Added",
(ShelfKind::RecentlyAdded, CatalogKind::Shows) => "Recently Added Shows",
(ShelfKind::Unwatched, _) => "Unwatched",
(ShelfKind::TopRated, _) => "Top Rated",
(ShelfKind::Genre(_), _) => "",
};
Shelf {
kind,
heading: heading.to_owned(),
style,
tiles,
}
}
fn genre_names(&self, entry: &Entry) -> Vec<String> {
(entry.genres.iter())
.filter_map(|id| self.genres.get(id).cloned())
.take(2)
.collect()
}
fn meta(&self, entry: &Entry) -> String {
let length = match &entry.title {
Title::Movie(movie) => movie.duration.map(|m| text::runtime(u64::from(m))),
Title::Show(_) => seasons_label(&entry.episodes),
};
meta_line(entry.title.year(), &self.genre_names(entry), length)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MoviePage {
pub movie: Movie,
pub meta: String,
pub imdb: Option<String>,
pub genres: Vec<String>,
pub watched: bool,
pub progress: Option<f32>,
pub left: Option<String>,
pub play: Option<Play>,
pub start_over: Option<Play>,
pub files: Vec<FileRow>,
pub facts: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ShowPage {
pub serie: Serie,
pub meta: String,
pub imdb: Option<String>,
pub genres: Vec<String>,
pub seasons: Vec<Season>,
pub current_season: Option<u32>,
pub play: Option<Play>,
pub facts: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Season {
pub number: u32,
pub name: String,
pub episodes: Vec<EpisodeRow>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EpisodeRow {
pub episode: Episode,
pub name: String,
pub details: String,
pub watched: bool,
pub progress: Option<f32>,
pub upcoming: bool,
pub available: bool,
pub next: bool,
pub play: Option<Play>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FileRow {
pub media: MediaItem,
pub name: String,
pub details: String,
}
impl FileRow {
pub fn new(media: MediaItem) -> FileRow {
let item = &media.item;
let mut parts = Vec::new();
if let Some(height) = item.height.filter(|h| *h > 0) {
parts.push(format!("{height}p"));
}
if let Some(size) = item.size.filter(|s| *s > 0) {
parts.push(text::bytes(size));
}
if let Some(duration) = item.duration.filter(|d| *d > 0) {
parts.push(text::duration(duration as u64));
}
FileRow {
name: item.name.clone(),
details: parts.join(" · "),
media,
}
}
}
pub fn is_video(media: &MediaItem) -> bool {
media.item.kind == FileType::Video || media.item.mimetype.starts_with("video/")
}
pub fn movie_page(
movie: ItemWithRelations<Movie>,
tags: &[Tag],
files: Vec<MediaItem>,
now: i64,
) -> MoviePage {
let catalog = Catalog::movies(vec![movie.clone()], tags, FileLinks::default(), now);
let genres = (catalog.entries.first())
.map(|entry| catalog.genre_names_all(entry))
.unwrap_or_default();
let meta = (catalog.entries.first())
.map(|entry| catalog.meta(entry))
.unwrap_or_default();
let movie = movie.item;
let files: Vec<FileRow> = files
.into_iter()
.filter(is_video)
.map(FileRow::new)
.collect();
let progress = movie_progress(&movie);
let play = (!files.is_empty()).then(|| movie_play(&movie));
let start_over = play.as_ref().filter(|p| p.resumes()).map(|p| Play {
start: 0,
label: "Start Over".to_owned(),
..p.clone()
});
let mut facts = Vec::new();
let mut fact = |label: &str, value: Option<String>| {
if let Some(value) = value.filter(|v| !v.is_empty()) {
facts.push((label.to_owned(), value));
}
};
fact("Released", movie.airdate.map(text::day));
fact("Digital release", movie.digitalairdate.map(text::day));
fact(
"Runtime",
movie.duration.map(|m| text::runtime(u64::from(m))),
);
fact(
"Original title",
movie.original.clone().filter(|o| *o != movie.name),
);
fact("Country", movie.country.clone());
fact("Language", movie.lang.clone());
fact("IMDb", rating(movie.imdb_rating, movie.imdb_votes));
fact(
"Trakt",
rating(movie.trakt_rating, movie.trakt_votes.map(u64::from)),
);
MoviePage {
meta,
imdb: imdb(movie.imdb_rating.filter(|r| *r > 0.)),
genres,
watched: is_watched(movie.watched),
progress,
left: progress.and(minutes_left(movie.progress, movie.duration.map(u64::from))),
play,
start_over,
files,
facts,
movie,
}
}
pub fn show_page(
serie: ItemWithRelations<Serie>,
episodes: Vec<Episode>,
tags: &[Tag],
links: FileLinks,
now: i64,
) -> ShowPage {
let entry = show_entry(serie, episodes, &links);
let catalog = Catalog::new(CatalogKind::Shows, Vec::new(), tags, links, now);
let entry = &entry;
let Title::Show(serie) = &entry.title else {
return Default::default();
};
let regular: Vec<&Episode> = (entry.episodes.iter()).filter(|e| e.season > 0).collect();
let next = next_episode(®ular).map(Episode::id);
let mut seasons: Vec<Season> = Vec::new();
for episode in &entry.episodes {
let available = catalog.has_file(episode);
let progress = episode_progress(episode);
let upcoming = !aired(episode, now);
let mut details = Vec::new();
if let Some(airdate) = episode.airdate {
details.push(text::day(airdate));
}
if let Some(duration) = episode.duration.filter(|d| *d > 0) {
details.push(text::runtime(duration));
}
if let Some(left) = progress.and(episode_left(episode)) {
details.push(left);
}
let name = (episode.name.clone())
.filter(|n| !n.trim().is_empty())
.unwrap_or_else(|| format!("Episode {}", episode.number));
let row = EpisodeRow {
name: format!("{}. {name}", episode.number),
details: details.join(" · "),
watched: is_watched(episode.watched),
progress,
upcoming,
available,
next: next.as_deref() == Some(&episode.id()),
play: available.then(|| episode_play(episode)),
episode: episode.clone(),
};
match seasons.last_mut() {
Some(season) if season.number == episode.season => season.episodes.push(row),
_ => seasons.push(Season {
number: episode.season,
name: season_name(episode.season),
episodes: vec![row],
}),
}
}
let current_season = (next.as_ref())
.and_then(|id| regular.iter().find(|e| &e.id() == id))
.map(|e| e.season)
.or_else(|| seasons.iter().map(|s| s.number).find(|n| *n > 0))
.or_else(|| seasons.first().map(|s| s.number));
let mut facts = Vec::new();
let mut fact = |label: &str, value: Option<String>| {
if let Some(value) = value.filter(|v| !v.is_empty()) {
facts.push((label.to_owned(), value));
}
};
fact("Status", serie.status.as_ref().and_then(status_label));
fact(
"Original title",
serie.original.clone().filter(|o| *o != serie.name),
);
fact("Language", serie.lang.clone());
fact("IMDb", rating(serie.imdb_rating, serie.imdb_votes));
fact("Trakt", rating(serie.trakt_rating, serie.trakt_votes));
ShowPage {
meta: catalog.meta(entry),
imdb: imdb(serie.imdb_rating.filter(|r| *r > 0.)),
genres: catalog.genre_names_all(entry),
play: catalog.show_play(entry),
current_season,
seasons,
facts,
serie: serie.clone(),
}
}
fn show_entry(
serie: ItemWithRelations<Serie>,
mut episodes: Vec<Episode>,
links: &FileLinks,
) -> Entry {
episodes.sort_by_key(episode_order);
let available = (episodes.iter()).any(|e| links.has_episode(&e.serie, e.season, e.number));
Entry {
genres: tag_ids(serie.relations.as_ref()),
available,
title: Title::Show(serie.item),
episodes,
}
}
impl Catalog {
fn genre_names_all(&self, entry: &Entry) -> Vec<String> {
(entry.genres.iter())
.filter_map(|id| self.genres.get(id).cloned())
.collect()
}
}
fn episode_order(episode: &Episode) -> (bool, u32, u32) {
(episode.season == 0, episode.season, episode.number)
}
pub fn next_episode<'a>(regular: &[&'a Episode]) -> Option<&'a Episode> {
if let Some(started) =
(regular.iter()).find(|e| !is_watched(e.watched) && e.progress.unwrap_or(0) > 0)
{
return Some(started);
}
let last = (regular.iter().enumerate())
.filter(|(_, e)| is_watched(e.watched))
.max_by_key(|(_, e)| e.watched);
match last {
Some((at, _)) => (regular[at + 1..].iter())
.find(|e| !is_watched(e.watched))
.copied(),
None => regular.first().copied(),
}
}
fn tag_ids(relations: Option<&crate::types::Relations>) -> Vec<String> {
(relations
.and_then(|r| r.tags.as_ref())
.into_iter()
.flatten())
.map(|tag| tag.id.clone())
.collect()
}
fn is_watched(watched: Option<i64>) -> bool {
watched.is_some_and(|date| date > 0)
}
fn aired(episode: &Episode, now: i64) -> bool {
episode.airdate.is_none_or(|airdate| airdate <= now)
}
fn ratio(progress: Option<u64>, duration: Option<u64>) -> Option<f32> {
let progress = progress.filter(|p| *p > 0)?;
let ratio = match duration.filter(|d| *d > 0) {
Some(duration) => (progress as f32 / (duration * MINUTE) as f32).min(1.),
None => 0.02,
};
(ratio < NEARLY_DONE).then_some(ratio)
}
fn movie_progress(movie: &Movie) -> Option<f32> {
if is_watched(movie.watched) {
return None;
}
ratio(movie.progress, movie.duration.map(u64::from))
}
fn episode_progress(episode: &Episode) -> Option<f32> {
if is_watched(episode.watched) {
return None;
}
ratio(episode.progress, episode.duration)
}
fn minutes_left(progress: Option<u64>, duration: Option<u64>) -> Option<String> {
let total = duration.filter(|d| *d > 0)? * MINUTE;
let left = total.saturating_sub(progress.unwrap_or(0)).div_ceil(MINUTE);
Some(format!("{} left", text::runtime(left.max(1))))
}
fn movie_left(movie: &Movie) -> String {
minutes_left(movie.progress, movie.duration.map(u64::from)).unwrap_or_else(|| "Resume".into())
}
fn episode_left(episode: &Episode) -> Option<String> {
episode_progress(episode)?;
minutes_left(episode.progress, episode.duration)
}
fn movie_play(movie: &Movie) -> Play {
let start = match movie_progress(movie) {
Some(_) => movie.progress.unwrap_or(0),
None => 0,
};
Play {
target: Playable::Movie(movie.id.clone()),
start,
label: if start > 0 { "Resume" } else { "Play" }.to_owned(),
}
}
fn episode_play(episode: &Episode) -> Play {
let start = match episode_progress(episode) {
Some(_) => episode.progress.unwrap_or(0),
None => 0,
};
let verb = if start > 0 { "Resume" } else { "Play" };
Play {
target: Playable::episode(episode),
start,
label: format!("{verb} {}", episode_label(episode)),
}
}
pub fn episode_label(episode: &Episode) -> String {
format!("S{}, E{}", episode.season, episode.number)
}
pub fn season_name(season: u32) -> String {
match season {
0 => "Specials".to_owned(),
n => format!("Season {n}"),
}
}
fn seasons_label(episodes: &[Episode]) -> Option<String> {
let seasons: HashSet<u32> = (episodes.iter())
.map(|e| e.season)
.filter(|s| *s > 0)
.collect();
match seasons.len() {
0 => None,
1 => Some("1 season".to_owned()),
n => Some(format!("{n} seasons")),
}
}
fn meta_line(year: Option<u16>, genres: &[String], length: Option<String>) -> String {
let mut parts = Vec::new();
if let Some(year) = year {
parts.push(year.to_string());
}
if !genres.is_empty() {
parts.push(genres.join(", "));
}
parts.extend(length);
parts.join(" · ")
}
fn imdb(rating: Option<f32>) -> Option<String> {
rating.map(|rating| format!("{rating:.1}"))
}
fn rating(rating: Option<f32>, votes: Option<u64>) -> Option<String> {
let rating = rating.filter(|r| *r > 0.)?;
Some(match votes.filter(|v| *v > 0) {
Some(votes) => format!("{rating:.1} ({} votes)", text::thousands(votes)),
None => format!("{rating:.1}"),
})
}
fn status_label(status: &SerieStatus) -> Option<String> {
Some(
match status {
SerieStatus::Returning => "Returning series",
SerieStatus::InProduction => "In production",
SerieStatus::PostProduction => "Post-production",
SerieStatus::Planned => "Planned",
SerieStatus::Rumored => "Rumored",
SerieStatus::Ended => "Ended",
SerieStatus::Released => "Released",
SerieStatus::Canceled => "Canceled",
SerieStatus::Pilot => "Pilot",
SerieStatus::Other(other) => return Some(other.clone()),
SerieStatus::Unknown => return None,
}
.to_owned(),
)
}
fn interleave<'a>(first: &[&'a Entry], second: &[&'a Entry]) -> impl Iterator<Item = &'a Entry> {
let mut seen = HashSet::new();
let longest = first.len().max(second.len());
(0..longest)
.flat_map(move |i| [first.get(i).copied(), second.get(i).copied()])
.flatten()
.filter(move |entry| seen.insert(entry.title.id().to_owned()))
}
const MAX_FILES: usize = 100;
impl ServerCopy {
pub async fn catalog(&self, library: &str) -> Result<Option<Catalog>> {
let kind = match self.mirror().library(library).await?.map(|l| l.kind) {
Some(LibraryType::Movies) => CatalogKind::Movies,
Some(LibraryType::Shows) => CatalogKind::Shows,
_ => return Ok(None),
};
let tags = self.tags(library).await?;
let links = self.mirror().file_links(library).await?;
let now = now_ms();
Ok(Some(match kind {
CatalogKind::Movies => Catalog::movies(self.movies(library).await?, &tags, links, now),
CatalogKind::Shows => {
let series = self.series(library).await?;
let episodes = self.episodes(library, None).await?;
Catalog::shows(series, episodes, &tags, links, now)
}
}))
}
pub async fn movie_page(&self, library: &str, movie: &str) -> Result<Option<MoviePage>> {
let Some(found) = self.movie(library, movie).await? else {
return Ok(None);
};
let tags = self.tags(library).await?;
let files = self
.files(library, &Playable::Movie(movie.to_owned()))
.await?;
Ok(Some(movie_page(found, &tags, files, now_ms())))
}
pub async fn show_page(&self, library: &str, serie: &str) -> Result<Option<ShowPage>> {
let Some(found) = self.serie(library, serie).await? else {
return Ok(None);
};
let tags = self.tags(library).await?;
let episodes = self.episodes(library, Some(serie)).await?;
let links = self.mirror().file_links(library).await?;
Ok(Some(show_page(found, episodes, &tags, links, now_ms())))
}
pub async fn files(&self, library: &str, target: &Playable) -> Result<Vec<MediaItem>> {
let mut query = MediaQuery {
sort: RsSort::Name,
order: SqlOrder::ASC,
..Default::default()
};
match target {
Playable::Movie(movie) => query.movie = Some(movie.clone()),
Playable::Episode {
serie,
season,
number,
} => query.series = vec![format!("{serie}|{season}|{number}")],
}
let mut files = Vec::new();
let mut offset = 0;
loop {
let page = self.medias(library, &query, offset, MAX_FILES).await?;
let read = page.len();
files.extend(page.into_iter().filter(is_video));
if read < MAX_FILES || files.len() >= MAX_FILES {
break;
}
offset += read;
}
files.truncate(MAX_FILES);
Ok(files)
}
pub async fn set_watched(&self, library: &str, target: &Playable, watched: bool) -> Result<()> {
match target {
Playable::Movie(movie) => {
(self.mirror())
.set_movie_watched(library, movie, watched)
.await
}
Playable::Episode { .. } => {
let episode = self.target_episode(library, target).await?;
(self.mirror())
.set_episode_watched(library, &episode, watched)
.await
}
}
}
pub async fn save_progress(
&self,
library: &str,
target: &Playable,
progress: u64,
) -> Result<()> {
match target {
Playable::Movie(movie) => {
(self.mirror())
.set_movie_progress(library, movie, progress)
.await
}
Playable::Episode { .. } => {
let episode = self.target_episode(library, target).await?;
(self.mirror())
.set_episode_progress(library, &episode, progress)
.await
}
}
}
pub async fn record_playback(
&self,
library: &str,
target: &Playable,
position: u64,
duration: u64,
) -> Result<()> {
if duration > 0 && position as f64 >= duration as f64 * WATCHED_AT {
self.set_watched(library, target, true).await
} else {
self.save_progress(library, target, position).await
}
}
pub async fn refresh_viewing(&self, library: &str) -> Result<()> {
self.mirror().refresh_viewing(library).await
}
async fn target_episode(&self, library: &str, target: &Playable) -> Result<Episode> {
let Playable::Episode {
serie,
season,
number,
} = target
else {
return Ok(Episode::default());
};
let wanted = Episode {
serie: serie.clone(),
season: *season,
number: *number,
..Default::default()
};
Ok(self.episode(library, &wanted.id()).await?.unwrap_or(wanted))
}
}
#[cfg(test)]
mod tests;