S025: yt-dlp video sites: finder, probe, run, error kinds, video page, test file

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-25 22:40:06 -06:00
commit b01c24244f
9 changed files with 851 additions and 9 deletions

View file

@ -12,13 +12,13 @@ FEATURES 6.1 with the system's yt-dlp (D-011).
- `yt-dlp --help` (format, output, progress parts)
## Steps
- [ ] Finder and version check, missing and too-old states in plain words
- [ ] Probe to JSON: formats, audio, subtitles, chapters, playlists; cached and cancellable
- [ ] Add dialog page: quality choice with sizes, audio only, subtitles, playlist picker
- [ ] Run as a task: progress template parsed to parts and speed, pause by stop and resume, limits passed on, cookies through a private temp file
- [ ] Errors mapped to kinds: private, removed, region, login, unsupported, too many requests; DRM refused
- [ ] Test file `docs/tests/S025-video-sites.md`, with the checks below
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S025: …`, push
- [x] Finder and version check, missing and too-old states in plain words
- [x] Probe to JSON: formats, audio, subtitles, chapters, playlists; cached and cancellable
- [x] Add dialog page: quality choice with sizes, audio only, subtitles, playlist picker
- [x] Run as a task: progress template parsed to parts and speed, pause by stop and resume, limits passed on, cookies through a private temp file
- [x] Errors mapped to kinds: private, removed, region, login, unsupported, too many requests; DRM refused
- [x] Test file `docs/tests/S025-video-sites.md`, with the checks below
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S025: …`, push
## End criteria
`nice cargo check -q -j 2 -p medlar` clean

View file

@ -44,7 +44,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
## 06 Media
- [ ] [S025](06%20Media/S025-video-sites.md) Video sites through yt-dlp
- [x] [S025](06%20Media/S025-video-sites.md) Video sites through yt-dlp
## 07 Library and tools

View file

@ -15,3 +15,4 @@ pub mod queues;
pub mod rail;
pub mod schedule;
pub mod settings;
pub mod video;

View file

@ -0,0 +1,147 @@
//! The Add dialog's page for a video site: quality with sizes, audio only, subtitles, the videos of a playlist.
//! It holds what was asked and what was chosen; `choice` gives the core what to run. The dialog owns the probe's task.
use crate::theme::Theme;
use crate::tokens::{space, text};
use crate::ui::odometer::amount;
use crate::ui::widgets::Choice as Pick;
use eframe::egui::{RichText, ScrollArea, Ui};
use medlar_core::ytdlp::{Choice, Probe, Quality};
use medlar_core::{strings, tr};
use std::sync::Arc;
/// Rows of the playlist that are seen at once.
const SEEN: f32 = 220.0;
/// Where the page is.
pub enum Page {
Looking,
/// In plain words, what failed and why.
Failed(String),
Ready(Box<Video>),
}
pub struct Video {
probe: Arc<Probe>,
qualities: Vec<Quality>,
quality: usize,
audio_only: bool,
/// Subtitles by language: what is offered, and whether it is wanted.
subtitles: Vec<(String, bool)>,
/// One for each video of a playlist.
picked: Vec<bool>,
}
impl Video {
pub fn new(probe: Arc<Probe>) -> Video {
let qualities = probe.qualities();
let subtitles = probe
.subtitles
.iter()
.map(|l| (l.clone(), false))
.chain(probe.automatic.iter().filter(|l| !probe.subtitles.contains(l)).map(|l| (l.clone(), false)))
.collect();
let picked = vec![true; probe.entries.len()];
Video { probe, qualities, quality: 0, audio_only: false, subtitles, picked }
}
pub fn probe(&self) -> &Probe {
&self.probe
}
/// Nothing of a playlist is wanted.
pub fn empty(&self) -> bool {
self.probe.is_playlist() && !self.picked.contains(&true)
}
pub fn choice(&self) -> Choice {
let playlist = self.probe.is_playlist();
let all = self.picked.iter().all(|p| *p);
Choice {
height: self.qualities.get(self.quality).and_then(|q| q.height),
audio_only: self.audio_only,
subtitles: self.subtitles.iter().filter(|(_, on)| *on).map(|(l, _)| l.clone()).collect(),
items: (playlist && !all).then(|| ranges(&self.picked)),
playlist,
}
}
pub fn show(&mut self, ui: &mut Ui, t: &Theme) {
let small = |s: String| RichText::new(s).size(text::LABEL).color(t.on_variant);
ui.label(RichText::new(&self.probe.title).size(text::TITLE).color(t.on_surface));
let mut facts = vec![];
facts.extend(self.probe.uploader.clone());
if self.probe.is_playlist() {
facts.push(tr!("video.entries", count = self.probe.entries.len()));
}
if !self.probe.chapters.is_empty() {
facts.push(tr!("video.chapters", count = self.probe.chapters.len()));
}
if !facts.is_empty() {
ui.label(small(facts.join(" · ")));
}
ui.add_space(space::M);
ui.label(small(tr!("video.quality")));
for (i, q) in self.qualities.iter().enumerate() {
let label = match q.size {
Some(size) => tr!("video.size", quality = q.label, size = amount(size)),
None => q.label.clone(),
};
if Pick::new(&label).enabled(!self.audio_only).radio(ui, t, self.quality == i).clicked() {
self.quality = i;
}
}
Pick::new(&tr!("video.audio_only")).checkbox(ui, t, &mut self.audio_only);
if !self.subtitles.is_empty() {
ui.add_space(space::M);
ui.label(small(tr!("video.subtitles")));
let automatic = &self.probe.automatic;
let made = &self.probe.subtitles;
ScrollArea::vertical().id_salt("video-subs").max_height(SEEN / 2.0).show(ui, |ui| {
for (language, on) in &mut self.subtitles {
let label = if made.contains(language) || !automatic.contains(language) { language.clone() } else { tr!("video.automatic", language = language) };
Pick::new(&label).checkbox(ui, t, on);
}
});
}
if self.probe.is_playlist() {
ui.add_space(space::M);
ui.horizontal(|ui| {
ui.label(small(tr!("video.playlist")));
if ui.link(strings::text("video.all", &[])).clicked() {
self.picked.fill(true);
}
if ui.link(strings::text("video.none", &[])).clicked() {
self.picked.fill(false);
}
});
ScrollArea::vertical().id_salt("video-entries").max_height(SEEN).show(ui, |ui| {
for (entry, on) in self.probe.entries.iter().zip(&mut self.picked) {
Pick::new(&entry.title).checkbox(ui, t, on);
}
});
}
}
}
/// `1,3-5` for the videos that are picked.
fn ranges(picked: &[bool]) -> String {
let mut parts: Vec<String> = vec![];
let mut i = 0;
while i < picked.len() {
if !picked[i] {
i += 1;
continue;
}
let from = i;
while i + 1 < picked.len() && picked[i + 1] {
i += 1;
}
parts.push(if from == i { (from + 1).to_string() } else { format!("{}-{}", from + 1, i + 1) });
i += 1;
}
parts.join(",")
}

