//! Filmek / Sorozatok: Ajánlott, Könyvtáram, Böngészés (as in the web app's //! pages/Browse.tsx). use std::any::Any; use std::collections::{HashMap, HashSet}; use crate::api::{ContinueItem, Genre, ListItem, MediaType, TitleState, TitleSummary}; use crate::app::{Cx, Look, Screen}; use crate::page::{C, Ch, Frame, GRID, L, Spec, grid_lines}; use crate::screens::{self, Load, continue_card, title_card}; /// Pages in a row that matched nothing before loading stops and asks. const MAX_EMPTY_STREAK: usize = 3; const DECADES: [(&str, Option, Option); 6] = [ ("2020-as évek", Some(2020), None), ("2010-es évek", Some(2010), Some(2019)), ("2000-es évek", Some(2000), Some(2009)), ("1990-es évek", Some(1990), Some(1999)), ("1980-as évek", Some(1980), Some(1989)), ("Régebbi", None, Some(1979)), ]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Tab { Recommended, Mine, All, } struct Entry { title: TitleSummary, saved: bool, watched: bool, last: Option, added: Option, } #[derive(Debug, Clone, PartialEq)] struct Filters { sort: &'static str, genre: Option, yf: Option, yt: Option, rf: Option, rt: Option, } impl Filters { fn filtered(&self) -> bool { self.genre.is_some() || self.yf.is_some() || self.yt.is_some() || self.rf.is_some() || self.rt.is_some() } fn custom(&self) -> usize { (self.yf.is_some() || self.yt.is_some()) as usize + (self.rf.is_some() || self.rt.is_some()) as usize } } #[derive(Default)] struct Catalog { items: Vec, page: u32, cursor: Option, has_more: bool, loading: bool, /// Pages loaded; empty ones since `resume_from` count towards the stop. pages: Vec, resume_from: usize, error: Option, generation: u64, } pub struct Source { kind: MediaType, tab: Tab, started: bool, genres: Load>, continuing: Vec, library: Load>, states: HashMap, rails: Vec<(String, String, String, Load>)>, rails_started: bool, // Könyvtáram show: &'static str, lib_sort: &'static str, // Böngészés f: Filters, open: bool, cat: Catalog, } fn this_year() -> i32 { crate::format::today()[0..4].parse().unwrap_or(2026) } impl Source { pub fn new(kind: MediaType) -> Source { Source { kind, tab: Tab::Recommended, started: false, genres: Load::Loading, continuing: Vec::new(), library: Load::Loading, states: HashMap::new(), rails: Vec::new(), rails_started: false, show: "all", lib_sort: "recent", f: Filters { sort: "popularity", genre: None, yf: None, yt: None, rf: None, rt: None }, open: false, cat: Catalog::default(), } } fn copy(&self) -> (&'static str, &'static str, &'static str, &'static str, &'static str, &'static str) { match self.kind { MediaType::Movie => ("Filmek", "Népszerű most", "A legjobbra értékelt filmek", "Idei bemutatók", "Még egy filmet sem mentettél", "Egy film oldalán a + gombbal mentheted el, és itt vár rád, amikor ráérsz."), MediaType::Tv => ("Sorozatok", "Népszerű sorozatok most", "A legjobbra értékelt sorozatok", "Idén indult", "Még egy sorozatot sem mentettél", "Egy sorozat oldalán a + gombbal mentheted el. Amit elkezdesz, magától is ide kerül."), } } fn start(&mut self, cx: &Cx) { let (api, kind) = (cx.api(), self.kind); cx.spawn::( move || { let genres = api.genres(kind); let cont = api.continue_watching().unwrap_or_default(); let mine = api.my_list(); let history = api.history().unwrap_or_default(); let states = api.list_status().unwrap_or_default(); (genres, cont, mine, history, states) }, move |s, cx, (genres, cont, mine, history, states)| { s.genres = Load::from(genres, cx); s.continuing = cont.into_iter().filter(|c| c.title.kind == s.kind).collect(); s.states = states; s.library = match mine { Ok(mine) => Load::Ready(library(s.kind, mine, history)), Err(e) => Load::Failed(crate::api::describe(&e)), }; s.start_rails(cx); }, ); } fn start_rails(&mut self, cx: &Cx) { if self.rails_started { return; } let Some(genres) = self.genres.ready().cloned() else { return }; self.rails_started = true; let (_, popular, rating, fresh, _, _) = self.copy(); let year = this_year(); let mut defs: Vec<(String, String, &'static str, Option, Option)> = vec![ ("popularity".into(), popular.into(), "popularity", None, None), ("rating".into(), rating.into(), "rating", None, None), ("new".into(), fresh.into(), "new", None, Some(year)), ]; for g in genres.iter().take(5) { defs.push((format!("g:{}", g.id), g.name.clone(), "popularity", Some(g.id.clone()), None)); } for (id, title, sort, genre, yr) in defs { self.rails.push((id.clone(), title, genre.clone().unwrap_or_default(), Load::Loading)); let (api, kind) = (cx.api(), self.kind); cx.spawn::( move || api.browse(kind, sort, genre.as_deref(), yr, (None, None), (None, None), 1, None), move |s, cx, r| { if let Some(rail) = s.rails.iter_mut().find(|x| x.0 == id) { rail.3 = Load::from(r.map(|p| p.items), cx); } }, ); } } fn reload_catalog(&mut self, cx: &Cx) { self.cat = Catalog { generation: self.cat.generation + 1, has_more: true, ..Catalog::default() }; self.next_page(cx); } fn next_page(&mut self, cx: &Cx) { if self.cat.loading || !self.cat.has_more || self.paused() { return; } self.cat.loading = true; let (api, kind, f, page, cursor, generation) = (cx.api(), self.kind, self.f.clone(), self.cat.page + 1, self.cat.cursor.clone(), self.cat.generation); cx.spawn::( move || api.browse(kind, f.sort, f.genre.as_deref(), None, (f.yf, f.yt), (f.rf, f.rt), page, cursor.as_deref()), move |s, _cx, r| { if s.cat.generation != generation { return; } s.cat.loading = false; match r { Ok(p) => { let seen: HashSet = s.cat.items.iter().map(|t| t.id.clone()).collect(); let new: Vec = p.items.into_iter().filter(|t| !seen.contains(&t.id)).collect(); s.cat.pages.push(new.len()); s.cat.items.extend(new); s.cat.page = page; s.cat.cursor = p.cursor; s.cat.has_more = p.has_more; s.cat.error = None; } Err(e) => s.cat.error = Some(crate::api::describe(&e)), } }, ); } fn paused(&self) -> bool { let streak = self.cat.pages[self.cat.resume_from.min(self.cat.pages.len())..].iter().rev().take_while(|n| **n == 0).count(); streak >= MAX_EMPTY_STREAK } fn find(&self, key: &str) -> Option { let (kind, id) = screens::parse_title_key(key).or_else(|| screens::parse_continue(key).map(|(k, i, _)| (k, i)))?; let lib = self.library.ready().into_iter().flatten().map(|e| &e.title); let rails = self.rails.iter().filter_map(|r| r.3.ready()).flatten(); self.cat.items.iter().chain(lib).chain(rails).chain(self.continuing.iter().map(|c| &c.title)).find(|t| t.kind == kind && t.id == id).cloned() } fn cards(&self, cx: &Cx, items: &[TitleSummary]) -> Vec { let api = cx.api(); items.iter().map(|t| title_card(&api, t, self.states.get(&format!("{}:{}", t.kind.key(), t.id)))).collect() } fn pick_year(&mut self, cx: &Cx, which: &'static str) { let current = if which == "yf" { self.f.yf } else { self.f.yt }; let empty = if which == "yf" { "Kezdettől" } else { "Máig" }; let mut items = vec![(empty.to_string(), String::new(), current.is_none())]; let years: Vec = (1920..=this_year()).rev().collect(); items.extend(years.iter().map(|y| (y.to_string(), String::new(), current == Some(*y)))); cx.select::(if which == "yf" { "Megjelenés ettől" } else { "Megjelenés eddig" }, items, move |s, cx, i| { let v = if i == 0 { None } else { years.get(i - 1).copied() }; if which == "yf" { s.f.yf = v; if let (Some(a), Some(b)) = (s.f.yf, s.f.yt) { if a > b { s.f.yt = Some(a); } } } else { s.f.yt = v; if let (Some(a), Some(b)) = (s.f.yf, s.f.yt) { if a > b { s.f.yf = Some(b); } } } s.reload_catalog(cx); }); } fn pick_rating(&mut self, cx: &Cx, which: &'static str) { let current = if which == "rf" { self.f.rf } else { self.f.rt }; let list: Vec = (0..17).map(|i| 9.5 - i as f64 * 0.5).collect(); let fmt = |v: f64| format!("{v:.1}").replace('.', ","); let mut items = vec![(if which == "rf" { "Bármennyi" } else { "10-ig" }.to_string(), String::new(), current.is_none())]; items.extend(list.iter().map(|r| (format!("{}{}", fmt(*r), if which == "rf" { "-tól" } else { "-ig" }), String::new(), current == Some(*r)))); cx.select::(if which == "rf" { "IMDb értékelés legalább" } else { "IMDb értékelés legfeljebb" }, items, move |s, cx, i| { let v = if i == 0 { None } else { list.get(i - 1).copied() }; if which == "rf" { s.f.rf = v; if let (Some(a), Some(b)) = (s.f.rf, s.f.rt) { if a > b { s.f.rt = Some(a); } } } else { s.f.rt = v; if let (Some(a), Some(b)) = (s.f.rf, s.f.rt) { if a > b { s.f.rf = Some(b); } } } s.reload_catalog(cx); }); } } fn library(kind: MediaType, mine: Vec, history: Vec) -> Vec { let mut out: Vec = Vec::new(); for it in mine.into_iter().filter(|i| i.title.kind == kind) { out.push(Entry { title: it.title, saved: true, watched: false, last: None, added: it.added_at }); } for it in history.into_iter().filter(|i| i.title.kind == kind) { match out.iter_mut().find(|e| e.title.id == it.title.id) { Some(e) => { e.watched = true; e.last = it.last_watched_at; } None => out.push(Entry { title: it.title, saved: false, watched: true, last: it.last_watched_at, added: None }), } } out } fn ts(iso: &Option) -> i64 { iso.as_deref().and_then(crate::format::parse_iso).unwrap_or(0) } impl Screen for Source { fn spec(&mut self, cx: &Cx) -> Spec { if !self.started { self.started = true; self.start(cx); } let (title, _, _, _, empty_mine, empty_hint) = self.copy(); let lib_n = self.library.ready().map(|l| l.len()).unwrap_or(0); let mut lines = vec![ L::page_title("title", title, ""), L::chips( "tabs", "", vec![ Ch::new("rec", "Ajánlott").active(self.tab == Tab::Recommended), Ch::new("mine", format!("Könyvtáram ({lib_n})")).active(self.tab == Tab::Mine), Ch::new("all", "Böngészés").active(self.tab == Tab::All), ], ), ]; let api = cx.api(); match self.tab { Tab::Recommended => { if !self.continuing.is_empty() { lines.push(L::cards("continue", "Folytasd, ahol abbahagytad", "landscape", self.continuing.iter().map(|c| continue_card(&api, c)).collect()).captions()); } if let Some(lib) = self.library.ready() { let saved: Vec = lib.iter().filter(|e| e.saved).take(30).map(|e| e.title.clone()).collect(); if !saved.is_empty() { let n = lib.iter().filter(|e| e.saved).count(); lines.push(L::cards("saved", "A könyvtáradból", "poster", self.cards(cx, &saved)).sub(format!("{n} mentett cím"))); } } if let Some(st) = self.genres.status("status") { lines.push(st); } for (id, title, _, rail) in &self.rails { match rail { Load::Ready(items) if !items.is_empty() => lines.push(L::cards(format!("rail:{id}"), title.clone(), "poster", self.cards(cx, items))), Load::Loading => lines.push(L::cards(format!("rail:{id}"), title.clone(), "poster", Vec::new())), _ => {} } } if self.genres.ready().is_some_and(|g| g.len() > 5) { lines.push(L::chips("browse-all", "", vec![Ch::new("all", "Minden műfaj böngészése").icon("list")])); } } Tab::Mine => { let filters = [("all", "Minden"), ("saved", "Mentett"), ("watched", "Nézett"), ("unwatched", "Nem nézett")]; lines.push(L::chips("show", "", filters.iter().map(|(id, l)| Ch::new(*id, *l).active(self.show == *id)).collect())); let sorts = [("recent", "Legutóbbi"), ("oldest", "Legrégebben nézett"), ("title", "Cím"), ("year", "Megjelenés")]; lines.push(L::chips("sort", "RENDEZÉS", sorts.iter().map(|(id, l)| Ch::new(*id, *l).active(self.lib_sort == *id)).collect())); match &self.library { Load::Ready(lib) if lib.is_empty() => lines.push(L::notice("empty", "info", empty_mine, empty_hint)), Load::Ready(lib) => { let mut shown: Vec<&Entry> = lib .iter() .filter(|e| match self.show { "saved" => e.saved, "watched" => e.watched, "unwatched" => !e.watched, _ => true, }) .collect(); match self.lib_sort { "title" => shown.sort_by(|a, b| a.title.title.to_lowercase().cmp(&b.title.title.to_lowercase())), "year" => shown.sort_by_key(|e| std::cmp::Reverse(e.title.year.unwrap_or(0))), "oldest" => shown.sort_by_key(|e| if e.last.is_some() { ts(&e.last) } else { i64::MAX }), _ => shown.sort_by_key(|e| std::cmp::Reverse(ts(&e.added).max(ts(&e.last)))), } if shown.is_empty() { lines.push(L::notice("empty", "info", "Ehhez a szűréshez nincs cím", "Válts a „Minden” nézetre.")); } else { let items: Vec = shown.iter().map(|e| e.title.clone()).collect(); lines.extend(grid_lines("lib", "", "poster", self.cards(cx, &items), GRID)); } } other => lines.extend(other.status("status")), } } Tab::All => { let sorts = [("popularity", "Népszerű"), ("rating", "Legjobbra értékelt"), ("new", "Legújabb")]; let mut chips: Vec = sorts.iter().map(|(id, l)| Ch::new(format!("sort:{id}"), *l).active(self.f.sort == *id)).collect(); let custom = self.f.custom(); chips.push(Ch::new("filters", if custom > 0 { format!("Szűrők ({custom})") } else { "Szűrők".into() }).icon("settings").active(self.open || custom > 0)); if self.f.filtered() { chips.push(Ch::new("reset", "Törlés").icon("close")); } lines.push(L::chips("cat-sort", "", chips)); if self.open { let year = |v: Option, empty: &str| v.map(|y| y.to_string()).unwrap_or_else(|| empty.to_string()); let mut yc = vec![ Ch::new("yf", format!("Ettől: {}", year(self.f.yf, "kezdettől"))).active(self.f.yf.is_some()), Ch::new("yt", format!("Eddig: {}", year(self.f.yt, "máig"))).active(self.f.yt.is_some()), ]; yc.extend(DECADES.iter().enumerate().map(|(i, (l, a, b))| Ch::new(format!("dec:{i}"), *l).active(self.f.yf == *a && self.f.yt == *b))); lines.push(L::chips("cat-year", "MEGJELENÉS", yc)); let r = |v: Option, suffix: &str, empty: &str| v.map(|v| format!("{}{suffix}", format!("{v:.1}").replace('.', ","))).unwrap_or_else(|| empty.to_string()); let mut rc = vec![ Ch::new("rf", format!("★ {}", r(self.f.rf, "-tól", "Bármennyi"))).active(self.f.rf.is_some()), Ch::new("rt", r(self.f.rt, "-ig", "10-ig")).active(self.f.rt.is_some()), ]; rc.extend([6.0, 7.0, 8.0].iter().map(|v| Ch::new(format!("rp:{v}"), format!("{v}+")).active(self.f.rf == Some(*v) && self.f.rt.is_none()))); lines.push(L::chips("cat-rating", "IMDB", rc)); } let mut gc = vec![Ch::new("g:", "Minden műfaj").active(self.f.genre.is_none())]; if let Some(gs) = self.genres.ready() { gc.extend(gs.iter().map(|g| Ch::new(format!("g:{}", g.id), g.name.clone()).active(self.f.genre.as_deref() == Some(g.id.as_str())))); } lines.push(L::chips("cat-genre", "MŰFAJ", gc)); if self.cat.items.is_empty() { if let Some(e) = &self.cat.error { lines.push(L::notice("cat-error", "bad", "Nem sikerült betölteni", e.clone())); lines.push(L::chips("cat-retry", "", vec![Ch::new("retry", "Újrapróbálom").icon("refresh")])); } else if self.cat.loading || self.cat.has_more { lines.push(L::text("cat-loading", "Betöltés…", "caption")); } else { lines.push(L::notice("cat-empty", "info", "Ehhez a szűréshez nincs találat", "Tágítsd az év- vagy az értékelés-tartományt, vagy válassz másik műfajt.")); if self.f.filtered() { lines.push(L::chips("cat-reset", "", vec![Ch::new("reset", "Szűrők törlése").icon("close")])); } } } else { lines.extend(grid_lines("cat", "", "poster", self.cards(cx, &self.cat.items.clone()), GRID)); if self.cat.error.is_some() { lines.push(L::chips("cat-retry", "", vec![Ch::new("retry", "Újrapróbálom").icon("refresh")])); } else if self.paused() && self.cat.has_more && !self.cat.loading { lines.push(L::text("cat-deep", "Szűk szűrés: a katalógus mélyén már ritka a találat.", "caption")); lines.push(L::chips("cat-more", "", vec![Ch::new("more", "Keresés tovább")])); } else if self.cat.loading { lines.push(L::text("cat-loading", "Betöltés…", "caption")); } else if !self.cat.has_more { lines.push(L::text("cat-end", format!("A lista végére értél · {} cím", self.cat.items.len()), "caption")); } } } } Spec { lines, frame: Frame { nav: Some(if self.kind == MediaType::Movie { 1 } else { 2 }), ..Frame::default() } } } fn activate(&mut self, cx: &Cx, line: &str, item: &str) { match (line, item) { ("tabs", t) | ("browse-all", t) => { self.tab = match t { "mine" => Tab::Mine, "all" => Tab::All, _ => Tab::Recommended, }; if self.tab == Tab::All && self.cat.pages.is_empty() && !self.cat.loading { self.reload_catalog(cx); } if line == "browse-all" { cx.focus_on("tabs", 2); } } ("show", v) => { self.show = match v { "saved" => "saved", "watched" => "watched", "unwatched" => "unwatched", _ => "all", } } ("sort", v) => { self.lib_sort = match v { "oldest" => "oldest", "title" => "title", "year" => "year", _ => "recent", } } ("cat-sort", "filters") => self.open = !self.open, ("cat-sort", "reset") | ("cat-reset", _) => { self.f = Filters { sort: self.f.sort, genre: None, yf: None, yt: None, rf: None, rt: None }; self.reload_catalog(cx); } ("cat-sort", s) => { self.f.sort = match s.trim_start_matches("sort:") { "rating" => "rating", "new" => "new", _ => "popularity", }; self.reload_catalog(cx); } ("cat-year", "yf") => self.pick_year(cx, "yf"), ("cat-year", "yt") => self.pick_year(cx, "yt"), ("cat-year", d) => { if let Some((_, a, b)) = d.strip_prefix("dec:").and_then(|i| i.parse::().ok()).and_then(|i| DECADES.get(i)) { let on = self.f.yf == *a && self.f.yt == *b; (self.f.yf, self.f.yt) = if on { (None, None) } else { (*a, *b) }; self.reload_catalog(cx); } } ("cat-rating", "rf") => self.pick_rating(cx, "rf"), ("cat-rating", "rt") => self.pick_rating(cx, "rt"), ("cat-rating", p) => { if let Some(v) = p.strip_prefix("rp:").and_then(|v| v.parse::().ok()) { let on = self.f.rf == Some(v) && self.f.rt.is_none(); (self.f.rf, self.f.rt) = if on { (None, None) } else { (Some(v), None) }; self.reload_catalog(cx); } } ("cat-genre", g) => { let g = g.trim_start_matches("g:"); self.f.genre = if g.is_empty() || self.f.genre.as_deref() == Some(g) { None } else { Some(g.to_string()) }; self.reload_catalog(cx); } ("cat-retry", _) => { self.cat.error = None; self.next_page(cx); } ("cat-more", _) => { self.cat.resume_from = self.cat.pages.len(); self.next_page(cx); } (_, key) => { let found = self.find(key); screens::open_card(cx, key, |_| found.clone()); } } } fn focus(&mut self, cx: &Cx, _line: &str, item: &str) { match self.find(item) { Some(t) => { let url = cx.api().image(t.backdrop.as_deref(), false); cx.backdrop(&url, Look::Soft, item); } None => cx.backdrop("", Look::Soft, ""), } } fn more(&mut self, cx: &Cx, list: &str) { if list == "cat" { self.next_page(cx); } } fn shown(&mut self, cx: &Cx) { // Progress and lists may have changed on a details page. let (api, kind) = (cx.api(), self.kind); cx.spawn::( move || (api.continue_watching().unwrap_or_default(), api.my_list(), api.history().unwrap_or_default(), api.list_status().unwrap_or_default()), move |s, _cx, (cont, mine, history, states)| { s.continuing = cont.into_iter().filter(|c| c.title.kind == kind).collect(); if let Ok(mine) = mine { s.library = Load::Ready(library(kind, mine, history)); } s.states = states; }, ); } fn as_any(&mut self) -> &mut dyn Any { self } }