diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs index f889216..d9fd6b8 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -856,6 +856,8 @@ impl Add { task.checksum = self.checksum_text(); if let Some(Page::Ready(v)) = &self.video { task.video = Some(v.choice()); + // The title until yt-dlp names the file. + task.name = self.name.trim().to_string(); } } (tasks, secrets) diff --git a/crates/app/tests/add.rs b/crates/app/tests/add.rs index 4b7d68e..38e5166 100644 --- a/crates/app/tests/add.rs +++ b/crates/app/tests/add.rs @@ -19,7 +19,10 @@ use medlar_core::paths::Paths; use medlar_core::settings::{Motion, Settings}; use medlar_core::snapshot::TaskView; use medlar_testserver::{Faults, TestServer, expected}; +use medlar_app::views::video::{Page, Video}; +use medlar_core::ytdlp::{Choice as VideoChoice, Probe}; use std::path::{Path, PathBuf}; +use std::sync::Arc; use std::time::{Duration, Instant}; type H = Harness<'static, Option>; @@ -562,3 +565,64 @@ fn a_fresh_link_to_another_file_is_refused() { assert!(app(&mut b.h).main.adding.now().is_none(), "no dialog"); assert_eq!(Bench::state(&b.h, id).unwrap().0, State::Waiting, "the download keeps waiting"); } + +/// What yt-dlp would say of a video, or of a playlist of three. +fn video_page(playlist: bool) -> Page { + let json = if playlist { + r#"{"_type":"playlist","title":"Talks","entries":[{"title":"One","url":"https://v.example.org/1"},{"title":"Two","url":"https://v.example.org/2"},{"title":"Three","url":"https://v.example.org/3"}]}"# + } else { + r#"{"title":"Clip","formats":[{"format_id":"a","ext":"m4a","vcodec":"none","acodec":"mp4a","filesize":1000},{"format_id":"v","ext":"mp4","height":720,"vcodec":"avc1","acodec":"none","filesize":9000}],"subtitles":{"en":[{}]}}"# + }; + Page::Ready(Box::new(Video::new(Arc::new(Probe::read(&serde_json::from_str(json).unwrap()))))) +} + +fn web_page() -> Probed { + Probed { name: "watch".into(), size: None, mime: Some("text/html".into()), ranges: false, page: true } +} + +#[test] +fn a_video_site_gives_its_choices_to_the_task() { + let mut h = harness(all()); + still(&mut h, "https://videos.example.org/watch?v=abc", |a| { + a.learned(web_page()); + a.video = Some(video_page(false)); + a.name = "Clip".into(); + }); + for label in ["Quality", "Audio only", "Subtitles"] { + assert!(h.query_by_label(label).is_some(), "{label}"); + } + assert!(h.query_by_label("The link leads to a web page, not to a file.").is_none()); + click(&mut h, "Audio only"); + click(&mut h, "Download"); + let [task] = &added(&mut h)[..] else { panic!("not one") }; + assert_eq!(task.video, Some(VideoChoice { audio_only: true, ..VideoChoice::default() })); + assert_eq!((&*task.url, &*task.name), ("https://videos.example.org/watch?v=abc", "Clip")); +} + +#[test] +fn a_playlist_needs_one_video_at_least() { + let mut h = harness(all()); + still(&mut h, "https://videos.example.org/list?id=9", |a| { + a.learned(web_page()); + a.video = Some(video_page(true)); + }); + assert!(h.query_by_label("Playlist").is_some() && !disabled(&h, "Download")); + click(&mut h, "None"); + assert!(disabled(&h, "Download")); + click(&mut h, "Two"); + assert!(!disabled(&h, "Download")); + click(&mut h, "Download"); + let [task] = &added(&mut h)[..] else { panic!("not one") }; + let choice = task.video.clone().unwrap(); + assert_eq!((choice.playlist, choice.items.as_deref()), (true, Some("2"))); +} + +#[test] +fn a_page_that_is_no_video_is_a_plain_download() { + let mut h = harness(all()); + still(&mut h, "https://www.example.org/about.html", |a| a.learned(web_page())); + assert!(h.query_by_label("The link leads to a web page, not to a file.").is_some() && h.query_by_label("Quality").is_none()); + click(&mut h, "Download"); + let [task] = &added(&mut h)[..] else { panic!("not one") }; + assert_eq!(task.video, None); +} diff --git a/crates/app/tests/shots.rs b/crates/app/tests/shots.rs index 554df73..a56e0f6 100644 --- a/crates/app/tests/shots.rs +++ b/crates/app/tests/shots.rs @@ -62,6 +62,13 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame ("add-error", |app, ui| main_view(app, ui, |app| add(app, "https://files.example.org/private/plan.pdf", |a| { a.failed(ErrorKind::Login, "Login needed: files.example.org wants a user name and password."); }))), + ("add-video", |app, ui| main_view(app, ui, |app| add(app, "https://videos.example.org/playlist?list=talks", |a| { + a.learned(Probed { name: "playlist".into(), size: None, mime: Some("text/html".into()), ranges: false, page: true }); + let json = r#"{"_type":"playlist","title":"Conference talks 2026","uploader":"Example Channel","formats":[{"format_id":"a","ext":"m4a","vcodec":"none","acodec":"mp4a","filesize":3000000},{"format_id":"v1","ext":"mp4","height":1080,"vcodec":"avc1","acodec":"none","filesize":90000000},{"format_id":"v2","ext":"mp4","height":480,"vcodec":"avc1","acodec":"none","filesize":20000000}],"subtitles":{"en":[{}],"de":[{}]},"automatic_captions":{"fr":[{}]},"entries":[{"title":"Opening keynote"},{"title":"Fast downloads on slow lines"},{"title":"Spring motion in practice"},{"title":"Wavy progress bars"},{"title":"Closing panel"},{"title":"Lightning talks"},{"title":"Hallway track"},{"title":"Workshop recap"},{"title":"Sponsors"},{"title":"Thanks"}]}"#; + let probe = medlar_core::ytdlp::Probe::read(&serde_json::from_str(json).unwrap()); + a.video = Some(medlar_app::views::video::Page::Ready(Box::new(medlar_app::views::video::Video::new(std::sync::Arc::new(probe))))); + a.name = "Conference talks 2026".into(); + }))), ("add-batch", |app, ui| main_view(app, ui, |app| add(app, "https://share.example.org/files/fonts-collection.zip\nhttps://share.example.org/files/[098-120].jpg\nno link", |_| {}))), ("add-duplicate", |app, ui| main_view(app, ui, |app| add(app, "https://audio.example.edu/files/podcast-archive.flac", |a| { a.learned(Probed { name: "podcast-archive.flac".into(), size: Some(410 * downloads::MB), mime: None, ranges: true, page: false }); diff --git a/crates/core/tests/video.rs b/crates/core/tests/video.rs new file mode 100644 index 0000000..18d8458 --- /dev/null +++ b/crates/core/tests/video.rs @@ -0,0 +1,180 @@ +//! Video tasks in the manager, through a stub yt-dlp: progress, pause and resume, error kinds, what is kept. No real site. + +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::{ClientOptions, Shared, client}; +use medlar_core::manager::*; +use medlar_core::model::*; +use medlar_core::settings::Limits; +use medlar_core::snapshot::{Snapshot, TaskView}; +use medlar_core::store::Store; +use medlar_core::ytdlp::Choice; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::time::sleep; + +const LIMITS: Limits = Limits { speed: 0, max_active: 2, max_connections: 32, parts_per_download: 4, connections_per_host: 16 }; + +/// Answers `--version`, `--dump-single-json` and downloads by the words in the link: `private`, `removed`, `slow` (the first +/// run hangs after some progress), `nothing` (no video site); anything else finishes. Its arguments go to `args`. +const STUB: &str = r#"#!/bin/sh +case "$*" in *--version*) echo 2024.08.06; exit 0;; esac +S='@DIR@' +prev=; dir=; url= +for a in "$@"; do [ "$prev" = "-P" ] && dir="$a"; prev="$a"; url="$a"; done +case "$*" in *--dump-single-json*) + case "$url" in *nothing*) echo "ERROR: Unsupported URL: $url" >&2; exit 1;; esac + echo '{"title":"Clip","formats":[{"format_id":"v","ext":"mp4","height":720,"vcodec":"avc1","acodec":"mp4a","filesize":1000}]}' + exit 0;; +esac +echo "$*" >> "$S/args" +n=$(wc -l < "$S/args") +case "$url" in + *private*) echo "ERROR: [site] x: Private video. Sign in if you've been granted access to this video" >&2; exit 1;; + *removed*) echo "ERROR: [site] x: Video unavailable. This video has been removed by the uploader" >&2; exit 1;; + *slow*) if [ "$n" = 1 ]; then echo 'MEDLAR:400|1000|NA|100|6|NA|NA|NA|NA'; echo $$ > "$S/pid"; exec sleep 60; fi;; +esac +echo 'MEDLAR:500|1000|NA|100|5|NA|NA|NA|NA' +sleep 0.2 +mkdir -p "$dir" +head -c 1000 /dev/zero > "$dir/Clip [x].mp4" +echo "MEDLAR-FILE:$dir/Clip [x].mp4" +"#; + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +struct Bench { + dir: tempfile::TempDir, + manager: Manager, +} + +impl Bench { + fn new() -> Bench { + let dir = tempfile::tempdir().unwrap(); + let stub = dir.path().join("yt-dlp"); + std::fs::write(&stub, STUB.replace("@DIR@", &dir.path().display().to_string())).unwrap(); + std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap(); + let manager = Manager::open(Bench::config(dir.path(), Some(stub))).unwrap(); + Bench { dir, manager } + } + + fn config(dir: &Path, ytdlp: Option) -> Config { + let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap()); + let client = client(&ClientOptions::default()).unwrap(); + let hosts = Hosts::new(Caps::default()); + let mut config = Config::new(Shared { client, store, hosts }, LIMITS); + (config.bin, config.tick, config.ytdlp) = (Bin::at(dir.join("Trash")), ms(20), ytdlp); + config + } + + /// Ends the program and starts it again with `ytdlp`. + fn restart(self, ytdlp: Option) -> Bench { + let Bench { dir, manager } = self; + drop(manager); + Bench { manager: Manager::open(Bench::config(dir.path(), ytdlp)).unwrap(), dir } + } + + fn files(&self) -> PathBuf { + self.dir.path().join("files") + } + + async fn add(&self, what: &str, choice: Choice) -> TaskId { + let task = Task { url: format!("https://video.test/{what}"), name: "Clip".into(), folder: self.files(), video: Some(choice), ..Task::default() }; + self.manager.send(Command::Add(Box::new(task))).await.unwrap() + } + + fn view(&self, id: TaskId) -> Arc { + self.manager.snapshot().get(id).unwrap().clone() + } + + fn args(&self) -> Vec { + std::fs::read_to_string(self.dir.path().join("args")).unwrap_or_default().lines().map(String::from).collect() + } + + async fn until(&self, what: &str, is: impl Fn(&Snapshot) -> bool) { + let end = Instant::now() + Duration::from_secs(20); + while !is(&self.manager.snapshot()) { + let states: Vec<_> = self.manager.snapshot().iter().map(|v| (v.id(), v.state(), v.task.error.clone())).collect(); + assert!(Instant::now() < end, "never {what}: {states:?}"); + sleep(ms(5)).await; + } + } + + async fn until_state(&self, id: TaskId, state: State) { + self.until(state.name(), |s| s.get(id).is_some_and(|v| v.state() == state)).await; + } + + async fn kind(&self, id: TaskId) -> Option { + self.until_state(id, State::Failed).await; + self.view(id).task.error.as_ref().and_then(|e| e.kind) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_video_is_downloaded_and_named_by_its_file() { + let b = Bench::new(); + let choice = Choice { height: Some(720), subtitles: vec!["en".into()], ..Choice::default() }; + let id = b.add("clip", choice.clone()).await; + b.until_state(id, State::Done).await; + let v = b.view(id); + assert_eq!((&*v.task.name, v.task.size, v.downloaded), ("Clip [x].mp4", Some(1000), 1000), "{:#?}", v.log); + assert_eq!(std::fs::metadata(b.files().join("Clip [x].mp4")).unwrap().len(), 1000); + let [args] = &b.args()[..] else { panic!("not one run: {:?}", b.args()) }; + assert!(args.contains("height<=720") && args.contains("--sub-langs en") && args.contains("--no-playlist"), "{args}"); + assert!(args.ends_with("-- https://video.test/clip"), "{args}"); + // The choice is kept. + let b = b.restart(None); + let v = b.view(id); + assert_eq!((v.state(), v.task.video.as_ref()), (State::Done, Some(&choice))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn pause_ends_the_program_and_resume_goes_on() { + let b = Bench::new(); + let id = b.add("slow", Choice::default()).await; + b.until("under way", |s| s.get(id).is_some_and(|v| v.downloaded == 400 && v.state() == State::Running)).await; + let pid = std::fs::read_to_string(b.dir.path().join("pid")).unwrap().trim().to_string(); + b.manager.send(Command::Pause(id)).await.unwrap(); + assert_eq!(b.view(id).state(), State::Paused); + let end = Instant::now() + Duration::from_secs(5); + while Path::new(&format!("/proc/{pid}")).exists() { + assert!(Instant::now() < end, "yt-dlp {pid} still runs after the pause"); + sleep(ms(20)).await; + } + b.manager.send(Command::Resume(id)).await.unwrap(); + b.until_state(id, State::Done).await; + let args = b.args(); + assert_eq!(args.len(), 2, "{args:?}"); + assert!(args.iter().all(|a| a.contains("--continue")), "{args:?}"); + assert_eq!(b.view(id).counters.runs, 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn failures_have_kinds() { + let b = Bench::new(); + let private = b.add("private", Choice::default()).await; + let removed = b.add("removed", Choice::default()).await; + assert_eq!(b.kind(private).await, Some(ErrorKind::Login)); + assert_eq!(b.kind(removed).await, Some(ErrorKind::NotFound)); + let detail = b.view(private).task.error.clone().unwrap().detail; + assert!(!detail.is_empty() && !detail.starts_with("error."), "{detail}"); + // Without a working yt-dlp it says so. + let b = b.restart(Some(PathBuf::from("/nonexistent/yt-dlp"))); + b.manager.send(Command::Resume(removed)).await.unwrap(); + assert_eq!(b.kind(removed).await, Some(ErrorKind::Tool)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_page_is_asked_without_adding() { + let b = Bench::new(); + let probe = b.manager.probe_video("https://video.test/clip".into(), None).await.unwrap(); + assert_eq!((&*probe.title, probe.formats.len()), ("Clip", 1)); + match b.manager.probe_video("https://video.test/nothing".into(), None).await { + Err(Error::Link(f)) => assert_eq!(f.kind, ErrorKind::BadLink), + other => panic!("{:?}", other.map(|p| p.title.clone())), + } + assert!(b.manager.snapshot().iter().next().is_none() && b.args().is_empty()); +}