View file

@ -822,5 +822,32 @@
"incoming.differs": "The new link for {name} was not used: {why}",
"incoming.added": "Added {n} from the browser.",
"incoming.no_start": "The browser port could not start: {why}",
"unit.mb_short": "MB"
"unit.mb_short": "MB",
"video.missing": "Video sites need the program yt-dlp, which is not on this computer. Install it, then try again.",
"video.old": "The yt-dlp on this computer ({version}) is too old. Update it, then try again.",
"video.broken": "The yt-dlp on this computer does not answer. Reinstall it, then try again.",
"video.best": "Best",
"video.title": "Video",
"video.looking": "Asking the site what it offers",
"video.quality": "Quality",
"video.audio_only": "Audio only",
"video.subtitles": "Subtitles",
"video.automatic": "{language} (automatic)",
"video.playlist": "Playlist",
"video.chapters": "{count} chapters",
"video.entries": "{count} videos",
"video.all": "All videos",
"video.none": "None",
"video.size": "{quality}, about {size}",
"error.video.missing": "Video sites need the program yt-dlp, which is not on this computer. Install it, then try again.",
"error.video.old": "The yt-dlp on this computer is too old. Update it, then try again.",
"error.video.broken": "The yt-dlp on this computer does not answer. Reinstall it, then try again.",
"error.video.private": "This video is private. Sign in with an account that may see it.",
"error.video.login": "The site wants you signed in. Give Medlar the cookies of a signed-in browser, then try again.",
"error.video.removed": "The video has been removed or is not there any more.",
"error.video.region": "The site does not show this video in your country.",
"error.video.unsupported": "Medlar's video tool does not know this site or page.",
"error.video.many": "The site says there were too many requests. Wait a while, then try again.",
"error.video.drm": "This video is protected against copying, and Medlar will not get around that.",
"error.video.other": "The video could not be downloaded. The log has the details."
}

View file

@ -45,5 +45,6 @@ pub mod strings;
pub mod tls;
mod transport;
pub mod verify;
pub mod ytdlp;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

622
crates/core/src/ytdlp.rs Normal file
View file

