YouTube 2.0.0: native client without ads
All checks were successful
release / release (push) Successful in 10m13s

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>
This commit is contained in:
Tamas Csikel
2026-11-02 16:27:41 +01:00
parent 645fd1c6fe
commit 9875d435e1
40 changed files with 15776 additions and 37 deletions

121
src/screens/channel.rs Normal file
View File

@@ -0,0 +1,121 @@
//! A channel: its name, subscribers, Feliratkozás, and its videos (newest
//! first, more as the focus nears the end). Signed in, Feliratkozás follows
//! the channel with the account; signed out, on this TV.
use std::any::Any;
use crate::app::{Cx, Look, Screen};
use crate::config::Sub;
use crate::page::{Ch, Frame, L, Spec};
use crate::screens::{self, Paged};
pub struct ChannelPage {
id: String,
title: String,
feed: Paged,
/// Signed in: the account follows it (None: not known yet).
subscribed: Option<bool>,
asked: bool,
}
impl ChannelPage {
pub fn new(id: &str, title: &str) -> ChannelPage {
ChannelPage { id: id.into(), title: title.into(), feed: Paged::new("ch", false, false), subscribed: None, asked: false }
}
fn paged(s: &mut ChannelPage) -> &mut Paged {
&mut s.feed
}
fn following(&self, cx: &Cx) -> bool {
if cx.signed_in() { self.subscribed.unwrap_or(false) } else { cx.library().is_sub(&self.id) }
}
}
impl Screen for ChannelPage {
fn spec(&mut self, cx: &Cx) -> Spec {
let client = cx.client();
let id = self.id.clone();
self.feed.start::<ChannelPage>(cx, ChannelPage::paged, move || client.channel(&id));
if cx.signed_in() && !self.asked {
self.asked = true;
let client = cx.client();
let id = self.id.clone();
cx.spawn::<ChannelPage, _>(move || client.is_subscribed(&id), |s, _cx, r| s.subscribed = r.ok().flatten());
}
let header = self.feed.feed().and_then(|f| f.header.clone()).unwrap_or_default();
if !header.title.is_empty() {
self.title = header.title.clone();
}
if let Some(h) = self.feed.feed().and_then(|f| f.header.as_ref()) {
if !h.thumb.is_empty() {
cx.backdrop(&h.thumb, Look::Soft, &format!("ch:{}", self.id));
}
}
let mut lines = vec![L::page_title("title", self.title.clone(), header.meta.clone())];
let on = self.following(cx);
let known = !cx.signed_in() || self.subscribed.is_some();
lines.push(L::chips(
"actions",
"",
vec![
Ch::new("sub", if on { "Feliratkozva" } else { "Feliratkozás" }).icon(if on { "check" } else { "plus" }).tone(if on { "" } else { "primary" }).active(on).enabled(known),
Ch::new("play", "Lejátszás").icon("play"),
],
));
lines.extend(self.feed.lines("Videók", cx.settings().shorts));
if self.feed.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "Nincs videó", "Ezen a csatornán nincs nyilvános videó."));
}
Spec { lines, frame: Frame::default() }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
match (line, key) {
("actions", "sub") => {
let on = !self.following(cx);
if cx.signed_in() {
let client = cx.client();
let id = self.id.clone();
self.subscribed = Some(on);
cx.call::<ChannelPage>("subscribe", move || client.subscribe(&id, on), move |s, cx, ok| {
if ok {
cx.toast(if on { "Feliratkoztál" } else { "Leiratkoztál" });
} else {
s.subscribed = Some(!on);
}
});
} else {
let thumb = self.feed.feed().and_then(|f| f.header.as_ref()).map(|h| h.thumb.clone()).unwrap_or_default();
let sub = Sub { id: self.id.clone(), title: self.title.clone(), thumb };
let now = cx.update_library(|l| l.toggle_sub(sub));
cx.toast(if now { "Feliratkoztál ezen a TV-n" } else { "Leiratkoztál" });
}
}
("actions", "play") => {
let Some(f) = self.feed.feed() else { return };
let mut videos = f.videos().filter(|v| !v.live && !v.short).cloned();
if let Some(first) = videos.next() {
cx.play(crate::player::Request::new(first, videos.take(crate::player::QUEUE_MAX).collect()));
}
}
_ => {
screens::open_card(cx, key, self.feed.find(key), self.feed.queue(line, key));
}
}
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
if let Some(item) = self.feed.find(key) {
screens::focus_backdrop(cx, Some(&item), key);
}
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<ChannelPage>(cx, list, ChannelPage::paged);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

