S044: video tasks run through yt-dlp in the manager; Add dialog shows the video page for site links
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
121df632bb
commit
1ec26bdb7f
10 changed files with 153 additions and 12 deletions
|
|
@ -249,6 +249,11 @@ impl Bridge {
|
|||
Some(self.manager()?.probe(task, secret))
|
||||
}
|
||||
|
||||
/// What a video site offers at the link. None without an engine. Ask for the answer with `poll`.
|
||||
pub fn probe_video(&self, url: String) -> Option<Reply<Arc<medlar_core::ytdlp::Probe>>> {
|
||||
Some(self.manager()?.probe_video(url, None))
|
||||
}
|
||||
|
||||
/// Adds downloads. Their secrets are put in the keyring first, under the names the tasks have.
|
||||
pub fn add(&self, tasks: Vec<Task>, secrets: Vec<(String, Secret)>) {
|
||||
let (sites, manager) = match &mut *lock(&self.inner.engine) {
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ impl Add {
|
|||
};
|
||||
// Nothing is made of the rest when another download goes on.
|
||||
let free = matches!(choice, Choice::Show | Choice::Resume);
|
||||
let good = n > 0 && (free || !wrong.any());
|
||||
let good = n > 0 && (free || !wrong.any() && !self.video_empty());
|
||||
let title = tr!("add.title");
|
||||
let open = self.open;
|
||||
let dialog = Dialog::new("add", &title, &verb).width(size::DIALOG_L).enabled(good).busy(self.check.busy());
|
||||
|
|
@ -99,6 +99,12 @@ impl Add {
|
|||
if !matches!(self.choice(), Choice::Download) {
|
||||
return;
|
||||
}
|
||||
match &mut self.video {
|
||||
Some(Page::Looking) => say(ui, &tr!("video.looking"), t.on_variant),
|
||||
Some(Page::Failed(why)) => say(ui, why, t.error),
|
||||
Some(Page::Ready(video)) => video.show(ui, t),
|
||||
None => {}
|
||||
}
|
||||
if !self.many() {
|
||||
let (label, hint) = (tr!("add.name"), tr!("add.name_hint"));
|
||||
let field = Field::new(&label).hint(&hint);
|
||||
|
|
@ -154,6 +160,7 @@ impl Add {
|
|||
_ if self.single().is_none() => tr!("add.nothing"),
|
||||
Look::Nothing => tr!("add.unknown"),
|
||||
Look::Waits(_) | Look::Asks(_) => tr!("add.asking", host = host),
|
||||
Look::Found(_) if matches!(self.video, Some(Page::Ready(_))) => tr!("video.title"),
|
||||
Look::Found(p) if p.page => tr!("add.page"),
|
||||
Look::Found(p) => {
|
||||
let size = p.size.map_or_else(|| tr!("add.no_size"), amount);
|
||||
|
|
@ -193,7 +200,7 @@ impl Add {
|
|||
let galley = p.layout_job(job);
|
||||
p.galley(pos2(x, rect.center().y - galley.size().y / 2.0), galley, ink);
|
||||
} else {
|
||||
let warn = matches!(&self.look, Look::Found(p) if p.page);
|
||||
let warn = matches!(&self.look, Look::Found(p) if p.page) && !matches!(self.video, Some(Page::Ready(_)));
|
||||
left(p, pos2(x, rect.center().y - 11.0), line(p, &self.name, fonts::med(text::BODY), ink, end - x));
|
||||
left(p, pos2(x, rect.center().y + 11.0), line(p, &words, fonts::ui(text::LABEL), if warn { t.warning } else { faint }, end - x));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ use crate::ui::shape::Kind;
|
|||
use crate::ui::toast::Toasts;
|
||||
use crate::views::list::model::{kind_key, kind_of};
|
||||
use crate::views::main::Reply as Click;
|
||||
use crate::views::video::{Page, Video};
|
||||
use chrono::{Days, Local, NaiveDateTime, NaiveTime};
|
||||
use eframe::egui::{Context, Ui};
|
||||
use medlar_core::auth::{Login, take_login};
|
||||
|
|
@ -365,6 +366,9 @@ pub struct Add {
|
|||
focus_links: bool,
|
||||
asked: Option<Asked>,
|
||||
pub look: Look,
|
||||
/// A video site's page at the single link; None when it is not one. Its choice goes to yt-dlp.
|
||||
pub video: Option<Page>,
|
||||
video_asked: Option<Reply<Arc<medlar_core::ytdlp::Probe>>>,
|
||||
/// Tests put answers here themselves.
|
||||
pub still: bool,
|
||||
/// What `known` was found for.
|
||||
|
|
@ -422,6 +426,8 @@ impl Add {
|
|||
focus_links: true,
|
||||
asked: None,
|
||||
look: Look::Nothing,
|
||||
video: None,
|
||||
video_asked: None,
|
||||
still: false,
|
||||
sought: None,
|
||||
known: None,
|
||||
|
|
@ -512,6 +518,7 @@ impl Add {
|
|||
self.read_text();
|
||||
self.usual_folder(cx);
|
||||
self.ask_server(ctx, cx);
|
||||
self.follow_video(ctx);
|
||||
self.seek(cx);
|
||||
self.ask_space(ctx);
|
||||
if self.check.follow(ctx) && self.check.good().is_some_and(|c| c.verdict() == Verdict::Same) {
|
||||
|
|
@ -579,6 +586,7 @@ impl Add {
|
|||
if self.asked != asked {
|
||||
self.look = if asked.is_some() { Look::Waits(now + PAUSE) } else { Look::Nothing };
|
||||
self.asked = asked;
|
||||
(self.video, self.video_asked) = (None, None);
|
||||
if !self.name_own {
|
||||
self.name = self.single().map(name_of).unwrap_or_default();
|
||||
}
|
||||
|
|
@ -591,7 +599,16 @@ impl Add {
|
|||
ctx.request_repaint();
|
||||
}
|
||||
Look::Asks(reply) => match poll(reply, ctx) {
|
||||
Some(Ok(found)) => self.learned(found),
|
||||
Some(Ok(found)) => {
|
||||
// A web page may be a video site's.
|
||||
if found.page
|
||||
&& let Some(asked) = &self.asked
|
||||
{
|
||||
self.video_asked = cx.bridge.probe_video(asked.task.url.clone());
|
||||
self.video = self.video_asked.is_some().then_some(Page::Looking);
|
||||
}
|
||||
self.learned(found);
|
||||
}
|
||||
Some(Err(manager::Error::Link(f))) => self.look = Look::Failed(Some(f.kind), f.text.clone()),
|
||||
Some(Err(e)) => self.look = Look::Failed(None, e.to_string()),
|
||||
None => {}
|
||||
|
|
@ -600,6 +617,29 @@ impl Add {
|
|||
}
|
||||
}
|
||||
|
||||
/// What yt-dlp said about the page.
|
||||
fn follow_video(&mut self, ctx: &Context) {
|
||||
let Some(answer) = self.video_asked.as_mut().and_then(|r| poll(r, ctx)) else { return };
|
||||
self.video_asked = None;
|
||||
self.video = match answer {
|
||||
Ok(probe) => {
|
||||
if !self.name_own {
|
||||
self.name = safe_name(&probe.title).unwrap_or_default();
|
||||
}
|
||||
Some(Page::Ready(Box::new(Video::new(probe))))
|
||||
}
|
||||
// Not a video site, or no yt-dlp to ask: the page itself is what the link gives.
|
||||
Err(manager::Error::Link(f)) if matches!(f.kind, ErrorKind::BadLink | ErrorKind::Tool) => None,
|
||||
Err(manager::Error::Link(f)) => Some(Page::Failed(f.text.clone())),
|
||||
Err(e) => Some(Page::Failed(e.to_string())),
|
||||
};
|
||||
}
|
||||
|
||||
/// Nothing of a playlist is picked.
|
||||
fn video_empty(&self) -> bool {
|
||||
matches!(&self.video, Some(Page::Ready(v)) if v.empty())
|
||||
}
|
||||
|
||||
/// What the server said.
|
||||
pub fn learned(&mut self, found: Probed) {
|
||||
if !self.name_own {
|
||||
|
|
@ -814,6 +854,9 @@ impl Add {
|
|||
}
|
||||
task.mirrors = Batch::of(&self.mirrors, false).links.iter().map(|m| take_login(m).0).collect();
|
||||
task.checksum = self.checksum_text();
|
||||
if let Some(Page::Ready(v)) = &self.video {
|
||||
task.video = Some(v.choice());
|
||||
}
|
||||
}
|
||||
(tasks, secrets)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ use crate::speed::{History, Meter};
|
|||
use crate::store::{self, Store};
|
||||
use crate::stream::{self, Tools};
|
||||
use crate::verify::Checksum;
|
||||
use crate::{schedule, adopt, disk, host, metalink, redact, site, strings, tr, verify};
|
||||
use crate::{schedule, adopt, disk, host, metalink, redact, site, strings, tr, verify, ytdlp};
|
||||
use arc_swap::ArcSwap;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
|
@ -423,6 +423,7 @@ impl Actor {
|
|||
Msg::FindChecksum(id, answer) => self.find_checksum(id, answer),
|
||||
Msg::ReadMetalink(link, answer) => self.read_metalink(link, answer),
|
||||
Msg::Probe(task, secret, answer) => self.probe(*task, secret, answer),
|
||||
Msg::ProbeVideo(url, cookies, answer) => self.probe_video(url, cookies, answer),
|
||||
Msg::Limits(limits) => self.set_limits(limits),
|
||||
Msg::Rescan => self.choose = true,
|
||||
Msg::OnChange(call) => self.on_change.push(call),
|
||||
|
|
@ -784,6 +785,14 @@ impl Actor {
|
|||
});
|
||||
}
|
||||
|
||||
fn probe_video(&self, url: String, cookies: Option<String>, answer: oneshot::Sender<Result<Arc<ytdlp::Probe>>>) {
|
||||
let (tool, cache) = (self.config.ytdlp.clone(), self.config.videos.clone());
|
||||
self.look(answer, host_of(&url), async move {
|
||||
let found = ytdlp::Ytdlp::found(tool.as_deref()).await?;
|
||||
found.probe(&cache, &url, cookies.as_deref(), std::future::pending()).await
|
||||
});
|
||||
}
|
||||
|
||||
fn await_link(&mut self, id: TaskId) -> Result<()> {
|
||||
if matches!(self.entries[&id].task.state, State::Checking | State::Finishing | State::Done | State::Gone) {
|
||||
return Ok(());
|
||||
|
|
@ -1128,9 +1137,12 @@ impl Actor {
|
|||
monitor.finish();
|
||||
}
|
||||
let (shared, options, to) = (self.config.shared.clone(), self.config.options.clone(), self.to.clone());
|
||||
let sites = self.config.sites.clone();
|
||||
let (sites, tool) = (self.config.sites.clone(), self.config.ytdlp.clone());
|
||||
self.runtime().spawn(async move {
|
||||
let work = tokio::spawn(async move {
|
||||
if task.video.is_some() {
|
||||
return ytdlp::download(&shared, &task, tool.as_deref(), &monitor, stopped).await;
|
||||
}
|
||||
let source = site::source(sites.as_ref(), &task, &stopped).await?;
|
||||
if stream::kind_of(&task).is_some() {
|
||||
let request = stream::Request { id, source, choice: task.stream.clone().unwrap_or_default(), tools: &Tools::find(), options: &options };
|
||||
|
|
|
|||
|
|
@ -206,6 +206,10 @@ pub struct Config {
|
|||
pub tick: Duration,
|
||||
/// Time for queue schedules; tests set their own.
|
||||
pub clock: Arc<dyn crate::schedule::Clock>,
|
||||
/// Where yt-dlp is; None: looked for beside Medlar and on the PATH. Tests set a stub.
|
||||
pub ytdlp: Option<PathBuf>,
|
||||
/// What video sites answered, for a while.
|
||||
pub videos: Arc<crate::ytdlp::Cache>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
|
|
@ -221,6 +225,8 @@ impl Config {
|
|||
undo: Duration::from_secs(60),
|
||||
tick: Duration::from_millis(100),
|
||||
clock: Arc::new(crate::schedule::SystemClock),
|
||||
ytdlp: None,
|
||||
videos: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -234,6 +240,7 @@ enum Msg {
|
|||
ReadMetalink(NewLink, oneshot::Sender<Result<Vec<metalink::File>>>),
|
||||
CheckPartial(PathBuf, NewLink, oneshot::Sender<Result<Found>>),
|
||||
Probe(Box<Task>, Option<Secret>, oneshot::Sender<Result<Probed>>),
|
||||
ProbeVideo(String, Option<String>, oneshot::Sender<Result<Arc<crate::ytdlp::Probe>>>),
|
||||
Limits(Limits),
|
||||
/// Queues were changed in the store.
|
||||
Rescan,
|
||||
|
|
@ -312,6 +319,14 @@ impl Manager {
|
|||
Reply(reply)
|
||||
}
|
||||
|
||||
/// What a video site offers at the link, through yt-dlp; nothing is added. `cookies` is the text of a cookie file, used
|
||||
/// without being kept. Dropping the reply ends it.
|
||||
pub fn probe_video(&self, url: String, cookies: Option<String>) -> Reply<Arc<crate::ytdlp::Probe>> {
|
||||
let (answer, reply) = oneshot::channel();
|
||||
let _ = self.to.send(Msg::ProbeVideo(url, cookies, answer));
|
||||
Reply(reply)
|
||||
}
|
||||
|
||||
/// Takes effect at once, also on running downloads. 0 is no limit. Connections that may stay go on as they are.
|
||||
pub fn set_limits(&self, limits: Limits) {
|
||||
let _ = self.to.send(Msg::Limits(limits));
|
||||
|
|
|
|||
|
|
@ -194,6 +194,8 @@ pub struct Task {
|
|||
pub after: Option<TaskId>,
|
||||
/// What was chosen of a stream. None is the best of it, for as long as it goes on.
|
||||
pub stream: Option<crate::stream::Choice>,
|
||||
/// What was chosen of a video site's page; such a task runs through yt-dlp.
|
||||
pub video: Option<crate::ytdlp::Choice>,
|
||||
/// The unfinished one this starts over. Removed when this is done.
|
||||
pub replaces: Option<TaskId>,
|
||||
pub start_at: Option<Time>,
|
||||
|
|
@ -235,6 +237,7 @@ impl Default for Task {
|
|||
secret: None,
|
||||
after: None,
|
||||
stream: None,
|
||||
video: None,
|
||||
replaces: None,
|
||||
start_at: None,
|
||||
added_at: now(),
|
||||
|
|
|
|||
1
crates/core/src/store/006.sql
Normal file
1
crates/core/src/store/006.sql
Normal file
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE tasks ADD COLUMN video TEXT;
|
||||
|
|
@ -16,7 +16,7 @@ use std::thread::JoinHandle;
|
|||
use std::time::Duration;
|
||||
|
||||
/// Never edit one that shipped; add the next number.
|
||||
const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql"), include_str!("005.sql")];
|
||||
const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql"), include_str!("005.sql"), include_str!("006.sql")];
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result<usize> {
|
|||
let folder = path_bytes(&t.folder);
|
||||
let (mirrors, headers) = (json(&t.mirrors), json(&t.headers));
|
||||
let stream = t.stream.as_ref().map(json);
|
||||
let video = t.video.as_ref().map(json);
|
||||
let pieces = t.pieces.as_ref().map(|p| p.to_string());
|
||||
let columns: &[(&str, &dyn ToSql)] = named_params! {
|
||||
":url": t.url, ":mirrors": mirrors, ":source_page": t.source_page, ":name": t.name, ":folder": folder,
|
||||
|
|
@ -39,7 +40,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result<usize> {
|
|||
":checksum": t.checksum, ":max_parts": t.max_parts, ":speed_limit": t.speed_limit, ":headers": headers,
|
||||
":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at,
|
||||
":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes, ":tries": t.tries,
|
||||
":replaces": t.replaces, ":pieces": pieces, ":verified": t.verified, ":stream": stream,
|
||||
":replaces": t.replaces, ":pieces": pieces, ":verified": t.verified, ":stream": stream, ":video": video,
|
||||
};
|
||||
Ok(c.execute(sql, columns)?)
|
||||
}
|
||||
|
|
@ -49,10 +50,10 @@ pub fn insert_task(c: &Connection, t: &Task) -> Result<TaskId> {
|
|||
c,
|
||||
"INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime,
|
||||
etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at,
|
||||
finished_at, removed_at, notes, tries, replaces, pieces, verified, stream)
|
||||
finished_at, removed_at, notes, tries, replaces, pieces, verified, stream, video)
|
||||
VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime,
|
||||
:etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at,
|
||||
:finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified, :stream)",
|
||||
:finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified, :stream, :video)",
|
||||
t,
|
||||
)?;
|
||||
let id = c.last_insert_rowid();
|
||||
|
|
@ -71,7 +72,7 @@ pub fn update_task(c: &Connection, t: &Task) -> Result<usize> {
|
|||
etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts,
|
||||
speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after,
|
||||
start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes,
|
||||
tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified, stream = :stream
|
||||
tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified, stream = :stream, video = :video
|
||||
WHERE id = {}",
|
||||
t.id
|
||||
);
|
||||
|
|
@ -134,6 +135,7 @@ fn task(r: &Row) -> Result<Task> {
|
|||
secret: r.get("secret")?,
|
||||
after: r.get("after")?,
|
||||
stream: r.get::<_, Option<String>>("stream")?.and_then(|s| serde_json::from_str(&s).ok()),
|
||||
video: r.get::<_, Option<String>>("video")?.and_then(|s| serde_json::from_str(&s).ok()),
|
||||
replaces: r.get("replaces")?,
|
||||
start_at: r.get("start_at")?,
|
||||
added_at: r.get("added_at")?,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
//! 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::http::{Error, Monitor, PartState, PartView, Result, Shared, Snapshot, Stop};
|
||||
use crate::model::Task;
|
||||
use crate::model::ErrorKind;
|
||||
use crate::redact;
|
||||
use serde_json::Value;
|
||||
|
|
@ -90,6 +91,15 @@ impl Ytdlp {
|
|||
}
|
||||
}
|
||||
|
||||
/// The one at `at`, or else the one that is found.
|
||||
pub async fn found(at: Option<&Path>) -> Result<Ytdlp> {
|
||||
let found = match at {
|
||||
Some(path) => Ytdlp::at(path.to_path_buf()).await,
|
||||
None => Ytdlp::find().await,
|
||||
};
|
||||
found.map_err(|p| p.error())
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
|
@ -176,6 +186,48 @@ impl Ytdlp {
|
|||
}
|
||||
}
|
||||
|
||||
/// Runs a video task of the manager to its end and gives the file it made. Doesn't touch the task's state. Stopping it keeps
|
||||
/// what is there: yt-dlp goes on from it next time.
|
||||
pub(crate) async fn download(shared: &Shared, task: &Task, tool: Option<&Path>, monitor: &Monitor, mut stop: Stop) -> Result<PathBuf> {
|
||||
let ytdlp = Ytdlp::found(tool).await?;
|
||||
let choice = task.video.clone().unwrap_or_default();
|
||||
let run = Run { url: task.url.clone(), folder: task.folder.clone(), name: Run::NAME.into(), choice, limit: task.speed_limit, cookies: None };
|
||||
let mut running = ytdlp.start(&run)?;
|
||||
let mut seen = running.progress();
|
||||
let (mut last, mut received) = (0, 0);
|
||||
let ended = loop {
|
||||
tokio::select! {
|
||||
result = running.end() => break Some(result),
|
||||
_ = stop.wait_for(|s| *s) => break None,
|
||||
Ok(()) = seen.changed() => {
|
||||
let now = *seen.borrow_and_update();
|
||||
// The next video of a playlist starts at 0 again.
|
||||
received += now.done.checked_sub(last).unwrap_or(now.done);
|
||||
last = now.done;
|
||||
let speed = now.speed.unwrap_or(0.0);
|
||||
let part = PartView { id: 0, start: 0, end: now.total, done: now.done, state: PartState::Running, speed, fails: 0 };
|
||||
let shot = Snapshot { size: now.total, parts: vec![part], connections: 1, wanted: 1, received, speed, ..Default::default() };
|
||||
monitor.publish(shot, vec![], std::iter::empty());
|
||||
}
|
||||
}
|
||||
};
|
||||
let Some(result) = ended else {
|
||||
running.stop().await;
|
||||
return Err(Error::Stopped);
|
||||
};
|
||||
let path = result?;
|
||||
let (store, id, file) = (shared.store.clone(), task.id, path.clone());
|
||||
crate::disk::blocking(move || {
|
||||
let size = file.metadata().map_err(io)?.len();
|
||||
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
store.save_parts(id, vec![crate::model::Part { start: 0, end: Some(size), done: size }])?;
|
||||
store.edit_task(id, move |task| (task.name, task.size) = (name, Some(size)))?;
|
||||
Ok::<(), Error>(())
|
||||
})
|
||||
.await?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn io(e: std::io::Error) -> Error {
|
||||
Error::Disk(e.into())
|
||||
}
|
||||
|
|
@ -402,7 +454,8 @@ impl Cache {
|
|||
}
|
||||
|
||||
/// What the user chose.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Choice {
|
||||
/// At most this tall; `None` is the best.
|
||||
pub height: Option<u32>,
|
||||
|
|
|
|||
Loading…
Reference in a new issue