Files
youtube/src/screens/mod.rs
Tamas Csikel 9875d435e1
All checks were successful
release / release (push) Successful in 10m13s
YouTube 2.0.0: native client without ads
Replaces the web app (youtube.com/tv in Chromium) with a native Rust +
Slint client on sf-ui, built on Netflex TV's page engine.

- InnerTube: web client for public pages, the TV client with the
  account's OAuth token for personal ones, visionOS (direct URLs) for
  streams, the TV client with yt-dlp's ejs solver (QuickJS) as fallback.
- One version, no ads: ad breaks are never requested, ad renderers are
  skipped in feeds. SponsorBlock skips sponsored parts.
- Sign-in with a QR code / youtube.com/activate (OAuth device flow).
- Signed out: subscriptions and history on the TV; a home filled with
  this week's popular Hungarian videos when YouTube's is empty.
- Playback: one-quality DASH manifest for GStreamer, H.264 up to 1080p
  or AV1 up to 4K, captions, quality switching, up next, resume.
- Release builds for x86-64 and the Raspberry Pi (aarch64).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:27:41 +01:00

350 lines
13 KiB
Rust

//! The browsing screens. Each one describes its page as lines (src/page.rs)
//! and reacts to OK; see app::Screen.
//!
//! Card ids: "v:<video>", "c:<channel>", "p:<playlist>", "m:<mix>:<video>".
pub mod channel;
pub mod home;
pub mod library;
pub mod playlist;
pub mod search;
pub mod settings;
pub mod subs;
use crate::app::{Cx, Look, Screen};
use crate::page::{C, GRID_YT, L, grid_lines};
use crate::player::{self, Request};
use crate::yt::{Feed, Item, Shelf, Video};
/// The screen of a top navigation section.
pub fn section(n: usize) -> Box<dyn Screen> {
match n {
1 => Box::new(subs::Subs::new()),
2 => Box::new(library::Library::new()),
3 => Box::new(search::Search::new()),
4 => 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 e.chain().any(|c| c.downcast_ref::<crate::yt::YtError>().is_some_and(|y| y.status == 401)) {
cx.error("", &e);
}
log::warn!("load: {e:#}");
Load::Failed(crate::yt::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,
}
}
}
pub fn video_card(v: &Video) -> C {
let mut c = C::new(format!("v:{}", v.id), v.title.clone(), v.thumb.clone());
c.caption = v.title.clone();
c.detail = [v.channel.as_str(), v.meta.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join(" · ");
c.progress = v.progress;
if v.live {
c.badge = "ÉLŐ".into();
c.badge_tone = "accent";
} else if v.short {
c.badge = "Shorts".into();
}
c.corner = v.duration.clone();
c
}
pub fn item_card(i: &Item) -> C {
match i {
Item::Video(v) => video_card(v),
Item::Channel(ch) => {
let mut c = C::new(format!("c:{}", ch.id), ch.title.clone(), ch.thumb.clone());
c.caption = ch.title.clone();
c.detail = if ch.meta.is_empty() { "Csatorna".into() } else { format!("Csatorna · {}", ch.meta) };
c.round = true;
c
}
Item::Playlist(p) => {
let id = if p.id.starts_with("RD") && !p.first_video.is_empty() { format!("m:{}:{}", p.id, p.first_video) } else { format!("p:{}", p.id) };
let mut c = C::new(id, p.title.clone(), p.thumb.clone());
c.caption = p.title.clone();
c.detail = p.meta.clone();
c.badge = if p.id.starts_with("RD") { "Mix".into() } else { "Lista".into() };
c
}
}
}
/// Items as cards; `shorts`: keep Shorts.
pub fn cards(items: &[Item], shorts: bool) -> Vec<C> {
items.iter().filter(|i| shorts || !matches!(i, Item::Video(v) if v.short)).map(item_card).collect()
}
/// A feed as lines: titled shelves as rows, the untitled main list as a
/// grid named `main`. `id`: prefix of the line ids.
pub fn feed_lines(id: &str, feed: &Feed, main: &str, shorts: bool) -> Vec<L> {
let mut out = Vec::new();
for (i, s) in feed.shelves.iter().enumerate() {
if !shorts && is_shorts(s) {
continue;
}
let cards = cards(&s.items, shorts);
if cards.is_empty() {
continue;
}
if s.title.is_empty() {
// Shorts mixed into the main list get a row of their own after it.
let (shorts_cards, rest): (Vec<C>, Vec<C>) = cards.into_iter().partition(|c| c.badge == "Shorts");
out.extend(grid_lines(&format!("{id}-grid"), main, "landscape", rest, GRID_YT));
if !shorts_cards.is_empty() {
out.push(L::cards(format!("{id}-shorts{i}"), "Shorts", "landscape", shorts_cards).captions());
}
} else {
out.push(L::cards(format!("{id}-{i}"), s.title.clone(), "landscape", cards).captions());
}
}
out
}
fn is_shorts(s: &Shelf) -> bool {
s.title.to_lowercase().contains("shorts") || (!s.items.is_empty() && s.items.iter().all(|i| matches!(i, Item::Video(v) if v.short)))
}
/// Finds an item by card id in feeds.
pub fn find<'a>(feeds: impl IntoIterator<Item = &'a Feed>, key: &str) -> Option<Item> {
let id = key.split(':').nth(1)?;
feeds.into_iter().flat_map(|f| f.items()).find(|i| i.id() == id).cloned()
}
/// Backdrop for a focused card: its picture, soft.
pub fn focus_backdrop(cx: &Cx, item: Option<&Item>, key: &str) {
match item {
Some(Item::Video(v)) => cx.backdrop(&v.thumb, Look::Soft, key),
Some(Item::Playlist(p)) => cx.backdrop(&p.thumb, Look::Soft, key),
_ => cx.backdrop("", Look::Soft, ""),
}
}
/// Opens a card: plays a video (with `queue` after it), opens a channel or
/// a playlist. True if it was a card.
pub fn open_card(cx: &Cx, key: &str, item: Option<Item>, queue: Vec<Video>) -> bool {
let mut parts = key.splitn(3, ':');
let (kind, id) = (parts.next().unwrap_or_default(), parts.next().unwrap_or_default());
match kind {
"v" => {
let video = match item {
Some(Item::Video(v)) => v,
_ => Video { id: id.to_string(), ..Video::default() },
};
cx.play(Request::new(video, queue));
true
}
"c" => {
let title = item.map(|i| i.title().to_string()).unwrap_or_default();
cx.push(Box::new(channel::ChannelPage::new(id, &title)));
true
}
"p" => {
let title = item.map(|i| i.title().to_string()).unwrap_or_default();
cx.push(Box::new(playlist::PlaylistPage::new(id, &title)));
true
}
"m" => {
let first = parts.next().unwrap_or_default();
let mut r = Request::new(Video { id: first.to_string(), ..Video::default() }, Vec::new());
r.mix = Some(id.to_string());
cx.play(r);
true
}
_ => false,
}
}
/// The videos after `key` in `items` (the queue when one of them plays).
pub fn queue_after(items: &[Item], key: &str) -> Vec<Video> {
let id = key.split(':').nth(1).unwrap_or_default();
let pos = items.iter().position(|i| i.id() == id).map(|p| p + 1).unwrap_or(items.len());
items[pos..]
.iter()
.filter_map(|i| match i {
Item::Video(v) if !v.live => Some(v.clone()),
_ => None,
})
.take(player::QUEUE_MAX)
.collect()
}
/// Items of the line holding `key` (for the queue).
pub fn line_items(feed: &Feed, line: &str) -> Vec<Item> {
// Grid lines ("x-grid#3") all belong to the untitled main list.
if line.contains("-grid") {
return feed.shelves.iter().filter(|s| s.title.is_empty()).flat_map(|s| s.items.clone()).collect();
}
if let Some(i) = line.rsplit('-').next().and_then(|n| n.strip_prefix("shorts")).and_then(|n| n.parse::<usize>().ok()) {
return feed.shelves.get(i).map(|s| s.items.iter().filter(|i| matches!(i, Item::Video(v) if v.short)).cloned().collect()).unwrap_or_default();
}
let i: Option<usize> = line.rsplit('-').next().and_then(|n| n.parse().ok());
i.and_then(|i| feed.shelves.get(i)).map(|s| s.items.clone()).unwrap_or_default()
}
/// A feed on a page with its continuations: the main list grows as a grid,
/// titled shelves grow sideways, and more shelves come at the end.
pub struct Paged {
pub load: Load<Feed>,
prefix: String,
search: bool,
personal: bool,
started: bool,
busy: std::collections::HashSet<String>,
}
impl Paged {
/// `prefix`: line ids; `search`: continuations go to the search
/// endpoint; `personal`: with the account (signed in).
pub fn new(prefix: &str, search: bool, personal: bool) -> Paged {
Paged { load: Load::Loading, prefix: prefix.into(), search, personal, started: false, busy: Default::default() }
}
/// Loads the first page once.
pub fn start<T: Screen>(&mut self, cx: &Cx, get: fn(&mut T) -> &mut Paged, work: impl FnOnce() -> anyhow::Result<Feed> + Send + 'static) {
if self.started {
return;
}
self.started = true;
self.load = Load::Loading;
cx.spawn::<T, _>(work, move |s, cx, r| get(s).load = Load::from(r, cx));
}
/// Marks the first page as loading (the caller loads it).
pub fn begin(&mut self) {
self.started = true;
self.load = Load::Loading;
}
pub fn feed(&self) -> Option<&Feed> {
self.load.ready()
}
/// The feed's lines (or its loading / error line).
pub fn lines(&self, main: &str, shorts: bool) -> Vec<L> {
match &self.load {
Load::Ready(f) => feed_lines(&self.prefix, f, main, shorts),
other => other.status(&format!("{}-status", self.prefix)).into_iter().collect(),
}
}
/// The focus is near the end of `list`: loads more of it (and more
/// shelves after the last one).
pub fn more<T: Screen>(&mut self, cx: &Cx, list: &str, get: fn(&mut T) -> &mut Paged) {
let Some(f) = self.load.ready() else { return };
let Some(rest) = list.strip_prefix(&format!("{}-", self.prefix)) else { return };
let mut jobs: Vec<(Option<usize>, String)> = Vec::new();
if rest.starts_with("grid") {
if let Some(t) = &f.more {
jobs.push((None, t.clone()));
}
} else if let Ok(i) = rest.parse::<usize>() {
if let Some(t) = f.shelves.get(i).and_then(|s| s.more.clone()) {
jobs.push((Some(i), t));
}
let last = f.shelves.iter().rposition(|s| !s.title.is_empty());
if last.is_some_and(|l| i + 1 >= l) {
if let Some(t) = &f.more {
jobs.push((None, t.clone()));
}
}
}
for (target, token) in jobs {
if !self.busy.insert(token.clone()) {
continue;
}
let client = cx.client();
let (search, personal) = (self.search, self.personal);
cx.spawn::<T, _>(move || client.more(&token, search, personal), move |s, _cx, r| match r {
Ok(m) => get(s).append(target, m),
Err(e) => log::warn!("more: {e:#}"),
});
}
}
fn append(&mut self, target: Option<usize>, more: Feed) {
let Some(f) = self.load.ready_mut() else { return };
match target {
Some(i) => {
let next = more.more.clone().or_else(|| more.shelves.iter().find_map(|s| s.more.clone()));
if let Some(s) = f.shelves.get_mut(i) {
for it in more.flat() {
if !s.items.iter().any(|x| x.id() == it.id()) {
s.items.push(it);
}
}
s.more = next;
}
}
None => {
for s in more.shelves {
if s.title.is_empty() {
let main = match f.shelves.iter().position(|x| x.title.is_empty()) {
Some(i) => i,
None => {
f.shelves.insert(0, Shelf::default());
0
}
};
let m = &mut f.shelves[main];
for it in s.items {
if !m.items.iter().any(|x| x.id() == it.id()) {
m.items.push(it);
}
}
} else {
f.shelves.push(s);
}
}
f.more = more.more;
}
}
}
pub fn find(&self, key: &str) -> Option<Item> {
find(self.feed(), key)
}
/// The videos after `key` on its line.
pub fn queue(&self, line: &str, key: &str) -> Vec<Video> {
self.feed().map(|f| queue_after(&line_items(f, line), key)).unwrap_or_default()
}
}