@ -0,0 +1,622 @@
//! Video sites through the yt-dlp that is on this computer: finding it, asking what a page offers, running it, stopping it.
//!
//! Links come after `--`, never in a shell; its config files are ignored; cookies go through a private temporary file that is
//! removed again. What it says is mapped to `Reason`s; its own words go to the log only, without secrets.
use crate::http::{Error, Result};
use crate::model::ErrorKind;
use crate::redact;
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::watch;
/// The oldest release that is known to work with what is asked of it, as year, month, day.
pub const OLDEST: (u32, u32, u32) = (2023, 7, 6);
/// Lines of its log that are kept.
const TAIL: usize = 40;
/// Longer lines are cut.
const LINE: u64 = 8192;
/// What it says about one page is kept this long.
const KEEP: Duration = Duration::from_secs(600);
/// A probe's answer is not larger.
const MOST: usize = 64 << 20;
/// The marks of what it prints for us.
const MARK: &str = "MEDLAR:";
const FILE: &str = "MEDLAR-FILE:";
/// Why it can't be used.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Problem {
Missing,
TooOld(String),
/// It is there but does not answer.
Broken,
}
impl Problem {
pub fn words(&self) -> String {
match self {
Problem::Missing => crate::tr!("video.missing"),
Problem::TooOld(version) => crate::tr!("video.old", version = version),
Problem::Broken => crate::tr!("video.broken"),
}
}
pub fn error(&self) -> Error {
Error::because(ErrorKind::Tool, match self {
Problem::Missing => "error.video.missing",
Problem::TooOld(_) => "error.video.old",
Problem::Broken => "error.video.broken",
})
}
}
/// A yt-dlp that works.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ytdlp {
path: PathBuf,
pub version: String,
}
impl Ytdlp {
/// Next to Medlar first, then where programs are; asks it for its version.
pub async fn find() -> std::result::Result<Ytdlp, Problem> {
let beside = std::env::current_exe().ok().and_then(|exe| Some(exe.parent()?.to_path_buf()));
let path = std::env::var_os("PATH").unwrap_or_default();
let path = locate(beside.as_deref(), &path).ok_or(Problem::Missing)?;
Ytdlp::at(path).await
}
/// The program at `path`, if it is a recent enough yt-dlp.
pub async fn at(path: PathBuf) -> std::result::Result<Ytdlp, Problem> {
let mut command = base(&path);
command.arg("--version").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null());
let out = tokio::time::timeout(Duration::from_secs(15), command.output()).await;
let out = out.ok().and_then(|o| o.ok()).filter(|o| o.status.success()).ok_or(Problem::Broken)?;
let version = String::from_utf8_lossy(&out.stdout).trim().to_string();
match date(&version) {
Some(d) if d >= OLDEST => Ok(Ytdlp { path, version }),
Some(_) => Err(Problem::TooOld(version)),
None => Err(Problem::Broken),
}
}
pub fn path(&self) -> &Path {
&self.path
}
/// Asks what the page offers. Dropping the future (or `cancel` ending) stops the program. Answers are cached for a while;
/// `cookies` is the text of a cookie file, which is not part of the key because a page that needs it is not cached anyway.
pub async fn probe(&self, cache: &Cache, url: &str, cookies: Option<&str>, cancel: impl Future<Output = ()>) -> Result<Arc<Probe>> {
if let Some(found) = cache.get(url) {
return Ok(found);
}
let jar = cookies.map(Jar::new).transpose()?;
let mut command = base(&self.path);
command.args(["--dump-single-json", "--no-warnings", "--flat-playlist", "--ignore-no-formats-error"]);
if let Some(jar) = &jar {
command.arg("--cookies").arg(jar.path());
}
command.arg("--").arg(url).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = command.spawn().map_err(|e| {
log::warn!("yt-dlp does not start: {e}");
Problem::Broken.error()
})?;
let (out, err) = (child.stdout.take().expect("piped"), child.stderr.take().expect("piped"));
let work = async {
let (mut out, mut err) = (out, err);
let (mut json, mut says) = (vec![], vec![]);
let (mut a, mut b) = ((&mut out).take(MOST as u64), (&mut err).take(1 << 16));
let _ = tokio::join!(a.read_to_end(&mut json), b.read_to_end(&mut says));
let status = child.wait().await;
(json, says, status)
};
let (json, says, status) = tokio::select! {
done = work => done,
() = cancel => return Err(Error::Stopped),
};
drop(jar);
let text = String::from_utf8_lossy(&says);
if !status.is_ok_and(|s| s.success()) || json.is_empty() {
let lines: Vec<String> = text.lines().map(|l| redact::text(l.trim())).collect();
log::debug!("yt-dlp probe failed: {}", lines.join(" / "));
return Err(Reason::of(lines.iter().map(String::as_str)).error());
}
let value: Value = serde_json::from_slice(&json).map_err(|_| Reason::Other.error())?;
let probe = Arc::new(Probe::read(&value));
if probe.drm {
return Err(Reason::Drm.error());
}
cache.put(url, probe.clone());
Ok(probe)
}
/// Starts the download. It goes on where the files of the folder say it stopped.
pub fn start(&self, run: &Run) -> Result<Running> {
let jar = run.cookies.as_deref().map(Jar::new).transpose()?;
let mut command = base(&self.path);
command.args(["--newline", "--no-warnings", "--continue"]);
command.args(["--progress", "--progress-template"]);
command.arg(format!(
"download:{MARK}%(progress.downloaded_bytes)s|%(progress.total_bytes)s|%(progress.total_bytes_estimate)s|%(progress.speed)s|%(progress.eta)s|%(progress.fragment_index)s|%(progress.fragment_count)s|%(info.playlist_index)s|%(info.n_entries)s"
));
command.arg("--print").arg(format!("after_move:{FILE}%(filepath)s"));
command.arg("-P").arg(&run.folder).arg("-o").arg(&run.name);
command.args(run.choice.arguments());
if let Some(rate) = run.limit.filter(|r| *r > 0) {
command.arg("--limit-rate").arg(rate.to_string());
}
if let Some(jar) = &jar {
command.arg("--cookies").arg(jar.path());
}
command.arg("--").arg(&run.url);
command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = command.spawn().map_err(|e| {
log::warn!("yt-dlp does not start: {e}");
Problem::Broken.error()
})?;
let (progress, seen) = watch::channel(Progress::default());
let tail = Arc::new(Mutex::new(VecDeque::new()));
let file = Arc::new(Mutex::new(None));
let (out, err) = (child.stdout.take().expect("piped"), child.stderr.take().expect("piped"));
let readers = vec![
tokio::spawn(listen(out, Some(progress), tail.clone(), file.clone())),
tokio::spawn(listen(err, None, tail.clone(), file.clone())),
];
Ok(Running { child, seen, tail, file, readers, _jar: jar })
}
}
fn io(e: std::io::Error) -> Error {
Error::Disk(e.into())
}
fn locate(beside: Option<&Path>, path: &std::ffi::OsStr) -> Option<PathBuf> {
let runs = |p: &PathBuf| p.is_absolute() && p.is_file() && rustix::fs::access(p, rustix::fs::Access::EXEC_OK).is_ok();
beside.map(Path::to_path_buf).into_iter().chain(std::env::split_paths(path)).map(|dir| dir.join("yt-dlp")).find(runs)
}
/// The same start for every run: no config files, no cache, no shell, the user's proxy not passed on by accident.
fn base(path: &Path) -> Command {
let mut command = Command::new(path);
command.args(["--ignore-config", "--no-cache-dir", "--no-update", "--no-colors"]);
command.process_group(0).kill_on_drop(true);
for name in ["http_proxy", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"] {
command.env_remove(name);
}
command
}
/// `2024.08.06`, maybe with `.1` or `-nightly` after it.
fn date(version: &str) -> Option<(u32, u32, u32)> {
let mut parts = version.split(|c: char| !c.is_ascii_digit()).filter(|p| !p.is_empty()).map(|p| p.parse::<u32>().ok());
let (y, m, d) = (parts.next()??, parts.next()??, parts.next()??);
(y >= 2000 && (1..=12).contains(&m) && (1..=31).contains(&d)).then_some((y, m, d))
}
/// A cookie file that only we can read, removed when this is dropped.
struct Jar(PathBuf);
impl Jar {
fn new(text: &str) -> Result<Jar> {
let dir = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|d| d.is_dir()).unwrap_or_else(std::env::temp_dir);
let path = dir.join(format!("medlar-{}-{:016x}.cookies", std::process::id(), fastrand_u64()));
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path).map_err(io)?;
file.write_all(text.as_bytes()).map_err(io)?;
Ok(Jar(path))
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Jar {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn fastrand_u64() -> u64 {
use std::hash::{BuildHasher, Hasher};
std::collections::hash_map::RandomState::new().build_hasher().finish() ^ Instant::now().elapsed().as_nanos() as u64
}
/// What a page offers.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Probe {
pub title: String,
pub uploader: Option<String>,
pub duration: Option<f64>,
pub formats: Vec<Format>,
/// Languages of subtitles that people made, and of those that were made by machine.
pub subtitles: Vec<String>,
pub automatic: Vec<String>,
pub chapters: Vec<Chapter>,
/// Not empty for a playlist.
pub entries: Vec<Entry>,
pub drm: bool,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Format {
pub id: String,
pub ext: String,
pub height: Option<u32>,
pub fps: Option<f64>,
/// Both picture and sound.
pub video: bool,
pub audio: bool,
pub size: Option<u64>,
pub bitrate: Option<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Chapter {
pub title: String,
pub start: f64,
pub end: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Entry {
pub title: String,
pub url: Option<String>,
pub duration: Option<f64>,
}
/// One line of the quality choice.
#[derive(Debug, Clone, PartialEq)]
pub struct Quality {
/// `None`: the best there is.
pub height: Option<u32>,
pub label: String,
/// Picture and sound together, when the sites say how large they are.
pub size: Option<u64>,
}
impl Probe {
pub fn is_playlist(&self) -> bool {
!self.entries.is_empty()
}
pub fn read(v: &Value) -> Probe {
let text = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
let number = |v: &Value, k: &str| v.get(k).and_then(Value::as_f64);
let languages = |k: &str| {
let mut all: Vec<String> = v.get(k).and_then(Value::as_object).map(|m| m.keys().cloned().collect()).unwrap_or_default();
// Live chat is not a subtitle.
all.retain(|l| l != "live_chat");
all.sort();
all
};
let formats = v.get("formats").and_then(Value::as_array).map(|a| a.iter().map(format).collect()).unwrap_or_default();
let chapters = v
.get("chapters")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|c| Some(Chapter { title: text(c, "title")?, start: number(c, "start_time")?, end: number(c, "end_time")? }))
.collect()
})
.unwrap_or_default();
let entries = v
.get("entries")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter(|e| e.is_object())
.map(|e| Entry {
title: text(e, "title").unwrap_or_default(),
url: text(e, "webpage_url").or_else(|| text(e, "url")),
duration: number(e, "duration"),
})
.collect()
})
.unwrap_or_default();
let drm = v.get("formats").and_then(Value::as_array).is_some_and(|a| {
!a.is_empty() && a.iter().all(|f| f.get("has_drm").is_some_and(|d| d == true || d == "maybe") || text(f, "format_note").is_some_and(|n| n.contains("DRM")))
});
Probe {
title: text(v, "title").unwrap_or_default(),
uploader: text(v, "uploader").or_else(|| text(v, "channel")),
duration: number(v, "duration"),
formats,
subtitles: languages("subtitles"),
automatic: languages("automatic_captions"),
chapters,
entries,
drm,
}
}
/// The heights that can be had, the largest first, after "best"; each with what picture and sound together weigh.
pub fn qualities(&self) -> Vec<Quality> {
let mut heights: Vec<u32> = self.formats.iter().filter(|f| f.video).filter_map(|f| f.height).collect();
heights.sort_unstable_by(|a, b| b.cmp(a));
heights.dedup();
let audio = self.best_audio().and_then(|f| f.size);
let mut all = vec![Quality { height: None, label: crate::tr!("video.best"), size: self.size_at(None, audio) }];
all.extend(heights.into_iter().map(|h| Quality { height: Some(h), label: format!("{h}p"), size: self.size_at(Some(h), audio) }));
all
}
fn best_audio(&self) -> Option<&Format> {
self.formats.iter().filter(|f| f.audio && !f.video).max_by(|a, b| a.bitrate.partial_cmp(&b.bitrate).unwrap_or(std::cmp::Ordering::Equal))
}
fn size_at(&self, height: Option<u32>, audio: Option<u64>) -> Option<u64> {
let best = self
.formats
.iter()
.filter(|f| f.video && height.is_none_or(|h| f.height == Some(h)))
.max_by(|a, b| (a.height, a.bitrate.map(|b| b as u64)).cmp(&(b.height, b.bitrate.map(|b| b as u64))))?;
let video = best.size?;
Some(if best.audio { video } else { video + audio.unwrap_or(0) })
}
}
fn format(f: &Value) -> Format {
let codec = |k: &str| f.get(k).and_then(Value::as_str).is_some_and(|c| c != "none");
let text = |k: &str| f.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
let size = f.get("filesize").and_then(Value::as_f64).or_else(|| f.get("filesize_approx").and_then(Value::as_f64));
Format {
id: text("format_id"),
ext: text("ext"),
height: f.get("height").and_then(Value::as_u64).map(|h| h as u32),
fps: f.get("fps").and_then(Value::as_f64),
video: codec("vcodec"),
audio: codec("acodec"),
size: size.filter(|s| *s > 0.0).map(|s| s as u64),
bitrate: f.get("tbr").and_then(Value::as_f64),
}
}
/// Answers of probes, for a few minutes.
#[derive(Default)]
pub struct Cache(Mutex<HashMap<String, (Instant, Arc<Probe>)>>);
impl Cache {
fn get(&self, url: &str) -> Option<Arc<Probe>> {
let mut all = self.0.lock().unwrap();
all.retain(|_, (at, _)| at.elapsed() < KEEP);
all.get(url).map(|(_, p)| p.clone())
}
fn put(&self, url: &str, probe: Arc<Probe>) {
let mut all = self.0.lock().unwrap();
if all.len() >= 64 {
all.clear();
}
all.insert(url.to_string(), (Instant::now(), probe));
}
}
/// What the user chose.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Choice {
/// At most this tall; `None` is the best.
pub height: Option<u32>,
pub audio_only: bool,
/// Languages of subtitles to save next to the video.
pub subtitles: Vec<String>,
/// Of a playlist, as yt-dlp writes them (`1,3,5-7`); `None` is all of it, or the video alone if it is not one.
pub items: Option<String>,
pub playlist: bool,
}
impl Choice {
fn arguments(&self) -> Vec<String> {
let mut a: Vec<String> = vec![];
if self.audio_only {
a.extend(["-f", "ba/b", "-x", "--audio-format", "best"].map(String::from));
} else {
let selector = match self.height {
Some(h) => format!("bv*[height<={h}]+ba/b[height<={h}]/bv*+ba/b"),
None => "bv*+ba/b".into(),
};
a.extend(["-f".into(), selector]);
}
let langs: Vec<&str> = self.subtitles.iter().map(String::as_str).filter(|l| l.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))).collect();
if !langs.is_empty() {
a.extend(["--write-subs".into(), "--write-auto-subs".into(), "--sub-langs".into(), langs.join(",")]);
}
if self.playlist {
a.push("--yes-playlist".into());
if let Some(items) = self.items.as_deref().filter(|i| i.chars().all(|c| c.is_ascii_digit() || matches!(c, ',' | '-' | ':'))) {
a.extend(["--playlist-items".into(), items.into()]);
}
} else {
a.push("--no-playlist".into());
}
a
}
}
/// What to run.
#[derive(Debug, Clone, Default)]
pub struct Run {
pub url: String,
pub folder: PathBuf,
/// yt-dlp's output template; the default keeps the title and the extension it knows.
pub name: String,
pub choice: Choice,
/// Bytes a second.
pub limit: Option<u64>,
/// The text of a cookie file. It is written to a private file for the length of the run.
pub cookies: Option<String>,
}
impl Run {
pub const NAME: &'static str = "%(title).150B [%(id)s].%(ext)s";
}
/// Where it is, as the progress lines say.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Progress {
pub done: u64,
pub total: Option<u64>,
/// Bytes a second.
pub speed: Option<f64>,
pub eta: Option<u64>,
/// The part of a fragmented download, as `(this, of)`.
pub fragment: Option<(u32, u32)>,
/// The video of a playlist, as `(this, of)`.
pub item: Option<(u32, u32)>,
}
impl Progress {
/// A line it printed for us, without the mark. `None` if it is not one.
pub fn read(line: &str) -> Option<Progress> {
let rest = line.strip_prefix(MARK)?;
let f: Vec<&str> = rest.split('|').collect();
let n = |i: usize| f.get(i).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| *v >= 0.0);
let pair = |a: usize, b: usize| Some((n(a)? as u32, n(b)? as u32));
Some(Progress {
done: n(0).unwrap_or(0.0) as u64,
total: n(1).or_else(|| n(2)).map(|t| t as u64),
speed: n(3),
eta: n(4).map(|e| e as u64),
fragment: pair(5, 6),
item: pair(7, 8),
})
}
}
/// A running download. Killed when it is dropped; stopping it is how it is paused, and `start` again goes on.
pub struct Running {
child: Child,
seen: watch::Receiver<Progress>,
tail: Arc<Mutex<VecDeque<String>>>,
file: Arc<Mutex<Option<PathBuf>>>,
readers: Vec<tokio::task::JoinHandle<()>>,
_jar: Option<Jar>,
}
impl Running {
pub fn progress(&self) -> watch::Receiver<Progress> {
self.seen.clone()
}
/// Pauses: ends the program, keeps what it has written.
pub async fn stop(mut self) {
let _ = self.child.kill().await;
}
/// Waits for its end. The file is where it moved the result.
pub async fn end(&mut self) -> Result<PathBuf> {
let status = self.child.wait().await.map_err(io)?;
for reader in &mut self.readers {
let _ = tokio::time::timeout(Duration::from_secs(1), reader).await;
}
let tail: Vec<String> = self.tail.lock().unwrap().iter().cloned().collect();
if status.success() {
return self.file.lock().unwrap().clone().ok_or_else(|| Reason::Other.error());
}
log::debug!("yt-dlp failed ({status}): {}", tail.join(" / "));
Err(Reason::of(tail.iter().map(String::as_str)).error())
}
}
async fn listen(
from: impl tokio::io::AsyncRead + Unpin,
progress: Option<watch::Sender<Progress>>,
tail: Arc<Mutex<VecDeque<String>>>,
file: Arc<Mutex<Option<PathBuf>>>,
) {
let mut lines = BufReader::new(from);
let mut line = vec![];
loop {
line.clear();
match (&mut lines).take(LINE).read_until(b'\n', &mut line).await {
Ok(0) | Err(_) => return,
Ok(_) => {}
}
let text = String::from_utf8_lossy(&line);
let text = text.trim();
if let Some(path) = text.strip_prefix(FILE) {
*file.lock().unwrap() = Some(PathBuf::from(path));
} else if let Some(now) = Progress::read(text) {
if let Some(progress) = &progress {
progress.send_replace(now);
}
} else if !text.is_empty() {
let mut tail = tail.lock().unwrap();
if tail.len() == TAIL {
tail.pop_front();
}
tail.push_back(redact::text(text));
}
}
}
/// What went wrong, in the terms a person can act on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reason {
Private,
Removed,
Region,
Login,
Unsupported,
TooManyRequests,
/// Protected by DRM: never worked around.
Drm,
Other,
}
impl Reason {
/// From the lines it printed, the later ones first. Lowercase comparison.
pub fn of<'a>(lines: impl DoubleEndedIterator<Item = &'a str>) -> Reason {
const KNOWN: [(&str, Reason); 22] = [
("drm", Reason::Drm),
("private video", Reason::Private),
("this video is private", Reason::Private),
("unsupported url", Reason::Unsupported),
("http error 429", Reason::TooManyRequests),
("too many requests", Reason::TooManyRequests),
("not available in your country", Reason::Region),
("blocked it in your country", Reason::Region),
("geo restricted", Reason::Region),
("geo-restricted", Reason::Region),
("who has blocked it", Reason::Region),
("sign in to confirm", Reason::Login),
("sign in", Reason::Login),
("log in", Reason::Login),
("login required", Reason::Login),
("members-only", Reason::Login),
("use --cookies", Reason::Login),
("has been removed", Reason::Removed),
("video unavailable", Reason::Removed),
("no longer available", Reason::Removed),
("does not exist", Reason::Removed),
("http error 404", Reason::Removed),
];
let lines: Vec<String> = lines.map(str::to_lowercase).collect();
// The most telling first: a DRM or private note beats a generic "sign in".
KNOWN.iter().find(|(text, _)| lines.iter().any(|l| l.contains(text))).map_or(Reason::Other, |(_, r)| *r)
}
pub fn error(self) -> Error {
use ErrorKind::*;
let (kind, why) = match self {
Reason::Private => (Login, "error.video.private"),
Reason::Login => (Login, "error.video.login"),
Reason::Removed => (NotFound, "error.video.removed"),
Reason::Region => (Forbidden, "error.video.region"),
Reason::Unsupported => (BadLink, "error.video.unsupported"),
Reason::TooManyRequests => (Rejected, "error.video.many"),
Reason::Drm => (Drm, "error.video.drm"),
Reason::Other => (Media, "error.video.other"),
};
Error::because(kind, why)
}
}

