Initial Netflex TV app
This commit is contained in:
608
src/screens/detail.rs
Normal file
608
src/screens/detail.rs
Normal file
@@ -0,0 +1,608 @@
|
||||
//! A movie's or series' page (the web app's pages/Detail.tsx): hero with
|
||||
//! Play / Continue / Next, My List, watched, versions; seasons as poster
|
||||
//! cards, episodes as rows; nCore versions with their badges; cast.
|
||||
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::api::{EpisodeInfo, MediaType, ProgressRow, ReleaseLanguages, SeasonDetail, SourceCandidate, SourcesResult, TitleDetail, TitleState, TitleSummary};
|
||||
use crate::app::{Cx, Look, Screen};
|
||||
use crate::page::{C, Ch, Frame, Kind, L, Spec};
|
||||
use crate::screens::Load;
|
||||
use crate::screens::home::meta_line;
|
||||
use crate::{format, player};
|
||||
|
||||
/// NFO languages load by themselves for the top rows only (one nCore page each).
|
||||
const AUTO_LANGS: usize = 5;
|
||||
|
||||
type Ep = (i32, i32);
|
||||
|
||||
pub struct Detail {
|
||||
kind: MediaType,
|
||||
id: String,
|
||||
summary: Option<TitleSummary>,
|
||||
data: Load<TitleDetail>,
|
||||
progress: Vec<ProgressRow>,
|
||||
state: TitleState,
|
||||
season: Option<i32>,
|
||||
seasons: HashMap<i32, Load<SeasonDetail>>,
|
||||
/// Versions open: the movie (None) or an episode.
|
||||
open: Option<Option<Ep>>,
|
||||
sources: HashMap<String, Load<SourcesResult>>,
|
||||
langs: HashMap<i64, Load<ReleaseLanguages>>,
|
||||
all_langs: bool,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
fn source_key(ep: Option<Ep>) -> String {
|
||||
ep.map(|(s, e)| format!("{s}:{e}")).unwrap_or_else(|| "movie".into())
|
||||
}
|
||||
|
||||
impl Detail {
|
||||
pub fn new(kind: MediaType, id: &str, summary: Option<TitleSummary>) -> Detail {
|
||||
Detail {
|
||||
kind,
|
||||
id: id.to_string(),
|
||||
summary,
|
||||
data: Load::Loading,
|
||||
progress: Vec::new(),
|
||||
state: TitleState::default(),
|
||||
season: None,
|
||||
seasons: HashMap::new(),
|
||||
open: None,
|
||||
sources: HashMap::new(),
|
||||
langs: HashMap::new(),
|
||||
all_langs: false,
|
||||
started: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn load(&mut self, cx: &Cx) {
|
||||
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
|
||||
cx.spawn::<Detail, _>(
|
||||
move || {
|
||||
let d = api.title(kind, &id);
|
||||
let p = api.progress(kind, &id).unwrap_or_default();
|
||||
let st = api.list_status().ok().and_then(|m| m.get(&format!("{}:{}", kind.key(), id)).cloned()).unwrap_or_default();
|
||||
let hu = api.hungarian(&[(kind, id.clone())]).ok().and_then(|m| m.into_values().next()).flatten();
|
||||
(d, p, st, hu)
|
||||
},
|
||||
|s, cx, (d, p, st, hu)| {
|
||||
s.data = Load::from(d, cx);
|
||||
s.progress = p;
|
||||
s.state = st;
|
||||
if let Some(d) = s.data.ready_mut() {
|
||||
if d.summary.hu.is_none() {
|
||||
d.summary.hu = hu;
|
||||
}
|
||||
}
|
||||
if s.kind == MediaType::Tv && s.season.is_none() {
|
||||
if let Some(d) = s.data.ready() {
|
||||
let n = current_season(d, &s.progress);
|
||||
s.season = Some(n);
|
||||
s.load_season(cx, n);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn load_season(&mut self, cx: &Cx, n: i32) {
|
||||
if self.seasons.contains_key(&n) {
|
||||
return;
|
||||
}
|
||||
self.seasons.insert(n, Load::Loading);
|
||||
let (api, id) = (cx.api(), self.id.clone());
|
||||
cx.spawn::<Detail, _>(move || api.season(&id, n), move |s, cx, r| {
|
||||
s.seasons.insert(n, Load::from(r, cx));
|
||||
});
|
||||
}
|
||||
|
||||
fn reload_progress(&mut self, cx: &Cx) {
|
||||
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
|
||||
cx.spawn::<Detail, _>(
|
||||
move || (api.progress(kind, &id).unwrap_or_default(), api.list_status().ok().and_then(|m| m.get(&format!("{}:{}", kind.key(), id)).cloned())),
|
||||
|s, _cx, (p, st)| {
|
||||
s.progress = p;
|
||||
if let Some(st) = st {
|
||||
s.state = st;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn load_sources(&mut self, cx: &Cx, ep: Option<Ep>) {
|
||||
let key = source_key(ep);
|
||||
if self.sources.contains_key(&key) {
|
||||
self.load_langs(cx, &key);
|
||||
return;
|
||||
}
|
||||
self.sources.insert(key.clone(), Load::Loading);
|
||||
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
|
||||
cx.spawn::<Detail, _>(move || api.sources(kind, &id, ep), move |s, cx, r| {
|
||||
s.sources.insert(key.clone(), Load::from(r, cx));
|
||||
s.load_langs(cx, &key);
|
||||
});
|
||||
}
|
||||
|
||||
fn load_langs(&mut self, cx: &Cx, key: &str) {
|
||||
let Some(list) = self.sources.get(key).and_then(|l| l.ready()) else { return };
|
||||
let n = if self.all_langs { list.candidates.len() } else { AUTO_LANGS };
|
||||
let ids: Vec<i64> = list.candidates.iter().take(n).map(|c| c.torrent.id).filter(|id| !self.langs.contains_key(id)).collect();
|
||||
for nid in ids {
|
||||
self.langs.insert(nid, Load::Loading);
|
||||
let api = cx.api();
|
||||
cx.spawn::<Detail, _>(move || api.release_languages(nid), move |s, cx, r| {
|
||||
s.langs.insert(nid, Load::from(r, cx));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
self.data.ready().map(|d| d.summary.title.clone()).or_else(|| self.summary.as_ref().map(|s| s.title.clone())).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn backdrop(&self) -> Option<String> {
|
||||
self.data.ready().and_then(|d| d.summary.backdrop.clone()).or_else(|| self.summary.as_ref().and_then(|s| s.backdrop.clone()))
|
||||
}
|
||||
|
||||
fn play(&self, cx: &Cx, ep: Option<Ep>, ncore: Option<i64>) {
|
||||
let mut r = player::Request::title(self.kind, &self.id, self.title(), ep, self.backdrop());
|
||||
r.pinned = ncore;
|
||||
cx.play(r);
|
||||
}
|
||||
|
||||
fn source_lines(&self, cx: &Cx, ep: Option<Ep>, out: &mut Vec<L>) {
|
||||
let key = source_key(ep);
|
||||
let id = |s: &str| format!("src:{key}:{s}");
|
||||
match self.sources.get(&key) {
|
||||
None | Some(Load::Loading) => out.push(L::text(id("loading"), "Verziók keresése az nCore-on…", "caption")),
|
||||
Some(Load::Failed(e)) => out.push(L::text(id("error"), e.clone(), "bad")),
|
||||
Some(Load::Ready(r)) if r.candidates.is_empty() => out.push(L::text(
|
||||
id("none"),
|
||||
format!("Ehhez most nincs verzió az nCore-on{}.", if r.searched_by.as_deref() == Some("name") { " (IMDb azonosító nélkül, név alapján kerestünk)" } else { "" }),
|
||||
"label",
|
||||
)),
|
||||
Some(Load::Ready(r)) => {
|
||||
for (i, c) in r.candidates.iter().enumerate() {
|
||||
out.push(self.source_item(&key, i, c));
|
||||
}
|
||||
let rest = r.candidates.len().saturating_sub(AUTO_LANGS);
|
||||
if rest > 0 && !self.all_langs {
|
||||
out.push(L::chips(format!("srclangs:{key}"), "", vec![Ch::new("langs", "Hangsávok a többi verziónál is").icon("audio")]));
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = cx;
|
||||
}
|
||||
|
||||
fn source_item(&self, key: &str, i: usize, c: &SourceCandidate) -> L {
|
||||
let mut badges: Vec<String> = Vec::new();
|
||||
if i == 0 {
|
||||
badges.push("Ajánlott".into());
|
||||
}
|
||||
if let Some(local) = &c.local {
|
||||
badges.push(
|
||||
match local.as_str() {
|
||||
"seeding" => "A szerveren, seedel",
|
||||
"eligible" => "A szerveren",
|
||||
"downloading" => "Letöltés alatt",
|
||||
_ => "A szerveren",
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
let nfo = self.langs.get(&c.torrent.id).and_then(|l| l.ready());
|
||||
let subs: Vec<String> = nfo.map(|n| n.subs.clone()).unwrap_or_default();
|
||||
if c.parsed.hungarian_audio {
|
||||
badges.push("Magyar szinkron".into());
|
||||
}
|
||||
if c.parsed.hungarian_subs && !subs.iter().any(|s| s == "hu") {
|
||||
badges.push("Magyar felirat".into());
|
||||
}
|
||||
if let Some(n) = nfo {
|
||||
if !n.audio.is_empty() {
|
||||
badges.push(format!("Hang: {}", n.audio.iter().map(|l| format::language(Some(l)).to_lowercase()).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
if !subs.is_empty() {
|
||||
badges.push(format!("Felirat: {}", subs.iter().map(|l| format::language(Some(l)).to_lowercase()).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
if n.found && n.audio.is_empty() && subs.is_empty() {
|
||||
badges.push("nyelv ismeretlen".into());
|
||||
}
|
||||
} else if matches!(self.langs.get(&c.torrent.id), Some(Load::Loading)) {
|
||||
badges.push("NFO…".into());
|
||||
}
|
||||
if let Some(r) = c.parsed.resolution {
|
||||
badges.push(format!("{}{}", if r >= 2160 { "4K".to_string() } else { format!("{r}p") }, if c.parsed.hdr { " HDR" } else { "" }));
|
||||
}
|
||||
badges.push(format!("{} seeder", c.torrent.seeders));
|
||||
if c.torrent.freeleech {
|
||||
badges.push("Freeleech".into());
|
||||
}
|
||||
let mut text = vec![crate::api::format_bytes(c.torrent.size)];
|
||||
if c.pack {
|
||||
text.push("évadcsomag".into());
|
||||
}
|
||||
if let Some(d) = &c.torrent.uploaded_at {
|
||||
text.push(format::date(Some(d)));
|
||||
}
|
||||
let mut l = L::item(
|
||||
format!("src:{key}:{}", c.torrent.id),
|
||||
c.torrent.name.clone(),
|
||||
badges.join(" · "),
|
||||
text.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · "),
|
||||
vec![Ch::new("play", if i == 0 { "Lejátszás ezzel (ajánlott)" } else { "Lejátszás ezzel" }).icon("play")],
|
||||
);
|
||||
l.indent = 40.0;
|
||||
l
|
||||
}
|
||||
|
||||
fn episode_item(&self, d: &TitleDetail, e: &EpisodeInfo, cx: &Cx) -> L {
|
||||
let today = format::today();
|
||||
let aired = e.air_date.as_deref().is_none_or(|a| a <= today.as_str());
|
||||
let p = self.progress.iter().find(|p| p.season == e.season && p.episode == e.episode);
|
||||
let done = p.is_some_and(|p| p.completed);
|
||||
let mut meta = vec![format!("{}. rész", e.episode)];
|
||||
let rt = format::runtime(e.runtime);
|
||||
if !rt.is_empty() {
|
||||
meta.push(rt);
|
||||
}
|
||||
if !aired {
|
||||
meta.push(format!("érkezik: {}", format::date(e.air_date.as_deref())));
|
||||
} else if let Some(a) = &e.air_date {
|
||||
meta.push(format::date(Some(a)));
|
||||
}
|
||||
if done {
|
||||
meta.push("megnézted".into());
|
||||
}
|
||||
let open = self.open == Some(Some((e.season, e.episode)));
|
||||
let chips = if aired {
|
||||
vec![
|
||||
Ch::new("play", "Lejátszás").icon("play"),
|
||||
Ch::new("versions", "Verziók").icon("list").active(open),
|
||||
Ch::new("watched", if done { "Megnézve" } else { "Megnéztem" }).icon("check").active(done),
|
||||
]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut l = L::item(
|
||||
format!("ep:{}:{}", e.season, e.episode),
|
||||
e.name.clone().unwrap_or_else(|| format!("{}. rész", e.episode)),
|
||||
meta.join(" · "),
|
||||
e.overview.clone().unwrap_or_default(),
|
||||
chips,
|
||||
);
|
||||
let still = cx.api().image(e.still.as_deref().or(d.summary.backdrop.as_deref()), false);
|
||||
l = l.image(still);
|
||||
l.progress = match p {
|
||||
Some(p) if p.completed => 1.0,
|
||||
Some(p) => p.duration.filter(|x| *x > 0.0).map(|x| (p.position / x).min(1.0) as f32).unwrap_or(-1.0),
|
||||
None => -1.0,
|
||||
};
|
||||
if !aired {
|
||||
l.tone = "dim".into();
|
||||
}
|
||||
l
|
||||
}
|
||||
}
|
||||
|
||||
/// Where Play goes, and its label (web: resumeTarget).
|
||||
fn target(d: &TitleDetail, progress: &[ProgressRow]) -> (Option<Ep>, String) {
|
||||
if d.summary.kind == MediaType::Movie {
|
||||
let p = progress.iter().find(|r| r.season == 0 && r.episode == 0);
|
||||
return (None, if p.is_some_and(|p| !p.completed && p.position > 60.0) { "Folytatás".into() } else { "Lejátszás".into() });
|
||||
}
|
||||
let latest = progress.iter().filter(|r| r.season > 0).max_by_key(|r| (r.season, r.episode));
|
||||
let Some(latest) = latest else {
|
||||
return (Some((d.seasons.first().map(|s| s.number).unwrap_or(1), 1)), "Lejátszás".into());
|
||||
};
|
||||
if !latest.completed {
|
||||
return (Some((latest.season, latest.episode)), format!("Folytatás · {}", format::episode_code(latest.season, latest.episode)));
|
||||
}
|
||||
let season = d.seasons.iter().find(|s| s.number == latest.season);
|
||||
let next = if season.is_some_and(|s| latest.episode < s.episode_count) {
|
||||
Some((latest.season, latest.episode + 1))
|
||||
} else if d.seasons.iter().any(|s| s.number == latest.season + 1) {
|
||||
Some((latest.season + 1, 1))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match next {
|
||||
Some((s, e)) => (Some((s, e)), format!("Következő · {}", format::episode_code(s, e))),
|
||||
None => (Some((latest.season, latest.episode)), "Újra".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The season you are in (web: currentSeason).
|
||||
fn current_season(d: &TitleDetail, progress: &[ProgressRow]) -> i32 {
|
||||
let first = d.seasons.first().map(|s| s.number).unwrap_or(1);
|
||||
let last = progress.iter().filter(|r| r.season > 0).map(|r| r.season).max().unwrap_or(0);
|
||||
if last == 0 {
|
||||
return first;
|
||||
}
|
||||
let Some(s) = d.seasons.iter().find(|x| x.number == last) else { return last };
|
||||
let watched = progress.iter().filter(|r| r.season == last && r.completed).count() as i32;
|
||||
if watched < s.aired() {
|
||||
return last;
|
||||
}
|
||||
d.seasons.iter().find(|x| x.number > last && x.aired() > 0).map(|x| x.number).unwrap_or(last)
|
||||
}
|
||||
|
||||
impl Screen for Detail {
|
||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
||||
if !self.started {
|
||||
self.started = true;
|
||||
self.load(cx);
|
||||
}
|
||||
let api = cx.api();
|
||||
let mut lines = Vec::new();
|
||||
let d = self.data.ready().cloned();
|
||||
let summary = d.as_ref().map(|d| d.summary.clone()).or_else(|| self.summary.clone());
|
||||
|
||||
// ---- hero ----
|
||||
let mut hero = L::new("hero", Kind::Hero);
|
||||
if let Some(t) = &summary {
|
||||
hero.title = t.title.clone();
|
||||
hero.logo = api.image(t.logo.as_deref(), true);
|
||||
hero.subtitle = t.original_title.clone().filter(|o| *o != t.title).unwrap_or_default();
|
||||
let extra = match &d {
|
||||
Some(d) if d.summary.kind == MediaType::Movie => format::runtime(d.runtime),
|
||||
Some(d) => d.number_of_seasons.filter(|n| *n > 0).map(|n| format!("{n} évad")).unwrap_or_default(),
|
||||
None => String::new(),
|
||||
};
|
||||
hero.meta = meta_line(t, &extra);
|
||||
let overview = t.overview.clone().unwrap_or_default();
|
||||
hero.text = match d.as_ref().and_then(|d| d.tagline.clone()) {
|
||||
Some(tag) if !tag.is_empty() => format!("{tag}\n{overview}"),
|
||||
_ => overview,
|
||||
};
|
||||
}
|
||||
if let Some(d) = &d {
|
||||
if let Some(n) = d.next_episode_to_air.as_ref().filter(|_| d.summary.kind == MediaType::Tv) {
|
||||
hero.extra = format!("Új rész érkezik: {} · {}", format::episode_code(n.season, n.episode), format::date_long(n.air_date.as_deref()));
|
||||
}
|
||||
let (_, label) = target(d, &self.progress);
|
||||
hero.chips.push(Ch::new("play", label).icon("play").tone("primary"));
|
||||
} else {
|
||||
hero.chips.push(Ch::new("play", "Lejátszás").icon("play").tone("primary").enabled(false));
|
||||
}
|
||||
hero.chips.push(Ch::new("list", if self.state.listed { "Listámon" } else { "Listám" }).icon(if self.state.listed { "check" } else { "plus" }).active(self.state.listed));
|
||||
if self.kind == MediaType::Movie {
|
||||
hero.chips.push(Ch::new("watched", if self.state.watched { "Megnézve" } else { "Megnéztem" }).icon("check").active(self.state.watched));
|
||||
hero.chips.push(Ch::new("versions", "Verziók").icon("list").active(self.open == Some(None)));
|
||||
if let Some(p) = self.progress.iter().find(|r| r.season == 0 && r.episode == 0 && !r.completed && r.position > 60.0) {
|
||||
if let Some(dur) = p.duration.filter(|d| *d > 0.0) {
|
||||
hero.progress = (p.position / dur).min(1.0) as f32;
|
||||
hero.note = format!("még {} perc", ((dur - p.position) / 60.0).round().max(1.0) as i64);
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.push(hero);
|
||||
if let Some(st) = self.data.status("status") {
|
||||
lines.push(st);
|
||||
}
|
||||
|
||||
// ---- movie: versions ----
|
||||
if self.kind == MediaType::Movie && self.open == Some(None) {
|
||||
lines.push(L::heading("versions-h", "Verziók az nCore-on").sub("A Lejátszás magától a legjobb verziót választja; itt kézzel is dönthetsz."));
|
||||
self.source_lines(cx, None, &mut lines);
|
||||
lines.push(L::chips("versions-close", "", vec![Ch::new("close", "Bezárás").icon("close")]));
|
||||
}
|
||||
|
||||
// ---- series: seasons and episodes ----
|
||||
if let (Some(d), MediaType::Tv) = (&d, self.kind) {
|
||||
if !d.seasons.is_empty() {
|
||||
let season = self.season.unwrap_or(1);
|
||||
lines.push(L::heading("eps-h", "Epizódok").sub(if d.seasons.len() > 1 { format!("{} évad", d.seasons.len()) } else { String::new() }));
|
||||
let cards: Vec<C> = d
|
||||
.seasons
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let watched = self.progress.iter().filter(|p| p.season == s.number && p.completed).count() as i32;
|
||||
let aired = s.aired();
|
||||
let complete = aired > 0 && watched >= aired;
|
||||
let poster = s.poster.as_deref().or(d.summary.poster.as_deref());
|
||||
let mut c = C::new(format!("season:{}", s.number), s.label(), api.image(poster, false));
|
||||
c.caption = s.label();
|
||||
c.detail = format!(
|
||||
"{}{}",
|
||||
if watched > 0 { format!("{} / {aired} rész", watched.min(aired)) } else { format!("{} rész", s.episode_count) },
|
||||
s.air_date.as_deref().filter(|a| a.len() >= 4).map(|a| format!(" · {}", &a[..4])).unwrap_or_default()
|
||||
);
|
||||
if s.poster.is_none() {
|
||||
c.big = s.number.to_string();
|
||||
}
|
||||
if complete {
|
||||
c.mark = "check";
|
||||
} else if watched > 0 && aired > 0 {
|
||||
c.progress = watched as f32 / aired as f32;
|
||||
}
|
||||
c.current = s.number == season;
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
let mut sl = L::cards("seasons", "", "season", cards).captions();
|
||||
sl.indent = 0.0;
|
||||
lines.push(sl);
|
||||
let current = d.seasons.iter().find(|s| s.number == season);
|
||||
match self.seasons.get(&season) {
|
||||
None | Some(Load::Loading) => lines.push(L::text("eps-loading", "Epizódok betöltése…", "caption")),
|
||||
Some(Load::Failed(e)) => lines.push(L::notice("eps-error", "bad", "Az epizódok nem töltődtek be", e.clone())),
|
||||
Some(Load::Ready(sd)) => {
|
||||
let today = format::today();
|
||||
let aired: Vec<&EpisodeInfo> = sd.episodes.iter().filter(|e| e.air_date.as_deref().is_none_or(|a| a <= today.as_str())).collect();
|
||||
let done = aired.iter().filter(|e| self.progress.iter().any(|p| p.season == e.season && p.episode == e.episode && p.completed)).count();
|
||||
let all = !aired.is_empty() && done == aired.len();
|
||||
let mut h = L::heading("season-h", current.map(|s| s.label()).unwrap_or_else(|| format!("{season}. évad")));
|
||||
if !aired.is_empty() {
|
||||
h.subtitle = format!("{done} / {} rész megnézve", aired.len());
|
||||
}
|
||||
lines.push(h);
|
||||
if !aired.is_empty() {
|
||||
lines.push(L::chips(
|
||||
"season-watched",
|
||||
"",
|
||||
vec![Ch::new("all", if all { "Évad megnézettségének törlése" } else { "Egész évad megnézve" }).icon("check").active(all)],
|
||||
));
|
||||
}
|
||||
for e in &sd.episodes {
|
||||
lines.push(self.episode_item(d, e, cx));
|
||||
if self.open == Some(Some((e.season, e.episode))) {
|
||||
self.source_lines(cx, Some((e.season, e.episode)), &mut lines);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- cast ----
|
||||
if let Some(d) = &d {
|
||||
if !d.cast.is_empty() || !d.directors.is_empty() {
|
||||
lines.push(L::heading("cast-h", "Szereplők és alkotók"));
|
||||
if !d.directors.is_empty() {
|
||||
lines.push(L::text("directors", format!("{}: {}", if d.directors.len() > 1 { "Rendezők" } else { "Rendező" }, d.directors.join(", ")), "label"));
|
||||
}
|
||||
if !d.cast.is_empty() {
|
||||
lines.push(L::text("cast", format!("Szereplők: {}", d.cast.iter().take(14).cloned().collect::<Vec<_>>().join(", ")), "label"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Spec { lines, frame: Frame::default() }
|
||||
}
|
||||
|
||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
|
||||
match (line, item) {
|
||||
("hero", "play") => {
|
||||
if let Some(d) = self.data.ready() {
|
||||
let (ep, _) = target(d, &self.progress);
|
||||
self.play(cx, ep, None);
|
||||
}
|
||||
}
|
||||
("hero", "list") => {
|
||||
let on = !self.state.listed;
|
||||
self.state.listed = on;
|
||||
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
|
||||
cx.call::<Detail>("Listám", move || api.set_listed(kind, &id, on), |_, _| {});
|
||||
cx.toast(if on { "Mentve a könyvtáradba" } else { "Eltávolítva a könyvtáradból" });
|
||||
}
|
||||
("hero", "watched") => {
|
||||
let on = !self.state.watched;
|
||||
self.state.watched = on;
|
||||
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
|
||||
cx.call::<Detail>("Megnézve", move || api.mark_watched(kind, &id, &[(0, 0)], on), |s, cx| s.reload_progress(cx));
|
||||
}
|
||||
("hero", "versions") => {
|
||||
if self.open == Some(None) {
|
||||
self.open = None;
|
||||
} else {
|
||||
self.open = Some(None);
|
||||
self.load_sources(cx, None);
|
||||
cx.focus_on("versions-h", 0);
|
||||
}
|
||||
}
|
||||
("versions-close", _) => {
|
||||
self.open = None;
|
||||
cx.focus_on("hero", 3);
|
||||
}
|
||||
("seasons", s) => {
|
||||
if let Some(n) = s.strip_prefix("season:").and_then(|n| n.parse::<i32>().ok()) {
|
||||
self.season = Some(n);
|
||||
self.open = None;
|
||||
self.load_season(cx, n);
|
||||
}
|
||||
}
|
||||
("season-watched", _) => {
|
||||
let Some(season) = self.season else { return };
|
||||
let Some(sd) = self.seasons.get(&season).and_then(|l| l.ready()) else { return };
|
||||
let today = format::today();
|
||||
let eps: Vec<Ep> = sd.episodes.iter().filter(|e| e.air_date.as_deref().is_none_or(|a| a <= today.as_str())).map(|e| (e.season, e.episode)).collect();
|
||||
let all = eps.iter().all(|(s, e)| self.progress.iter().any(|p| p.season == *s && p.episode == *e && p.completed));
|
||||
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
|
||||
cx.call::<Detail>("Megnézve", move || api.mark_watched(kind, &id, &eps, !all), |s, cx| s.reload_progress(cx));
|
||||
}
|
||||
(l, act) if l.starts_with("ep:") => {
|
||||
let mut p = l[3..].split(':');
|
||||
let (Some(s), Some(e)) = (p.next().and_then(|v| v.parse().ok()), p.next().and_then(|v| v.parse().ok())) else { return };
|
||||
match act {
|
||||
"play" => self.play(cx, Some((s, e)), None),
|
||||
"versions" => {
|
||||
if self.open == Some(Some((s, e))) {
|
||||
self.open = None;
|
||||
} else {
|
||||
self.open = Some(Some((s, e)));
|
||||
self.load_sources(cx, Some((s, e)));
|
||||
}
|
||||
}
|
||||
"watched" => {
|
||||
let done = self.progress.iter().any(|p| p.season == s && p.episode == e && p.completed);
|
||||
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
|
||||
cx.call::<Detail>("Megnézve", move || api.mark_watched(kind, &id, &[(s, e)], !done), |s, cx| s.reload_progress(cx));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(l, "langs") if l.starts_with("srclangs:") => {
|
||||
self.all_langs = true;
|
||||
let key = l["srclangs:".len()..].to_string();
|
||||
self.load_langs(cx, &key);
|
||||
}
|
||||
(l, "play") if l.starts_with("src:") => {
|
||||
// src:<key>:<ncore id>, key = "movie" or "s:e"
|
||||
let rest = &l[4..];
|
||||
let (key, nid) = rest.rsplit_once(':').unwrap_or((rest, ""));
|
||||
let Ok(nid) = nid.parse::<i64>() else { return };
|
||||
let ep = if key == "movie" {
|
||||
None
|
||||
} else {
|
||||
let mut p = key.split(':');
|
||||
p.next().and_then(|v| v.parse().ok()).zip(p.next().and_then(|v| v.parse().ok()))
|
||||
};
|
||||
self.play(cx, ep, Some(nid));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn focus(&mut self, cx: &Cx, _line: &str, _item: &str) {
|
||||
let url = cx.api().image(self.backdrop().as_deref(), false);
|
||||
cx.backdrop(&url, Look::Sharp, &format!("detail:{}", self.id));
|
||||
}
|
||||
|
||||
fn shown(&mut self, cx: &Cx) {
|
||||
self.reload_progress(cx);
|
||||
}
|
||||
|
||||
fn as_any(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn detail(seasons: &[(i32, i32)]) -> TitleDetail {
|
||||
let json = format!(
|
||||
r#"{{"type":"tv","id":"tt1","title":"X","genres":[],"seasons":[{}]}}"#,
|
||||
seasons.iter().map(|(n, c)| format!(r#"{{"number":{n},"episodeCount":{c},"airedCount":{c}}}"#)).collect::<Vec<_>>().join(",")
|
||||
);
|
||||
serde_json::from_str(&json).unwrap()
|
||||
}
|
||||
|
||||
fn row(s: i32, e: i32, completed: bool) -> ProgressRow {
|
||||
ProgressRow { season: s, episode: e, position: 100.0, duration: Some(1000.0), completed }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_targets() {
|
||||
let d = detail(&[(1, 3), (2, 2)]);
|
||||
assert_eq!(target(&d, &[]), (Some((1, 1)), "Lejátszás".into()));
|
||||
assert_eq!(target(&d, &[row(1, 2, false)]).1, "Folytatás · S01E02");
|
||||
assert_eq!(target(&d, &[row(1, 3, true)]), (Some((2, 1)), "Következő · S02E01".into()));
|
||||
assert_eq!(target(&d, &[row(2, 2, true)]).1, "Újra");
|
||||
assert_eq!(current_season(&d, &[row(1, 1, true), row(1, 2, true), row(1, 3, true)]), 2);
|
||||
assert_eq!(current_season(&d, &[row(1, 1, true)]), 1);
|
||||
}
|
||||
}
|
||||
283
src/screens/home.rs
Normal file
283
src/screens/home.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
//! Kezdőlap: the admin's setup checklist, the spotlight (popular movies and
|
||||
//! series taking turns), "Folytasd, ahol abbahagytad", the server's rows.
|
||||
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::api::{HomeData, MediaType, NcoreStatus, TitleState, TitleSummary, VpnStatus};
|
||||
use crate::app::{Cx, Look, Screen};
|
||||
use crate::page::{Ch, Frame, Kind, L, Spec};
|
||||
use crate::screens::{self, Load, continue_card, row_copy, title_cards};
|
||||
use crate::{format, player};
|
||||
|
||||
const DWELL_SECS: u64 = 9;
|
||||
|
||||
pub struct Home {
|
||||
data: Load<HomeData>,
|
||||
states: HashMap<String, TitleState>,
|
||||
setup: Option<(VpnStatus, NcoreStatus)>,
|
||||
/// The server answered 409: nothing can play until VPN / nCore are set up.
|
||||
needs_setup: bool,
|
||||
spotlight: Vec<TitleSummary>,
|
||||
index: usize,
|
||||
since: Instant,
|
||||
hero_focused: bool,
|
||||
loaded: bool,
|
||||
}
|
||||
|
||||
impl Home {
|
||||
pub fn new() -> Home {
|
||||
Home {
|
||||
data: Load::Loading,
|
||||
states: HashMap::new(),
|
||||
setup: None,
|
||||
needs_setup: false,
|
||||
spotlight: Vec::new(),
|
||||
index: 0,
|
||||
since: Instant::now(),
|
||||
hero_focused: true,
|
||||
loaded: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn load(&mut self, cx: &Cx) {
|
||||
let api = cx.api();
|
||||
let admin = cx.user().is_admin;
|
||||
cx.spawn::<Home, _>(
|
||||
move || {
|
||||
let home = api.home();
|
||||
let states = api.list_status().unwrap_or_default();
|
||||
let setup = if admin { api.vpn().ok().zip(api.ncore().ok()) } else { None };
|
||||
(home, states, setup)
|
||||
},
|
||||
|s, cx, (home, states, setup)| {
|
||||
s.needs_setup = matches!(&home, Err(e) if crate::api::status_of(e) == Some(409));
|
||||
s.data = if s.needs_setup { Load::Ready(HomeData { rows: Vec::new(), continue_watching: Vec::new() }) } else { Load::from(home, cx) };
|
||||
s.states = states;
|
||||
s.setup = setup;
|
||||
if let Some(d) = s.data.ready() {
|
||||
s.spotlight = spotlight(&d.rows);
|
||||
s.index = s.index.min(s.spotlight.len().saturating_sub(1));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn current(&self) -> Option<&TitleSummary> {
|
||||
self.spotlight.get(self.index)
|
||||
}
|
||||
|
||||
fn find(&self, key: &str) -> Option<TitleSummary> {
|
||||
let d = self.data.ready()?;
|
||||
if let Some((kind, id)) = screens::parse_title_key(key) {
|
||||
return d.rows.iter().flat_map(|r| r.items.iter()).chain(self.spotlight.iter()).find(|t| t.kind == kind && t.id == id).cloned();
|
||||
}
|
||||
if let Some((kind, id, _)) = screens::parse_continue(key) {
|
||||
return d.continue_watching.iter().map(|c| &c.title).find(|t| t.kind == kind && t.id == id).cloned();
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Popular movies and series, alternating, that have artwork worth showing.
|
||||
fn spotlight(rows: &[crate::api::HomeRow]) -> Vec<TitleSummary> {
|
||||
let pick = |id: &str| -> Vec<TitleSummary> { rows.iter().find(|r| r.id == id).map(|r| r.items.iter().filter(|t| t.backdrop.is_some()).cloned().collect()).unwrap_or_default() };
|
||||
let (movies, series) = (pick("popular-movie"), pick("popular-tv"));
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while out.len() < 6 && (i < movies.len() || i < series.len()) {
|
||||
if let Some(m) = movies.get(i) {
|
||||
out.push(m.clone());
|
||||
}
|
||||
if let Some(s) = series.get(i).filter(|_| out.len() < 6) {
|
||||
out.push(s.clone());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.extend(rows.first().map(|r| r.items.iter().filter(|t| t.backdrop.is_some()).take(6).cloned().collect::<Vec<_>>()).unwrap_or_default());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn hu_text(t: &TitleSummary) -> &'static str {
|
||||
match t.hu {
|
||||
Some(h) if h.dub => "Magyar szinkron",
|
||||
Some(h) if h.sub => "Magyar felirat",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// "★ 7.8 · 2024 · Film · Dráma, Krimi · Magyar szinkron"
|
||||
pub fn meta_line(t: &TitleSummary, extra: &str) -> String {
|
||||
let mut p: Vec<String> = Vec::new();
|
||||
if let Some(r) = t.rating.filter(|r| *r > 0.0) {
|
||||
p.push(format!("★ {}", format::rating(r)));
|
||||
}
|
||||
if let Some(y) = t.year_label.clone().or_else(|| t.year.map(|y| y.to_string())) {
|
||||
p.push(y);
|
||||
}
|
||||
p.push(t.kind.label().into());
|
||||
if !extra.is_empty() {
|
||||
p.push(extra.into());
|
||||
}
|
||||
if !t.genres.is_empty() {
|
||||
p.push(t.genres.iter().take(2).map(|g| format::genre(g)).collect::<Vec<_>>().join(", "));
|
||||
}
|
||||
let hu = hu_text(t);
|
||||
if !hu.is_empty() {
|
||||
p.push(hu.into());
|
||||
}
|
||||
p.join(" · ")
|
||||
}
|
||||
|
||||
impl Screen for Home {
|
||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
||||
if !self.loaded {
|
||||
self.loaded = true;
|
||||
self.load(cx);
|
||||
}
|
||||
let api = cx.api();
|
||||
let mut lines = Vec::new();
|
||||
|
||||
// Setup checklist (admin): VPN and nCore.
|
||||
if let Some((vpn, ncore)) = &self.setup {
|
||||
let vpn_ok = vpn.traffic.path == "vpn";
|
||||
let ncore_ok = ncore.configured && ncore.circuit.state == "ok";
|
||||
let left = [vpn_ok, ncore_ok].iter().filter(|b| !**b).count();
|
||||
if left > 0 || self.needs_setup {
|
||||
let title = match left {
|
||||
0 => "Minden készen áll".to_string(),
|
||||
1 => "Még egy lépés, és indulhat a filmezés".to_string(),
|
||||
_ => "Még két lépés, és indulhat a filmezés".to_string(),
|
||||
};
|
||||
lines.push(L::notice("setup", "info", title, "Tunnel nélkül semmi nem megy ki a szerverről, a katalógus sem tölt be. Az nCore fiókból jönnek a filmek és a sorozatok."));
|
||||
lines.push(L::checks(
|
||||
"setup-checks",
|
||||
vec![
|
||||
(vpn_ok as i32, "WireGuard tunnel csatlakoztatva".into(), vpn.traffic.reason.clone().unwrap_or_default()),
|
||||
(ncore_ok as i32, "nCore fiók megadva".into(), ncore.circuit.message.clone().unwrap_or_default()),
|
||||
],
|
||||
));
|
||||
let mut chips = Vec::new();
|
||||
if !vpn_ok {
|
||||
chips.push(Ch::new("vpn", "VPN beállítása").tone("primary"));
|
||||
}
|
||||
if !ncore_ok {
|
||||
chips.push(Ch::new("ncore", "nCore fiók megadása").tone("primary"));
|
||||
}
|
||||
if !chips.is_empty() {
|
||||
lines.push(L::chips("setup-go", "", chips));
|
||||
}
|
||||
}
|
||||
} else if self.needs_setup {
|
||||
lines.push(L::notice("setup", "info", "A szerver még nincs kész", "A VPN-t és az nCore fiókot az admin állítja be. Amint kész, itt megjelennek a filmek és a sorozatok."));
|
||||
}
|
||||
|
||||
// Spotlight.
|
||||
if let Some(t) = self.current() {
|
||||
let listed = self.states.get(&format!("{}:{}", t.kind.key(), t.id)).is_some_and(|s| s.listed);
|
||||
let mut hero = L::new("hero", Kind::Hero);
|
||||
hero.style = "KIEMELT TARTALOM".into();
|
||||
hero.title = t.title.clone();
|
||||
hero.logo = api.image(t.logo.as_deref(), true);
|
||||
hero.meta = meta_line(t, "");
|
||||
hero.text = t.overview.clone().unwrap_or_default();
|
||||
hero.subtitle = format!("{} / {}", self.index + 1, self.spotlight.len());
|
||||
hero.chips = vec![
|
||||
Ch::new("play", if t.kind == MediaType::Movie { "Lejátszás" } else { "Epizódok" }).icon("play").tone("primary"),
|
||||
Ch::new("info", "További infók").icon("info"),
|
||||
Ch::new("list", "").icon(if listed { "check" } else { "plus" }).active(listed),
|
||||
];
|
||||
lines.push(hero);
|
||||
}
|
||||
|
||||
if let Some(st) = self.data.status("status") {
|
||||
lines.push(st);
|
||||
}
|
||||
if let Some(d) = self.data.ready() {
|
||||
if !d.continue_watching.is_empty() {
|
||||
lines.push(L::cards("continue", "Folytasd, ahol abbahagytad", "landscape", d.continue_watching.iter().map(|c| continue_card(&api, c)).collect()).captions());
|
||||
}
|
||||
for r in &d.rows {
|
||||
let (title, note) = row_copy(&r.id).map(|(t, n)| (t.to_string(), n.to_string())).unwrap_or((r.title.clone(), String::new()));
|
||||
lines.push(L::cards(format!("row:{}", r.id), title, "poster", title_cards(&api, &r.items, &self.states)).sub(note));
|
||||
}
|
||||
}
|
||||
Spec { lines, frame: Frame { nav: Some(0), ..Frame::default() } }
|
||||
}
|
||||
|
||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
|
||||
match (line, item) {
|
||||
("setup-go", "vpn") => cx.c.open_settings("vpn"),
|
||||
("setup-go", "ncore") => cx.c.open_settings("ncore"),
|
||||
("hero", "play") => {
|
||||
let Some(t) = self.current().cloned() else { return };
|
||||
if t.kind == MediaType::Movie {
|
||||
cx.play(player::Request::title(t.kind, &t.id, t.title.clone(), None, t.backdrop.clone()));
|
||||
} else {
|
||||
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id, Some(t))));
|
||||
}
|
||||
}
|
||||
("hero", "info") => {
|
||||
if let Some(t) = self.current().cloned() {
|
||||
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id, Some(t))));
|
||||
}
|
||||
}
|
||||
("hero", "list") => {
|
||||
let Some(t) = self.current().cloned() else { return };
|
||||
let key = format!("{}:{}", t.kind.key(), t.id);
|
||||
let on = !self.states.get(&key).is_some_and(|s| s.listed);
|
||||
self.states.entry(key).or_default().listed = on;
|
||||
let api = cx.api();
|
||||
cx.call::<Home>("Listám", move || api.set_listed(t.kind, &t.id, on), |_, _| {});
|
||||
cx.toast(if on { "Hozzáadva a listádhoz" } else { "Eltávolítva a listádról" });
|
||||
}
|
||||
(_, key) => {
|
||||
let found = self.find(key);
|
||||
screens::open_card(cx, key, |_| found.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn focus(&mut self, cx: &Cx, line: &str, item: &str) {
|
||||
self.hero_focused = line == "hero";
|
||||
self.since = Instant::now();
|
||||
if self.hero_focused {
|
||||
if let Some(t) = self.current() {
|
||||
let url = cx.api().image(t.backdrop.as_deref(), false);
|
||||
cx.backdrop(&url, Look::Sharp, &format!("spot:{}", t.id));
|
||||
}
|
||||
return;
|
||||
}
|
||||
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 tick(&mut self, cx: &Cx) {
|
||||
// The spotlight turns after a while without a key press (any focus
|
||||
// move restarts the clock): Play always plays what it shows.
|
||||
if self.spotlight.len() >= 2 && self.since.elapsed().as_secs() >= DWELL_SECS {
|
||||
self.since = Instant::now();
|
||||
self.index = (self.index + 1) % self.spotlight.len();
|
||||
cx.refresh();
|
||||
if self.hero_focused {
|
||||
self.focus(cx, "hero", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(&mut self, cx: &Cx) {
|
||||
self.load(cx);
|
||||
}
|
||||
|
||||
fn as_any(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
210
src/screens/mod.rs
Normal file
210
src/screens/mod.rs
Normal file
@@ -0,0 +1,210 @@
|
||||
//! The browsing screens. Each one describes its page as lines (src/page.rs)
|
||||
//! and reacts to OK; see app::Screen.
|
||||
|
||||
pub mod anime_detail;
|
||||
pub mod anime_hub;
|
||||
pub mod detail;
|
||||
pub mod home;
|
||||
pub mod mylist;
|
||||
pub mod search;
|
||||
pub mod settings;
|
||||
pub mod source;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::api::{AnimeSummary, Api, ContinueItem, MediaType, TitleState, TitleSummary};
|
||||
use crate::app::{Cx, Screen};
|
||||
use crate::format;
|
||||
use crate::page::{C, L};
|
||||
|
||||
/// The screen of a top navigation section.
|
||||
pub fn section(n: usize) -> Box<dyn Screen> {
|
||||
match n {
|
||||
1 => Box::new(source::Source::new(MediaType::Movie)),
|
||||
2 => Box::new(source::Source::new(MediaType::Tv)),
|
||||
3 => Box::new(anime_hub::AnimeHub::new()),
|
||||
4 => Box::new(mylist::MyList::new()),
|
||||
5 => Box::new(search::Search::new()),
|
||||
6 => Box::new(settings::Settings::new()),
|
||||
_ => Box::new(home::Home::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Data that loads.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub enum Load<T> {
|
||||
#[default]
|
||||
Loading,
|
||||
Ready(T),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl<T> Load<T> {
|
||||
pub fn ready(&self) -> Option<&T> {
|
||||
match self {
|
||||
Load::Ready(t) => Some(t),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn ready_mut(&mut self) -> Option<&mut T> {
|
||||
match self {
|
||||
Load::Ready(t) => Some(t),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn from(r: anyhow::Result<T>, cx: &Cx) -> Load<T> {
|
||||
match r {
|
||||
Ok(t) => Load::Ready(t),
|
||||
Err(e) => {
|
||||
if crate::api::is_unauthenticated(&e) {
|
||||
cx.error("", &e);
|
||||
}
|
||||
Load::Failed(crate::api::describe(&e))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The loading / error line, or None when ready.
|
||||
pub fn status(&self, id: &str) -> Option<L> {
|
||||
match self {
|
||||
Load::Loading => Some(L::text(id, "Betöltés…", "caption")),
|
||||
Load::Failed(e) => Some(L::notice(id, "bad", "Nem sikerült betölteni", e.clone())),
|
||||
Load::Ready(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// "t:movie:tt0133093"
|
||||
pub fn title_key(kind: MediaType, id: &str) -> String {
|
||||
format!("t:{}:{}", kind.key(), id)
|
||||
}
|
||||
|
||||
pub fn parse_title_key(key: &str) -> Option<(MediaType, String)> {
|
||||
let mut p = key.splitn(3, ':');
|
||||
if p.next()? != "t" {
|
||||
return None;
|
||||
}
|
||||
let kind = match p.next()? {
|
||||
"movie" => MediaType::Movie,
|
||||
"tv" => MediaType::Tv,
|
||||
_ => return None,
|
||||
};
|
||||
Some((kind, p.next()?.to_string()))
|
||||
}
|
||||
|
||||
/// A movie / series card (poster); `state` adds the watched marks.
|
||||
pub fn title_card(api: &Api, t: &TitleSummary, state: Option<&TitleState>) -> C {
|
||||
let mut c = C::new(title_key(t.kind, &t.id), t.title.clone(), api.image(t.poster.as_deref(), false));
|
||||
c.caption = t.title.clone();
|
||||
let mut detail = vec![t.year_label.clone().or_else(|| t.year.map(|y| y.to_string())).unwrap_or_default(), t.kind.label().to_string()];
|
||||
if let Some(r) = t.rating.filter(|r| *r > 0.0) {
|
||||
detail.push(format!("★ {}", format::rating(r)));
|
||||
}
|
||||
c.detail = detail.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
if let Some(hu) = t.hu {
|
||||
if hu.dub {
|
||||
c.badge = "Szinkron".into();
|
||||
c.badge_tone = "dub";
|
||||
} else if hu.sub {
|
||||
c.badge = "Felirat".into();
|
||||
c.badge_tone = "sub";
|
||||
}
|
||||
}
|
||||
if let Some(s) = state {
|
||||
if s.watched {
|
||||
c.mark = "check";
|
||||
} else if s.watched_episodes > 0 && t.kind == MediaType::Tv {
|
||||
c.detail = format!("{} · {} rész megnézve", c.detail, s.watched_episodes);
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
pub fn title_cards(api: &Api, items: &[TitleSummary], states: &HashMap<String, TitleState>) -> Vec<C> {
|
||||
items.iter().map(|t| title_card(api, t, states.get(&format!("{}:{}", t.kind.key(), t.id)))).collect()
|
||||
}
|
||||
|
||||
/// "Folytatás" card: landscape art, progress, "S01E02 · még 12 perc".
|
||||
pub fn continue_card(api: &Api, item: &ContinueItem) -> C {
|
||||
let t = &item.title;
|
||||
let ep = item.season.zip(item.episode).filter(|(s, _)| *s > 0 && t.kind == MediaType::Tv);
|
||||
let id = match ep {
|
||||
Some((s, e)) => format!("c:{}:{}:{s}:{e}", t.kind.key(), t.id),
|
||||
None => format!("c:{}:{}", t.kind.key(), t.id),
|
||||
};
|
||||
let art = t.backdrop.as_deref().or(t.poster.as_deref());
|
||||
let mut c = C::new(id, t.title.clone(), api.image(art, false));
|
||||
c.caption = t.title.clone();
|
||||
let left = item.duration.map(|d| ((d - item.position) / 60.0).round().max(0.0) as i64);
|
||||
let what = ep.map(|(s, e)| format::episode_code(s, e)).unwrap_or_else(|| "Film".into());
|
||||
c.detail = match left {
|
||||
Some(l) if l > 0 => format!("{what} · még {l} perc"),
|
||||
_ => what,
|
||||
};
|
||||
c.progress = item.duration.filter(|d| *d > 0.0).map(|d| (item.position / d).min(1.0) as f32).unwrap_or(-1.0);
|
||||
c
|
||||
}
|
||||
|
||||
/// Parses a "Folytatás" card id: (type, id, episode).
|
||||
pub fn parse_continue(key: &str) -> Option<(MediaType, String, Option<(i32, i32)>)> {
|
||||
let p: Vec<&str> = key.split(':').collect();
|
||||
if p.first() != Some(&"c") || p.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let kind = if p[1] == "tv" { MediaType::Tv } else { MediaType::Movie };
|
||||
let ep = if p.len() >= 5 { p[3].parse().ok().zip(p[4].parse().ok()) } else { None };
|
||||
Some((kind, p[2].to_string(), ep))
|
||||
}
|
||||
|
||||
/// An anime card (cover).
|
||||
pub fn anime_card(api: &Api, a: &AnimeSummary) -> C {
|
||||
let mut c = C::new(format!("a:{}", a.id), a.title.name(), api.image(a.cover_image.as_deref(), false));
|
||||
c.caption = a.title.name();
|
||||
let mut d = vec![format::anime_season(a.season.as_deref(), a.season_year), format::anime_format(a.format.as_deref())];
|
||||
if let Some(s) = a.average_score.filter(|s| *s > 0.0) {
|
||||
d.push(format!("★ {}", format::anime_score(s)));
|
||||
}
|
||||
c.detail = d.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
c
|
||||
}
|
||||
|
||||
pub fn parse_anime_key(key: &str) -> Option<i64> {
|
||||
key.strip_prefix("a:")?.split(':').next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The web app's names for the server's home rows: (title, note).
|
||||
pub fn row_copy(id: &str) -> Option<(&'static str, &'static str)> {
|
||||
Some(match id {
|
||||
"popular-movie" => ("Most felkapott", "Népszerű filmek"),
|
||||
"ncore-movie" => ("Épp most érkezett", "Friss filmek az nCore-on"),
|
||||
"ncore-tv" => ("Friss részek, friss évadok", "Új sorozat-feltöltések az nCore-on"),
|
||||
"popular-tv" => ("Sorozatok, amiket nem tudsz majd letenni", "Népszerű sorozatok"),
|
||||
"new-movie" => ("Idén mutatták be", "Idei filmek"),
|
||||
"featured-movie" => ("Kihagyhatatlan filmek", "Kiemelt filmek"),
|
||||
"featured-tv" => ("Sorozatok, amikbe beleszeretsz", "Kiemelt sorozatok"),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens the page of a card id ("t:…", "c:…", "a:…"); true if it was one.
|
||||
pub fn open_card(cx: &Cx, key: &str, find: impl Fn(&str) -> Option<TitleSummary>) -> bool {
|
||||
if let Some((kind, id)) = parse_title_key(key) {
|
||||
cx.push(Box::new(detail::Detail::new(kind, &id, find(key))));
|
||||
return true;
|
||||
}
|
||||
if let Some((kind, id, ep)) = parse_continue(key) {
|
||||
// "Folytatás" plays right away, where it stopped.
|
||||
let summary = find(key);
|
||||
cx.play(crate::player::Request::title(kind, &id, summary.as_ref().map(|s| s.title.clone()).unwrap_or_default(), ep, summary.and_then(|s| s.backdrop)));
|
||||
return true;
|
||||
}
|
||||
if let Some(id) = key.strip_prefix("ac:").and_then(|r| r.split(':').next()).and_then(|v| v.parse::<i64>().ok()) {
|
||||
let ep: i32 = key.rsplit(':').next().and_then(|v| v.parse().ok()).unwrap_or(1);
|
||||
cx.play(crate::player::Request::anime(id, String::new(), ep, None));
|
||||
return true;
|
||||
}
|
||||
if let Some(id) = parse_anime_key(key) {
|
||||
cx.push(Box::new(anime_detail::AnimeDetail::new(id)));
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
559
src/screens/source.rs
Normal file
559
src/screens/source.rs
Normal file
@@ -0,0 +1,559 @@
|
||||
//! 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<i32>, Option<i32>); 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<String>,
|
||||
added: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct Filters {
|
||||
sort: &'static str,
|
||||
genre: Option<String>,
|
||||
yf: Option<i32>,
|
||||
yt: Option<i32>,
|
||||
rf: Option<f64>,
|
||||
rt: Option<f64>,
|
||||
}
|
||||
|
||||
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<TitleSummary>,
|
||||
page: u32,
|
||||
cursor: Option<String>,
|
||||
has_more: bool,
|
||||
loading: bool,
|
||||
/// Pages loaded; empty ones since `resume_from` count towards the stop.
|
||||
pages: Vec<usize>,
|
||||
resume_from: usize,
|
||||
error: Option<String>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
pub struct Source {
|
||||
kind: MediaType,
|
||||
tab: Tab,
|
||||
started: bool,
|
||||
genres: Load<Vec<Genre>>,
|
||||
continuing: Vec<ContinueItem>,
|
||||
library: Load<Vec<Entry>>,
|
||||
states: HashMap<String, TitleState>,
|
||||
rails: Vec<(String, String, String, Load<Vec<TitleSummary>>)>,
|
||||
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::<Source, _>(
|
||||
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<String>, Option<i32>)> = 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::<Source, _>(
|
||||
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::<Source, _>(
|
||||
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<String> = s.cat.items.iter().map(|t| t.id.clone()).collect();
|
||||
let new: Vec<TitleSummary> = 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<TitleSummary> {
|
||||
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<C> {
|
||||
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<i32> = (1920..=this_year()).rev().collect();
|
||||
items.extend(years.iter().map(|y| (y.to_string(), String::new(), current == Some(*y))));
|
||||
cx.select::<Source>(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<f64> = (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::<Source>(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<ListItem>, history: Vec<ListItem>) -> Vec<Entry> {
|
||||
let mut out: Vec<Entry> = 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<String>) -> 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<TitleSummary> = 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<TitleSummary> = 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<Ch> = 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<i32>, 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<f64>, 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::<usize>().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::<f64>().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::<Source, _>(
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user