190
src/screens/home.rs Normal file
View File

@@ -0,0 +1,190 @@
//! Kezdőlap: "Folytatás" (this TV's unfinished videos), then YouTube's home
//! feed (personal when signed in). A signed-out home can come back empty
//! (YouTube shows nothing without a history): then this TV fills it with
//! its subscriptions' latest videos, videos related to what it played last,
//! and this week's most watched videos of a few topics (Hungarian queries,
//! so the rows are local).
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Frame, L, Spec};
use crate::screens::{self, Load, Paged, cards, video_card};
use crate::yt::{Item, Video};
/// Rows of a signed-out home: (title, search).
const TOPICS: [(&str, &str); 5] = [
("Zene · népszerű a héten", "magyar zene"),
("Hírek", "híradó"),
("Film-előzetesek", "film előzetes"),
("Gaming", "gaming"),
("Sport", "sport összefoglaló"),
];
pub struct Home {
feed: Paged,
extra: Option<Load<Vec<(String, Vec<Item>)>>>,
}
impl Home {
pub fn new() -> Home {
Home { feed: Paged::new("home", false, true), extra: None }
}
fn paged(s: &mut Home) -> &mut Paged {
&mut s.feed
}
fn needs_extra(&self) -> bool {
match &self.feed.load {
Load::Ready(f) => f.is_empty(),
Load::Failed(_) => true,
Load::Loading => false,
}
}
fn load_extra(&mut self, cx: &Cx) {
if self.extra.is_some() {
return;
}
self.extra = Some(Load::Loading);
let client = cx.client();
let subs: Vec<String> = cx.library().subs.iter().take(15).map(|s| s.id.clone()).collect();
let last: Vec<(String, String)> = cx.library().history.iter().take(2).map(|w| (w.id.clone(), w.title.clone())).collect();
cx.spawn::<Home, _>(
move || {
let mut rows: Vec<(String, Vec<Item>)> = Vec::new();
let mut latest: Vec<(String, Video)> = Vec::new();
let handles: Vec<_> = subs
.into_iter()
.map(|id| {
let c = client.clone();
std::thread::spawn(move || crate::yt::extras::channel_feed(&c, &id).unwrap_or_default())
})
.collect();
for h in handles {
latest.extend(h.join().unwrap_or_default().into_iter().filter(|(_, v)| !v.short).take(6));
}
latest.sort_by(|a, b| b.0.cmp(&a.0));
if !latest.is_empty() {
rows.push(("Feliratkozásaid".into(), latest.into_iter().take(30).map(|(_, v)| Item::Video(v)).collect()));
}
let watched: Vec<_> = last
.into_iter()
.map(|(id, title)| {
let c = client.clone();
std::thread::spawn(move || (format!("Mert megnézted: {title}"), c.related(&id, None).map(|f| videos(&f))))
})
.collect();
let topics: Vec<_> = TOPICS
.iter()
.map(|(title, q)| {
let c = client.clone();
let (title, q) = (title.to_string(), q.to_string());
std::thread::spawn(move || (title, c.popular_this_week(&q).map(|f| videos(&f))))
})
.collect();
let handles: Vec<_> = watched.into_iter().chain(topics).collect();
let mut err = None;
for h in handles {
if let Ok((title, r)) = h.join() {
match r {
Ok(items) if !items.is_empty() => rows.push((title, items)),
Ok(_) => {}
Err(e) => err = Some(e),
}
}
}
match (rows.is_empty(), err) {
(true, Some(e)) => Err(e),
_ => Ok(rows),
}
},
|s, cx, r| s.extra = Some(Load::from(r, cx)),
);
}
fn item(&self, cx: &Cx, key: &str) -> Option<Item> {
if let Some(i) = self.feed.find(key) {
return Some(i);
}
if let Some(Load::Ready(rows)) = &self.extra {
let id = key.split(':').nth(1).unwrap_or_default();
if let Some(i) = rows.iter().flat_map(|r| r.1.iter()).find(|i| i.id() == id) {
return Some(i.clone());
}
}
let id = key.strip_prefix("v:")?;
cx.library().find(id).map(|w| Item::Video(w.video()))
}
}
/// A feed's videos for a row: no Shorts, no live streams.
fn videos(f: &crate::yt::Feed) -> Vec<Item> {
f.videos().filter(|v| !v.short && !v.live).take(24).cloned().map(Item::Video).collect()
}
impl Screen for Home {
fn spec(&mut self, cx: &Cx) -> Spec {
let client = cx.client();
self.feed.start::<Home>(cx, Home::paged, move || client.home());
let shorts = cx.settings().shorts;
let mut lines = Vec::new();
let unfinished: Vec<_> = cx.library().history.iter().filter(|w| w.unfinished()).take(20).map(|w| video_card(&w.video())).collect();
if !unfinished.is_empty() {
lines.push(L::cards("continue", "Folytatás", "landscape", unfinished).captions());
}
let main = if cx.signed_in() { "Neked ajánljuk" } else { "Ajánlott" };
let feed_lines = self.feed.lines(main, shorts);
let feed_failed = matches!(self.feed.load, Load::Failed(_));
if self.needs_extra() {
self.load_extra(cx);
if feed_failed {
lines.extend(feed_lines);
}
match &self.extra {
Some(Load::Ready(rows)) => {
for (i, (title, items)) in rows.iter().enumerate() {
lines.push(L::cards(format!("extra-{i}"), title.clone(), "landscape", cards(items, shorts)).captions());
}
if rows.is_empty() {
lines.push(L::notice("empty", "info", "Itt még üres", "Keress rá valamire, vagy jelentkezz be a Beállításokban."));
}
}
Some(other) => lines.extend(other.status("extra-status")),
None => {}
}
} else {
lines.extend(feed_lines);
}
Spec { lines, frame: Frame { nav: Some(0), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
let item = self.item(cx, key);
let queue = if let Some(i) = line.strip_prefix("extra-").and_then(|n| n.parse::<usize>().ok()) {
match &self.extra {
Some(Load::Ready(rows)) => rows.get(i).map(|r| screens::queue_after(&r.1, key)).unwrap_or_default(),
_ => Vec::new(),
}
} else if line == "continue" {
Vec::new()
} else {
self.feed.queue(line, key)
};
screens::open_card(cx, key, item, queue);
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
let item = self.item(cx, key);
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<Home>(cx, list, Home::paged);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

119
src/screens/library.rs Normal file
View File

@@ -0,0 +1,119 @@
//! Könyvtár: what this TV watched, and signed in, the account's lists:
//! YouTube history, Később megnézendő, Kedvelt videók, own playlists.
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Ch, Frame, L, Spec};
use crate::screens::{self, Load, cards, video_card};
use crate::yt::{Feed, Item};
/// The account's rows: (line id, title, what to load).
const ROWS: [(&str, &str, &str); 4] = [("wl", "Később megnézendő", "WL"), ("ll", "Kedvelt videók", "LL"), ("yth", "YouTube-előzmények", "history"), ("lists", "Lejátszási listáid", "library")];
pub struct Library {
rows: Vec<Load<Vec<Item>>>,
started: bool,
}
impl Library {
pub fn new() -> Library {
Library { rows: ROWS.iter().map(|_| Load::Loading).collect(), started: false }
}
fn start(&mut self, cx: &Cx) {
if self.started || !cx.signed_in() {
return;
}
self.started = true;
for (i, (_, _, what)) in ROWS.iter().enumerate() {
let client = cx.client();
let what = what.to_string();
cx.spawn::<Library, _>(
move || -> anyhow::Result<Vec<Item>> {
let f: Feed = match what.as_str() {
"history" => client.history()?,
"library" => client.library()?,
id => client.playlist(id, true)?,
};
let items = f.flat();
// The library page lists playlists; the others videos.
Ok(if what == "library" { items.into_iter().filter(|i| matches!(i, Item::Playlist(_))).collect() } else { items })
},
move |s, cx, r| s.rows[i] = Load::from(r, cx),
);
}
}
fn row_items(&self, line: &str) -> Vec<Item> {
ROWS.iter().position(|r| r.0 == line).and_then(|i| self.rows[i].ready().cloned()).unwrap_or_default()
}
fn local_items(cx: &Cx) -> Vec<Item> {
cx.library().history.iter().take(60).map(|w| Item::Video(w.video())).collect()
}
}
impl Screen for Library {
fn spec(&mut self, cx: &Cx) -> Spec {
self.start(cx);
let mut lines = Vec::new();
let local: Vec<_> = cx.library().history.iter().take(60).map(|w| video_card(&w.video())).collect();
if local.is_empty() {
lines.push(L::page_title("title", "Könyvtár", "Amit ezen a TV-n nézel, itt jelenik meg."));
} else {
lines.push(L::cards("local", "Ezen a TV-n nézted", "landscape", local).captions());
}
if cx.signed_in() {
for (i, (id, title, _)) in ROWS.iter().enumerate() {
match &self.rows[i] {
Load::Ready(items) if items.is_empty() => {}
Load::Ready(items) => {
let row = cards(items, true);
lines.push(L::cards(*id, *title, "landscape", row).captions());
}
Load::Loading => lines.push(L::text(format!("{id}-status"), format!("{title}: betöltés…"), "caption")),
Load::Failed(e) => lines.push(L::notice(format!("{id}-status"), "bad", format!("{title}: nem sikerült betölteni"), e.clone())),
}
}
if ROWS.iter().enumerate().all(|(i, _)| self.rows[i].ready().is_some_and(|r| r.is_empty())) {
lines.push(L::notice("empty", "info", "A fiókod listái üresek", "A Később megnézendő, a kedvelt videók és a lejátszási listáid jelennek meg itt."));
}
} else {
lines.push(L::notice(
"signin-note",
"info",
"Jelentkezz be a listáidért",
"Bejelentkezve itt vannak a Később megnézendő videóid, a kedvelt videók, a YouTube-előzményeid és a lejátszási listáid.",
));
lines.push(L::chips("signin", "", vec![Ch::new("signin", "Bejelentkezés QR-kóddal").icon("user").tone("primary")]));
}
Spec { lines, frame: Frame { nav: Some(2), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
if line == "signin" {
cx.c.sign_in();
return;
}
let items = if line == "local" { Library::local_items(cx) } else { self.row_items(line) };
let id = key.split(':').nth(1).unwrap_or_default();
let item = items.iter().find(|i| i.id() == id).cloned();
// Opening the account's own list (WL, LL) from the row title isn't a
// card; videos play with the rest of the row after them.
screens::open_card(cx, key, item, if line == "local" { Vec::new() } else { screens::queue_after(&items, key) });
}
fn focus(&mut self, cx: &Cx, line: &str, key: &str) {
let items = if line == "local" { Library::local_items(cx) } else { self.row_items(line) };
let id = key.split(':').nth(1).unwrap_or_default();
let item = items.into_iter().find(|i| i.id() == id);
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn shown(&mut self, _cx: &Cx) {}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

349
src/screens/mod.rs Normal file
View File

@@ -0,0 +1,349 @@
//! 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()
}
}

104
src/screens/playlist.rs Normal file
View File

@@ -0,0 +1,104 @@
//! A playlist: Lejátszás (in order), Keverve (shuffled), and its videos.
//! The account's own lists (WL, LL, private ones) load with the account.
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Ch, Frame, L, Spec};
use crate::player::{QUEUE_MAX, Request};
use crate::screens::{self, Paged};
use crate::yt::Video;
pub struct PlaylistPage {
id: String,
title: String,
feed: Paged,
}
impl PlaylistPage {
pub fn new(id: &str, title: &str) -> PlaylistPage {
let personal = matches!(id, "WL" | "LL");
PlaylistPage { id: id.into(), title: title.into(), feed: Paged::new("pl", false, personal) }
}
fn paged(s: &mut PlaylistPage) -> &mut Paged {
&mut s.feed
}
fn videos(&self) -> Vec<Video> {
self.feed.feed().map(|f| f.videos().filter(|v| !v.live).cloned().collect()).unwrap_or_default()
}
}
/// A cheap shuffle (no rand crate): sorts by a hash of the id and the time.
fn shuffle(v: &mut [Video]) {
use std::hash::{Hash, Hasher};
let seed = crate::yt::now();
v.sort_by_cached_key(|x| {
let mut h = std::collections::hash_map::DefaultHasher::new();
(seed, &x.id).hash(&mut h);
h.finish()
});
}
impl Screen for PlaylistPage {
fn spec(&mut self, cx: &Cx) -> Spec {
let client = cx.client();
let id = self.id.clone();
let personal = matches!(id.as_str(), "WL" | "LL");
let signed_in = cx.signed_in();
self.feed.start::<PlaylistPage>(cx, PlaylistPage::paged, move || {
let f = client.playlist(&id, personal)?;
// A private list of the account: only with it.
if f.is_empty() && signed_in && !personal { client.playlist(&id, true) } else { Ok(f) }
});
let header = self.feed.feed().and_then(|f| f.header.clone()).unwrap_or_default();
if !header.title.is_empty() {
self.title = header.title.clone();
}
let n = self.videos().len();
let mut lines = vec![L::page_title("title", self.title.clone(), if header.meta.is_empty() && n > 0 { format!("{n} videó") } else { header.meta.clone() })];
if n > 0 {
lines.push(L::chips("actions", "", vec![Ch::new("play", "Lejátszás").icon("play").tone("primary"), Ch::new("shuffle", "Keverve").icon("refresh")]));
}
lines.extend(self.feed.lines("Videók", true));
if self.feed.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "A lista üres", "Ebben a listában nincs lejátszható videó."));
}
Spec { lines, frame: Frame::default() }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
match (line, key) {
("actions", "play" | "shuffle") => {
let mut v = self.videos();
if key == "shuffle" {
shuffle(&mut v);
}
if v.is_empty() {
return;
}
let first = v.remove(0);
v.truncate(QUEUE_MAX);
cx.play(Request::new(first, v));
}
_ => {
screens::open_card(cx, key, self.feed.find(key), self.feed.queue(line, key));
}
}
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
if let Some(item) = self.feed.find(key) {
screens::focus_backdrop(cx, Some(&item), key);
}
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<PlaylistPage>(cx, list, PlaylistPage::paged);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

91
src/screens/search.rs Normal file
View File

@@ -0,0 +1,91 @@
//! Keresés: the on-screen keyboard and the results (videos, channels,
//! playlists), more as the focus nears the end.
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Frame, Kind, L, Spec};
use crate::screens::{self, Load, Paged};
pub struct Search {
searched: String,
result: Option<Paged>,
}
impl Search {
pub fn new() -> Search {
Search { searched: String::new(), result: None }
}
fn paged(s: &mut Search) -> &mut Paged {
s.result.get_or_insert_with(|| Paged::new("res", true, false))
}
}
impl Screen for Search {
fn spec(&mut self, cx: &Cx) -> Spec {
let shorts = cx.settings().shorts;
let mut lines = vec![L::page_title("title", "Keresés", "Videók, csatornák és lejátszási listák."), L::new("kb", Kind::Keyboard)];
match &self.result {
None => lines.push(L::notice("hint", "info", "Kezdj el gépelni", "A találatok gépelés közben jönnek; a Keresés gomb azonnal keres.")),
Some(p) => {
let res = p.lines(&format!("Találatok · {}", self.searched), shorts);
if p.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "Erre nincs találat", "Próbáld másképp írni."));
} else {
lines.extend(res);
}
}
}
Spec { lines, frame: Frame { nav: Some(3), keyboard: Some("Mit keresel?".into()), ..Frame::default() } }
}
fn query(&mut self, cx: &Cx, text: &str, submit: bool) {
let q = text.trim().to_string();
if q.chars().count() < 2 {
if !submit {
self.result = None;
self.searched.clear();
cx.refresh();
}
return;
}
if q == self.searched {
return;
}
self.searched = q.clone();
let mut p = Paged::new("res", true, false);
p.begin();
self.result = Some(p);
let client = cx.client();
cx.spawn::<Search, _>(move || (client.search(&q), q), |s, cx, (r, q)| {
// Only the latest search counts.
if s.searched == q {
if let Some(p) = s.result.as_mut() {
p.load = Load::from(r, cx);
}
}
});
cx.refresh();
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
let Some(p) = &self.result else { return };
screens::open_card(cx, key, p.find(key), p.queue(line, key));
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
let item = self.result.as_ref().and_then(|p| p.find(key));
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn more(&mut self, cx: &Cx, list: &str) {
if let Some(p) = self.result.as_mut() {
p.more::<Search>(cx, list, Search::paged);
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

154
src/screens/settings.rs Normal file
View File

@@ -0,0 +1,154 @@
//! Beállítások: Fiók (QR sign-in), Lejátszás, Megjelenés, Adatok, Névjegy.
use std::any::Any;
use crate::app::{Cx, SETTINGS, Screen};
use crate::config;
use crate::page::{Ch, Frame, L, Spec};
const TABS: [&str; 5] = ["Fiók", "Lejátszás", "Megjelenés", "Adatok", "Névjegy"];
pub struct Settings {
tab: usize,
}
impl Settings {
pub fn new() -> Settings {
Settings { tab: 0 }
}
}
fn choice<T: PartialEq + Copy>(line: &str, label: &str, options: &[(T, &str)], current: T, key: impl Fn(T) -> String) -> L {
L::chips(line, label, options.iter().map(|(v, text)| Ch::new(key(*v), *text).active(*v == current)).collect())
}
fn on_off(line: &str, label: &str, on: bool) -> L {
choice(line, label, &[(true, "Bekapcsolva"), (false, "Kikapcsolva")], on, |v| if v { "on".into() } else { "off".into() })
}
impl Screen for Settings {
fn spec(&mut self, cx: &Cx) -> Spec {
let s = cx.settings();
let mut lines = Vec::new();
match self.tab {
0 => {
let a = cx.account();
if a.signed_in() {
lines.push(L::page_title("title", "Fiók", if a.name.is_empty() { "Bejelentkezve".to_string() } else { a.name.clone() }));
lines.push(L::notice(
"on",
"good",
"Bejelentkezve a YouTube-fiókoddal",
"A kezdőlap a fiókod ajánlásai, a Feliratkozások és a Könyvtár a fiókod adatai. Amit itt nézel, bekerül a YouTube-előzményeidbe.",
));
lines.push(L::chips("account", "", vec![Ch::new("signout", "Kijelentkezés").icon("close").tone("danger")]));
} else {
lines.push(L::page_title("title", "Fiók", "Nincs bejelentkezve"));
lines.push(L::notice(
"off",
"info",
"Bejelentkezés telefonnal",
"A TV egy kódot és egy QR-kódot mutat. Olvasd be a telefonoddal (vagy nyisd meg a youtube.com/activate oldalt), és erősítsd meg a fiókodat. Jelszót nem kell beírni a TV-n.",
));
lines.push(L::chips("account", "", vec![Ch::new("signin", "Bejelentkezés QR-kóddal").icon("user").tone("primary")]));
}
}
1 => {
lines.push(L::page_title("title", "Lejátszás", "Minden videóra érvényes; a lejátszóban videónként is állítható."));
lines.push(choice(
"quality",
"Legjobb minőség",
&[(0u64, "Automatikus"), (480, "480p"), (720, "720p"), (1080, "1080p"), (1440, "1440p"), (2160, "4K")],
s.quality,
|v| v.to_string(),
));
lines.push(L::text("quality-note", "Automatikus: legfeljebb 1080p, a hálózathoz igazítva. A 1440p és a 4K csak AV1 kodekkel érhető el.", "caption"));
lines.push(choice("codec", "Kodek", &[("h264", "H.264 · minden TV-n"), ("av1", "AV1 · újabb hardveren")], s.codec.as_str(), |v| v.to_string()));
lines.push(choice("captions", "Felirat", &[("", "Kikapcsolva"), ("hu", "Magyar"), ("en", "Angol")], s.captions.as_str(), |v| if v.is_empty() { "off".into() } else { v.to_string() }));
lines.push(L::text("captions-note", "A videó saját feliratát mutatja ezen a nyelven (kézit, ha van, különben az automatikusat). A lejátszóban bármelyik felirat választható.", "caption"));
lines.push(on_off("sponsorblock", "Szponzorált részek átugrása (SponsorBlock)", s.sponsorblock));
lines.push(on_off("autoplay", "Következő videó automatikusan", s.autoplay));
lines.push(choice("shorts", "Shorts", &[(true, "Megjelenik"), (false, "Elrejtve")], s.shorts, |v| if v { "on".into() } else { "off".into() }));
}
2 => {
lines.push(L::page_title("title", "Megjelenés", "Az üveghatás erőssége ezen a TV-n."));
lines.push(choice(
"glass",
"Üveg",
&[("auto", "Automatikus"), ("full", "Teljes"), ("light", "Könnyű"), ("off", "Matt")],
s.glass.as_str(),
|v| v.to_string(),
));
lines.push(L::text("glass-note", "Automatikus: a TV a grafikus chip alapján választ. Gyengébb gépen a Matt a leggyorsabb.", "caption"));
}
3 => {
let (history, subs) = {
let l = cx.library();
(l.history.len(), l.subs.len())
};
lines.push(L::page_title("title", "Adatok", "Amit az app ezen a TV-n tárol."));
lines.push(L::item("history", "Előzmények ezen a TV-n", format!("{history} videó"), "A Folytatás sorhoz és a Könyvtárhoz.", vec![Ch::new("clear", "Törlés").icon("delete").enabled(history > 0)]));
lines.push(L::item(
"subs",
"Feliratkozások ezen a TV-n",
format!("{subs} csatorna"),
"Bejelentkezés nélkül ezek a csatornák látszanak a Feliratkozásokban.",
vec![Ch::new("clear", "Törlés").icon("delete").enabled(subs > 0)],
));
}
_ => {
lines.push(L::page_title("title", "YouTube", format!("Fennec OS · {}. verzió", env!("CARGO_PKG_VERSION"))));
lines.push(L::notice(
"ads",
"good",
"Reklámok nélkül",
"Az app a YouTube saját felületéről kéri a videókat, de a hirdetéseket nem kéri le és nem játssza le, a hirdetéskártyákat pedig kihagyja.",
));
lines.push(L::text(
"credits",
"Videók: YouTube (InnerTube). Az aláírások megoldása: yt-dlp ejs (Unlicense), QuickJS-ben. Szponzorált részek: SponsorBlock (sponsor.ajay.app).",
"caption",
));
}
}
Spec { lines, frame: Frame { nav: Some(SETTINGS), side: Some(("Beállítások".into(), TABS.iter().map(|t| t.to_string()).collect(), self.tab)), ..Frame::default() } }
}
fn side(&mut self, _cx: &Cx, i: usize) {
self.tab = i;
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
let mut s = cx.settings();
match line {
"account" if key == "signin" => return cx.c.sign_in(),
"account" if key == "signout" => return cx.c.signed_out(false),
"quality" => s.quality = key.parse().unwrap_or(0),
"codec" => s.codec = key.into(),
"captions" => s.captions = if key == "off" { String::new() } else { key.into() },
"sponsorblock" => s.sponsorblock = key == "on",
"autoplay" => s.autoplay = key == "on",
"shorts" => s.shorts = key == "on",
"glass" => {
s.glass = key.into();
config::apply_look(&cx.c.glass, key);
}
"history" => {
cx.update_library(|l| l.history.clear());
cx.toast("Előzmények törölve");
return;
}
"subs" => {
cx.update_library(|l| l.subs.clear());
cx.toast("Feliratkozások törölve");
return;
}
_ => return,
}
cx.set_settings(s);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

164
src/screens/subs.rs Normal file
View File

@@ -0,0 +1,164 @@
//! Feliratkozások. Signed in: the account's subscriptions feed. Signed out:
//! the channels followed on this TV and their latest videos (from each
//! channel's RSS feed, newest first).
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{C, Frame, GRID_YT, L, Spec, grid_lines};
use crate::screens::{self, Load, Paged, video_card};
use crate::yt::{Item, Video};
pub struct Subs {
feed: Paged,
local: Option<Load<Vec<Video>>>,
}
impl Subs {
pub fn new() -> Subs {
Subs { feed: Paged::new("subs", false, true), local: None }
}
fn paged(s: &mut Subs) -> &mut Paged {
&mut s.feed
}
fn load_local(&mut self, cx: &Cx) {
if self.local.is_some() {
return;
}
let ids: Vec<String> = cx.library().subs.iter().map(|s| s.id.clone()).collect();
if ids.is_empty() {
self.local = Some(Load::Ready(Vec::new()));
return;
}
self.local = Some(Load::Loading);
let client = cx.client();
cx.spawn::<Subs, _>(
move || {
let mut all: Vec<(String, Video)> = Vec::new();
let mut err = None;
// A few channels at a time.
for chunk in ids.chunks(8) {
let handles: Vec<_> = chunk
.iter()
.map(|id| {
let (c, id) = (client.clone(), id.clone());
std::thread::spawn(move || crate::yt::extras::channel_feed(&c, &id))
})
.collect();
for h in handles {
match h.join() {
Ok(Ok(v)) => all.extend(v),
Ok(Err(e)) => err = Some(e),
Err(_) => {}
}
}
}
if all.is_empty() {
if let Some(e) = err {
return Err(e);
}
}
all.sort_by(|a, b| b.0.cmp(&a.0));
Ok(all.into_iter().map(|(_, v)| v).take(120).collect())
},
|s, cx, r| s.local = Some(Load::from(r, cx)),
);
}
fn local_items(&self) -> Vec<Item> {
match &self.local {
Some(Load::Ready(v)) => v.iter().cloned().map(Item::Video).collect(),
_ => Vec::new(),
}
}
}
impl Screen for Subs {
fn spec(&mut self, cx: &Cx) -> Spec {
let shorts = cx.settings().shorts;
let mut lines = Vec::new();
if cx.signed_in() {
let client = cx.client();
self.feed.start::<Subs>(cx, Subs::paged, move || client.subscriptions());
lines.extend(self.feed.lines("Legújabb videók", shorts));
if self.feed.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "Nincs új videó", "A fiókod feliratkozásainak videói jelennek meg itt."));
}
} else {
self.load_local(cx);
let subs = cx.library().subs.clone();
if subs.is_empty() {
lines.push(L::page_title("title", "Feliratkozások", "Ezen a TV-n még nem iratkoztál fel egy csatornára sem."));
lines.push(L::notice(
"how",
"info",
"Így iratkozhatsz fel",
"Nyiss meg egy csatornát (egy videó alatt vagy a keresőben), és nyomd meg a Feliratkozás gombot. Ha bejelentkezel, a fiókod feliratkozásai látszanak itt.",
));
lines.push(L::chips("signin", "", vec![crate::page::Ch::new("signin", "Bejelentkezés QR-kóddal").icon("user").tone("primary")]));
} else {
let channels: Vec<C> = subs
.iter()
.map(|s| {
let mut c = C::new(format!("c:{}", s.id), s.title.clone(), s.thumb.clone());
c.caption = s.title.clone();
c.round = true;
c
})
.collect();
lines.push(L::cards("channels", "Csatornáid", "landscape", channels).captions());
match &self.local {
Some(Load::Ready(v)) => {
let cards = v.iter().filter(|v| shorts || !v.short).map(video_card).collect();
lines.extend(grid_lines("subs-grid", "Legújabb videók", "landscape", cards, GRID_YT));
}
Some(other) => lines.extend(other.status("local-status")),
None => {}
}
}
}
Spec { lines, frame: Frame { nav: Some(1), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
if line == "signin" {
cx.c.sign_in();
return;
}
if cx.signed_in() {
screens::open_card(cx, key, self.feed.find(key), self.feed.queue(line, key));
} else {
let items = self.local_items();
let id = key.split(':').nth(1).unwrap_or_default();
let item = items.iter().find(|i| i.id() == id).cloned();
let title = cx.library().subs.iter().find(|s| s.id == id).map(|s| s.title.clone());
let item = item.or_else(|| title.map(|t| Item::Channel(crate::yt::parse::Channel { id: id.into(), title: t, ..Default::default() })));
screens::open_card(cx, key, item, screens::queue_after(&items, key));
}
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
let item = if cx.signed_in() { self.feed.find(key) } else { self.local_items().into_iter().find(|i| key.ends_with(i.id())) };
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<Subs>(cx, list, Subs::paged);
}
fn shown(&mut self, cx: &Cx) {
// Followed or dropped a channel meanwhile.
if !cx.signed_in() {
let have = matches!(&self.local, Some(Load::Ready(_)));
if have {
self.local = None;
}
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}