View file

@ -218,3 +218,7 @@ Seen: boxes were ticked together after the tests, against rule 3.
- `views/incoming.rs` `Inbox` (in `App`): starts `Connector`, follows settings, takes arrivals. Awaited task + Likely match: check, then `Continue` by itself; else Add dialog (`literal`, queued, focus only if none open) or direct add when `Settings::auto_ok` (new `auto_types`, `auto_min_mb`, `auto_max_mb`, off by default). `medlar:` and `.metalink` args always show the dialog.
- `instance.rs`: Unix socket per home; second start hands args over and exits (`wants`, `run_with`). `assets/medlar.desktop`. Connector page `views/connector.rs` (state, test link, log, Nacre steps).
- Not done: no integration test, no Nacre run, no keyring cleanup change, `.desktop` not installed by any script; a task already in the Add dialog's "Continue" is still the dialog's own logic.
## S025 — Video sites (compiled, not tested)
- `core::ytdlp`: finder and version check (`Problem`), `probe` (cached, cancellable by drop, DRM refused), `Choice`/`Run`, `start` -> `Running` (progress parsed, stop = kill, restart continues), `Reason` mapped to error kinds, cookies in a 0600 temp file. `views/video.rs`: quality/audio/subtitle/playlist page.
- Not done: page not shown by the Add dialog, no manager task kind, limiter not fed live, no cookie-header conversion, no automatic tests or stub. Tests: `docs/tests/S025-video-sites.md`.

View file

@ -0,0 +1,40 @@
# S025 — Video sites through yt-dlp: test file
Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so.
## Built
- `crates/core/src/ytdlp.rs` · `Ytdlp::find/at` (finder, version check), `probe` (JSON, `Cache`, cancel by dropping), `start` -> `Running` (progress, `stop`, `end`), `Choice`, `Run`, `Progress::read`, `Reason::of` (error kinds), private cookie `Jar`.
- `crates/app/src/views/video.rs` · `Page`, `Video` (quality radios with sizes, audio only, subtitles, playlist picker); not yet shown by the Add dialog.
- Strings `video.*`, `error.video.*` in `crates/core/lang/en.json`.
## Checks
| # | Risk | Do this | Expect | How | Result |
|---|---|---|---|---|---|
| 1 | MED | `Ytdlp::find` with no yt-dlp on PATH or beside the test | `Problem::Missing`, words say to install it | unit | — |
| 2 | MED | Stub `--version` prints `2022.01.01` | `Problem::TooOld("2022.01.01")`; `2024.08.06`, `2025.01.01.1` and `2024.08.06-nightly` pass | unit (stub) | — |
| 3 | MED | Stub that exits 1 or prints junk for `--version` | `Problem::Broken` | unit (stub) | — |
| 4 | HIGH | Stub replays a recorded `-J` of one video; call `probe` | formats, sizes, subtitles, automatic captions, chapters read; `qualities()` lists Best then heights descending with video plus best-audio sizes | unit (stub) | — |
| 5 | MED | Probe a recorded playlist | `is_playlist`, entries have titles and urls; `live_chat` is not a subtitle | unit (stub) | — |
| 6 | MED | Probe the same link twice | the stub ran once (cache); after the keep time it runs again | unit (stub) | — |
| 7 | HIGH | Stub sleeps; end the cancel future during `probe` | `Error::Stopped` at once and the stub process is gone | unit (stub) | — |
| 8 | HIGH | Probe a recorded answer whose formats are all `has_drm` | error of kind `Drm`, nothing cached | unit (stub) | — |
| 9 | HIGH | Stub prints recorded progress lines; read `Running::progress` | done, total (or estimate), speed, eta, fragment and playlist item match; `NA` parts are `None` | unit (stub) | — |
| 10 | HIGH | `start`, then `stop`, then `start` again with the same folder | stub sees the same arguments; first process is gone after `stop`; second goes on | unit (stub) | — |
| 11 | HIGH | Stub echoes its arguments | starts with `--ignore-config`; link is last and right after `--`; a link beginning with `-` stays an argument; limit gives `--limit-rate N`; no proxy variables in its environment | unit (stub) | — |
| 12 | HIGH | Run with cookies; stub reports the cookie file's mode and content | mode 600, content equal; file removed after `end` and after drop | unit (stub) | — |
| 13 | HIGH | Recorded failures: private, removed, region, sign-in, unsupported URL, HTTP 429, DRM, unknown | `Reason` is Private, Removed, Region, Login, Unsupported, TooManyRequests, Drm, Other; each error has its own plain text | unit | — |
| 14 | MED | `Choice` with height 720, audio only, subtitles `en,de`, items | format selector with `height<=720`; `-x`; `--write-subs --sub-langs en,de`; odd characters in languages or items dropped | unit | — |
| 15 | MED | `Video` page: pick items 1, 3, 4, 5 of 6 | `choice().items == "1,3-5"`; all picked gives `None`; none picked gives `empty()` | unit | — |
| 16 | LOW | Show the page with a playlist, subtitles and sizes, light and dark | readable, no overlap, list scrolls | screen | — |
| 17 | MED | `#[ignore]` test: real yt-dlp against the test server's generic page (never a real site) | file arrives in the folder, `end` returns its path | integration | — |
## Needs
A stub `yt-dlp` script (shell) that replays recorded outputs chosen by an environment variable and records its arguments; the test server for check 17; a throwaway `XDG_RUNTIME_DIR`. Never a real video site.
## Doubts
- The progress template and `--print after_move:` were written from reading `yt-dlp --help`, not run; check with the real program (check 17).
- `--flat-playlist` for probing gives playlist entries without sizes; a single video link is fully probed.
- Region, login and private are matched by English text in yt-dlp's messages, which may change between releases.
- `Reason::of` matches in list order, not line order; "sign in" may hide other causes.
- Not wired: the Add dialog does not show `video::Page`, and no manager task kind runs `Ytdlp::start`, so the limits of Medlar's limiter are not passed on yet (only a fixed `limit`).
- Cookies come as the text of a Netscape cookie file; nothing yet converts the connector's `Cookie` header.