From 08488b4df203d6d3f4957f43f3cff35ca3c8fbe9 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 14:03:30 -0600 Subject: [PATCH] S016: Add dialog, batch and duplicates Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + Plans/03 Interface/S016-add-dialog.md | 16 +- Plans/INDEX.md | 2 +- crates/app/Cargo.toml | 4 +- crates/app/src/bridge.rs | 135 +++- crates/app/src/ui/dialog.rs | 5 + crates/app/src/views/add/draw.rs | 398 +++++++++++ crates/app/src/views/add/mod.rs | 938 ++++++++++++++++++++++++++ crates/app/src/views/add/relink.rs | 110 +++ crates/app/src/views/list/model.rs | 10 +- crates/app/src/views/main.rs | 85 +-- crates/app/src/views/mod.rs | 1 + crates/app/src/views/settings/mod.rs | 2 +- crates/app/tests/add.rs | 488 ++++++++++++++ crates/app/tests/main.rs | 12 +- crates/app/tests/shots.rs | 33 + crates/core/lang/en.json | 86 ++- crates/core/src/batch.rs | 230 +++++++ crates/core/src/disk.rs | 7 + crates/core/src/duplicate.rs | 95 +++ crates/core/src/lib.rs | 3 + crates/core/src/manager/actor.rs | 57 +- crates/core/src/manager/mod.rs | 22 + crates/core/src/portal.rs | 33 + crates/core/src/secret.rs | 13 + crates/core/src/site.rs | 9 +- crates/core/tests/auth.rs | 76 ++- docs/DECISIONS.md | 3 + docs/PROGRESS.md | 12 + 29 files changed, 2809 insertions(+), 78 deletions(-) create mode 100644 crates/app/src/views/add/draw.rs create mode 100644 crates/app/src/views/add/mod.rs create mode 100644 crates/app/src/views/add/relink.rs create mode 100644 crates/app/tests/add.rs create mode 100644 crates/core/src/batch.rs create mode 100644 crates/core/src/duplicate.rs create mode 100644 crates/core/src/portal.rs diff --git a/Cargo.lock b/Cargo.lock index 3cae3be..747157c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2769,11 +2769,13 @@ dependencies = [ "medlar-cli", "medlar-core", "medlar-testserver", + "percent-encoding", "resvg", "serde", "serde_json", "tempfile", "tokio", + "url", ] [[package]] diff --git a/Plans/03 Interface/S016-add-dialog.md b/Plans/03 Interface/S016-add-dialog.md index 6c124f8..cdac2d9 100644 --- a/Plans/03 Interface/S016-add-dialog.md +++ b/Plans/03 Interface/S016-add-dialog.md @@ -12,14 +12,14 @@ FEATURES 3.1, 3.2, 3.8, and "this continues an earlier download" (4.6). - docs/FEATURES.md §3 ## Steps -- [ ] Dialog with link(s), live probe (size, kind shape, resume, parts), name, folder with recents and free space, queue, priority, limit, parts, schedule -- [ ] Advanced: headers, cookies, login, referrer, user agent, proxy, mirrors, checksum; remembers folders per type -- [ ] Batch: pasted lists, file or clipboard import, patterns `[001-120]`, `{a,b}`, dates, with preview, select and a hard cap -- [ ] Duplicates by link, name and checksum: resume, rename, skip or show -- [ ] When S008's matcher finds an unfinished download: "Continue that download" first, with the reason -- [ ] Paste a new link into a failed task ("Continue from link"), with the verdict shown before anything changes -- [ ] Probe errors inline with fixes (login needed, expired); add anyway is possible -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S016: …`, push +- [x] Dialog with link(s), live probe (size, kind shape, resume, parts), name, folder with recents and free space, queue, priority, limit, parts, schedule +- [x] Advanced: headers, cookies, login, referrer, user agent, proxy, mirrors, checksum; remembers folders per type +- [x] Batch: pasted lists, file or clipboard import, patterns `[001-120]`, `{a,b}`, dates, with preview, select and a hard cap +- [x] Duplicates by link, name and checksum: resume, rename, skip or show +- [x] When S008's matcher finds an unfinished download: "Continue that download" first, with the reason +- [x] Paste a new link into a failed task ("Continue from link"), with the verdict shown before anything changes +- [x] Probe errors inline with fixes (login needed, expired); add anyway is possible +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S016: …`, push ## End criteria - `nice cargo test -j 2 -p medlar --test add` green diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 08a322c..79a4082 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -27,7 +27,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S013](03%20Interface/S013-controls.md) Controls, dialogs and toasts - [x] [S014](03%20Interface/S014-wavy-parts-shapes.md) Wavy bars, parts map, shapes and speed graph - [x] [S015](03%20Interface/S015-main-window.md) Main window and list -- [ ] [S016](03%20Interface/S016-add-dialog.md) Add dialog, batch and duplicates +- [x] [S016](03%20Interface/S016-add-dialog.md) Add dialog, batch and duplicates - [ ] [S017](03%20Interface/S017-details.md) Details panel and file actions - [x] [S018](03%20Interface/S018-settings-palette.md) Settings, colour, shortcuts and first run diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index bda1dc2..b7d8bd8 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -22,7 +22,9 @@ serde_json.workspace = true chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } dirs = "6" eframe = { version = "0.37", default-features = false, features = ["glow", "wayland", "x11", "default_fonts", "system_fonts", "persistence"] } -tokio = { version = "1", features = ["rt"] } +tokio = { version = "1", features = ["macros", "rt", "sync"] } +percent-encoding = "2.3.2" +url = "2" resvg = { version = "0.45", default-features = false } [dev-dependencies] diff --git a/crates/app/src/bridge.rs b/crates/app/src/bridge.rs index 6153887..55e6b27 100644 --- a/crates/app/src/bridge.rs +++ b/crates/app/src/bridge.rs @@ -5,18 +5,23 @@ use eframe::egui::Context; use medlar_core::auth::Login; use medlar_core::host::{Caps, Hosts}; use medlar_core::http::{self, ClientOptions, Shared}; -use medlar_core::manager::{Command, Config, Manager, Reply}; -use medlar_core::model::{Queue, Tag}; +use medlar_core::manager::{Command, Config, Manager, Probed, Reply}; +use medlar_core::model::{Queue, Tag, Task, TaskId}; use medlar_core::paths::Paths; use medlar_core::net_state::Bus; -use medlar_core::secret::{Secret, Secrets}; +use medlar_core::relink::{Checked, NewLink}; +use medlar_core::secret::{self, Secret, Secrets}; use medlar_core::settings::Settings; use medlar_core::site::Sites; use medlar_core::snapshot::Snapshot; use medlar_core::store::Store; use medlar_core::tr; +use std::future::Future; use std::path::PathBuf; +use std::pin::Pin; use std::sync::{Arc, Mutex, MutexGuard, mpsc}; +use std::task::{Poll, Waker}; +use tokio::sync::oneshot; /// What is seldom changed. Read once; `reload` after a change. #[derive(Debug, Clone, Default, PartialEq)] @@ -214,6 +219,98 @@ impl Bridge { }); } + /// What a link leads to. None without an engine. Ask for the answer with `poll`. + pub fn probe(&self, task: Task, secret: Option) -> Option> { + Some(self.manager()?.probe(task, secret)) + } + + /// Adds downloads. Their secrets are put in the keyring first, under the names the tasks have. + pub fn add(&self, tasks: Vec, secrets: Vec<(String, Secret)>) { + let (sites, manager) = match &mut *lock(&self.inner.engine) { + Engine::Open { sites, manager, replies, .. } if secrets.is_empty() => { + for task in tasks { + let _ = replies.send(manager.send(Command::Add(Box::new(task)))); + } + return; + } + Engine::Open { sites, manager, .. } => (sites.clone(), manager.clone()), + Engine::Still { sent, .. } => return sent.extend(tasks.into_iter().map(|t| Command::Add(Box::new(t)))), + _ => return, + }; + self.aside(move |inner, runtime| { + for (name, secret) in &secrets { + keep(inner, runtime, &sites, name, secret); + } + let all: Vec<_> = tasks.into_iter().map(|t| (t.secret.clone(), manager.send(Command::Add(Box::new(t))))).collect(); + let mut used = vec![]; + for (secret, reply) in all { + match reply.wait() { + Ok(_) => used.extend(secret), + Err(e) => lock(&inner.errors).push(e.to_string()), + } + } + for (name, _) in secrets.iter().filter(|(name, _)| !used.contains(name)) { + runtime.block_on(sites.secrets.remove(name)); + } + }); + } + + /// Compares a download with a new link. A secret is put in the keyring for it under a new name; see `drop_check`. + pub fn check(&self, id: TaskId, mut link: NewLink, secret: Option) -> Option { + let Engine::Open { sites, manager, .. } = &*lock(&self.inner.engine) else { return None }; + let (sites, manager) = (sites.clone(), manager.clone()); + let (mut answer, check) = oneshot::channel(); + self.aside(move |inner, runtime| { + let own = secret.map(|secret| { + let name = secret::task_name(); + keep(inner, runtime, &sites, &name, &secret); + link.secret = Some(name.clone()); + name + }); + let reply = manager.check(id, link); + let result = runtime.block_on(async { + tokio::select! { + _ = answer.closed() => None, + result = reply => Some(result.map_err(|e| e.to_string())), + } + }); + let unwanted = match result { + Some(Ok(checked)) => answer.send(Ok(checked)).is_err(), + Some(Err(why)) => { + let _ = answer.send(Err(why)); + true + } + None => true, + }; + if let Some(name) = own.filter(|_| unwanted) { + runtime.block_on(sites.secrets.remove(&name)); + } + }); + Some(check) + } + + /// A finished check that nothing comes of: what it put in the keyring goes. `kept` is what the download had before. + pub fn drop_check(&self, checked: &Checked, kept: Option<&String>) { + if let Some(name) = checked.link.secret.clone().filter(|name| Some(name) != kept) { + self.forget_login(name); + } + } + + /// On a thread of its own, with a runtime for what it has to wait for. + fn aside(&self, work: impl FnOnce(&Inner, &tokio::runtime::Runtime) + Send + 'static) { + let inner = self.inner.clone(); + let ctx = self.opening.as_ref().map(|(_, ctx)| ctx.clone()); + std::thread::spawn(move || { + match tokio::runtime::Builder::new_current_thread().enable_all().build() { + Ok(runtime) => work(&inner, &runtime), + Err(e) => log::error!("bridge: {e}"), + } + if let Some(ctx) = ctx { + ctx.request_repaint(); + } + }); + } + /// Takes a login out of the keyring. pub fn forget_login(&self, name: String) { let Engine::Open { sites, .. } = &*lock(&self.inner.engine) else { return }; @@ -257,6 +354,38 @@ impl Bridge { } } +/// The answer to a check, or why there is none. +pub type Check = oneshot::Receiver>; + +/// The answer, if it is there. Draws a frame when it comes; ask no more after it. +pub fn poll(asked: &mut F, ctx: &Context) -> Option { + struct Frame(Context); + impl std::task::Wake for Frame { + fn wake(self: Arc) { + self.0.request_repaint(); + } + } + let waker = Waker::from(Arc::new(Frame(ctx.clone()))); + match Pin::new(asked).poll(&mut std::task::Context::from_waker(&waker)) { + Poll::Ready(answer) => Some(answer), + Poll::Pending => None, + } +} + +/// Runs something slow beside the window. +pub fn beside(work: impl FnOnce() -> T + Send + 'static) -> oneshot::Receiver { + let (answer, asked) = oneshot::channel(); + std::thread::spawn(move || drop(answer.send(work()))); + asked +} + +fn keep(inner: &Inner, runtime: &tokio::runtime::Runtime, sites: &Sites, name: &str, secret: &Secret) { + let host = secret.home.as_deref().and_then(crate::views::settings::site_of).unwrap_or_default(); + if let Some(words) = runtime.block_on(sites.secrets.save(name, &host, secret)).words() { + lock(&inner.errors).push(words); + } +} + /// Whose login it is. pub enum Place { Site { name: String, host: String }, diff --git a/crates/app/src/ui/dialog.rs b/crates/app/src/ui/dialog.rs index 2c05109..e30de03 100644 --- a/crates/app/src/ui/dialog.rs +++ b/crates/app/src/ui/dialog.rs @@ -24,6 +24,11 @@ pub fn any_open(ctx: &Context) -> bool { ctx.memory(|m| m.top_modal_layer().is_some()) } +/// Is anything of this dialog still to be seen? +pub fn shown(ctx: &Context, id: &str) -> bool { + ctx.data(|d| d.get_temp::(Id::unique(("dialog", id))).is_some()) +} + #[derive(Clone, Copy, Default)] struct State { open: bool, diff --git a/crates/app/src/views/add/draw.rs b/crates/app/src/views/add/draw.rs new file mode 100644 index 0000000..1dfb77d --- /dev/null +++ b/crates/app/src/views/add/draw.rs @@ -0,0 +1,398 @@ +//! How the dialog looks. + +use super::*; +use crate::theme::Theme; +use crate::tokens::{icon, radius, size, space, text}; +use crate::ui::dialog::{self, Answer, Dialog}; +use crate::ui::field::{Combo, Field, Number}; +use crate::ui::menu::{self, Item}; +use crate::ui::odometer::amount; +use crate::ui::shape; +use crate::ui::wave; +use crate::ui::widgets::{Button, Choice as Pick1, Kind as Style, Size, cr, left, line, spinner, text_width, tip, waiting}; +use crate::views::list::model::{queue_name, title}; +use crate::views::list::row::state_label; +use crate::{fonts, icons}; +use eframe::egui::{Color32, Id, Rect, RichText, ScrollArea, Sense, UiBuilder, Vec2, ViewportCommand, WidgetInfo, accesskit::Role, pos2, text::LayoutJob, vec2}; +use medlar_core::strings; + +/// What the server says, whatever it says. +const CARD: f32 = 72.0; +/// Rows of the batch's list that are seen. +const SEEN: f32 = 6.0; +/// A number with its name above and its error below. +const NUMBER: f32 = size::CONTROL + 2.0 * (space::L + space::XS); +/// A narrower dialog has one column. +const COLUMNS: f32 = 400.0; + +/// A quiet line, over as many rows as it needs. +fn say(ui: &mut Ui, words: &str, color: Color32) { + ui.label(RichText::new(words).font(fonts::ui(text::LABEL)).color(color)); +} + +/// `n` columns of one height. +fn columns(ui: &mut Ui, salt: &str, n: usize, height: f32, mut draw: impl FnMut(&mut Ui, usize, f32)) { + let across = if ui.available_width() < COLUMNS { 1 } else { n }; + let side = ((ui.available_width() - space::S * (across - 1) as f32) / across as f32).floor(); + for row in 0..n.div_ceil(across) { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + for i in (row * across)..((row + 1) * across).min(n) { + let at = pos2(rect.left() + (side + space::S) * (i % across) as f32, rect.top()); + let mut child = ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size(at, vec2(side, height))).id_salt((salt, i))); + draw(&mut child, i, side); + } + } +} + +/// A plate that says something. What is in it comes on top. +fn plate(ui: &mut Ui, fill: Color32, height: f32, words: &str) -> Rect { + let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + r.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); + ui.painter().rect_filled(rect, cr(radius::L), fill); + rect +} + +impl Add { + /// True when nothing is left of it. + pub(super) fn show(&mut self, ui: &Ui, t: &Theme, cx: &mut Cx) -> bool { + let ctx = ui.ctx().clone(); + if self.open { + self.follow(&ctx, cx); + } + let wrong = self.wrong(); + let choice = self.choice(); + let failed = matches!(self.look, Look::Failed(..)); + let n = self.count(); + let verb = match choice { + _ if self.many() && self.lines.iter().all(|l| !l.on) && self.twice == Twice::Resume => tr!("add.resume_n", n = n), + _ if self.many() => tr!("add.do_n", n = n), + Choice::Continue => match &self.check.found { + None => Choice::Continue.verb(), + Some(Ok(_)) => tr!("add.continue_anyway"), + Some(Err(_)) => tr!("add.check_again"), + }, + Choice::Download if failed => tr!("add.anyway"), + other => other.verb(), + }; + // 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 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()); + match dialog.show(&ctx, t, open, |ui| self.content(ui, t, cx, &wrong)) { + Some(Answer::Main) => self.act(cx), + Some(Answer::Cancel) => self.leave(cx), + None => {} + } + !self.open && !dialog::shown(&ctx, "add") + } + + fn content(&mut self, ui: &mut Ui, t: &Theme, cx: &mut Cx, wrong: &Wrong) { + self.links(ui, t); + if self.many() { + self.list(ui, t); + } else { + self.card(ui, t, cx); + self.known(ui, t, cx); + } + if !matches!(self.choice(), Choice::Download) { + return; + } + if !self.many() { + let (label, hint) = (tr!("add.name"), tr!("add.name_hint")); + let field = Field::new(&label).hint(&hint); + let field = if wrong.name.is_some() { field.error(wrong.name.as_deref()) } else { field }; + let r = field.show(ui, t, &mut self.name); + if r.changed() { + self.name_own = !self.name.trim().is_empty(); + } + } + self.where_to(ui, t, cx, wrong); + self.how(ui, t, cx, wrong); + let words = if self.more { tr!("add.less") } else { tr!("add.more") }; + let icon = if self.more { "expand_less" } else { "expand_more" }; + if Button::new(&words).with_icon(icon).kind(Style::Text).danger(wrong.in_more() && !self.more).show(ui, t).clicked() { + self.more = !self.more; + } + if self.more { + self.rest(ui, t, wrong); + } + } + + fn links(&mut self, ui: &mut Ui, t: &Theme) { + let field = Field::new(&tr!("add.links")).rows(2).show(ui, t, &mut self.text); + if std::mem::take(&mut self.focus_links) { + field.request_focus(); + } + ui.horizontal(|ui| { + if Button::new(&tr!("add.paste")).with_icon("content_paste").kind(Style::Tonal).size(Size::S).show(ui, t).clicked() { + field.request_focus(); + ui.ctx().send_viewport_cmd(ViewportCommand::RequestPaste); + } + let words = tr!("add.open_list"); + let list = Button::new(&words).with_icon("file_open").kind(Style::Tonal).size(Size::S).busy(self.list.is_some()); + if list.show(ui, t).clicked() && self.picker.is_none() { + self.choose(Pick::File); + } + if self.batch.patterns { + Pick1::new(&tr!("add.patterns")).checkbox(ui, t, &mut self.patterns); + } + }); + if self.batch.cut() { + say(ui, &tr!("add.too_many", most = medlar_core::batch::MOST, n = self.batch.total), t.error); + } else if self.batch.left_out > 0 && !self.batch.links.is_empty() { + say(ui, &tr!("add.left_out", n = self.batch.left_out), t.on_variant); + } + } + + /// What the link leads to. + fn card(&mut self, ui: &mut Ui, t: &Theme, cx: &Cx) { + let host = self.single().and_then(super::super::settings::site_of).unwrap_or_default(); + let failed = matches!(self.look, Look::Failed(..)); + let words = match &self.look { + _ if self.single().is_none() => tr!("add.nothing"), + Look::Nothing => tr!("add.unknown"), + Look::Waits(_) | Look::Asks(_) => tr!("add.asking", host = host), + Look::Found(p) if p.page => tr!("add.page"), + Look::Found(p) => { + let size = p.size.map_or_else(|| tr!("add.no_size"), amount); + if p.ranges { tr!("add.parts", size = size, n = self.planned(cx)) } else { tr!("add.one_part", size = size) } + } + Look::Failed(_, why) => why.clone(), + }; + let fill = if failed { t.error_container } else { t.high }; + let (ink, faint) = if failed { (t.on_error_container, t.on_error_container) } else { (t.on_surface, t.on_variant) }; + let rect = plate(ui, fill, CARD, &words); + let inside = rect.shrink(space::M); + let place = Rect::from_min_size(pos2(inside.left(), rect.center().y - icon::XL / 2.0), Vec2::splat(icon::XL)); + if failed { + icons::paint(ui.painter(), place.center(), icon::L, "error", ink); + } else if waiting(ui.ctx(), Id::unique("add asks"), self.look.busy()) { + spinner(ui.painter(), place.center(), icon::L, t.primary); + } else if self.single().is_some() { + shape::badge(ui, t, Id::unique("add badge"), place, self.kind(), wave::Look::Waiting); + } else { + icons::paint(ui.painter(), place.center(), icon::L, "link", faint); + } + let mut end = inside.right(); + if let Some((fix, label)) = self.fix() { + let wide = text_width(ui.painter(), &label, fonts::med(text::BODY)) + 2.0 * space::M; + let at = Rect::from_center_size(pos2(end - wide / 2.0, rect.center().y), vec2(wide, size::HIT)); + let mut child = ui.new_child(UiBuilder::new().max_rect(at).id_salt("fix")); + if Button::new(&label).kind(Style::Outlined).size(Size::S).show(&mut child, t).clicked() { + self.mend(fix, cx); + } + end = at.left() - space::M; + } + let x = place.right() + space::M; + let p = ui.painter(); + if failed || self.single().is_none() || self.name.is_empty() { + let mut job = LayoutJob::simple(words, fonts::ui(text::BODY), ink, end - x); + job.wrap.max_rows = 2; + 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); + 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)); + } + } + + /// Parts it has at most. + fn planned(&self, cx: &Cx) -> u32 { + let own = Some(self.parts as u32).filter(|n| *n > 0); + own.unwrap_or(match cx.settings.limits().parts_per_download { + 0 => 64, + n => n, + }) + } + + /// The download that the link has to do with. + fn known(&mut self, ui: &mut Ui, t: &Theme, cx: &mut Cx) { + let Some(known) = &mut self.known else { return }; + let view = cx.shot.get(known.task.id); + let name = view.map_or(known.task.name.clone(), |v| title(v).to_string()); + let state = match view { + Some(v) if v.state() != State::Done => { + let here = amount(v.downloaded); + let here = v.size.map_or(here.clone(), |size| tr!("add.of", here = here, size = amount(size))); + tr!("list.dot", a = state_label(v.state()), b = here) + } + _ => state_label(known.task.state), + }; + let head = tr!("list.dot", a = name, b = state); + let rows = known.choices.len() as f32; + let wide = ui.available_width() - 2.0 * space::M; + let layout = |ui: &Ui, words: &str, font, color| ui.painter().layout(words.into(), font, color, wide); + let why = layout(ui, &known.why, fonts::ui(text::LABEL), t.on_secondary_container); + let verdict = self.check.found.as_ref().map(|f| match f { + Ok(c) => (c.text(), c.verdict() == Verdict::Different), + Err(why) => (why.clone(), true), + }); + let verdict = verdict.map(|(words, bad)| layout(ui, &words, fonts::ui(text::LABEL), if bad { t.error } else { t.on_secondary_container })); + let below = verdict.as_ref().map_or(0.0, |v| v.size().y + space::S); + let height = space::M + 20.0 + why.size().y + space::XS + rows * size::HIT + below + space::M; + let rect = plate(ui, t.secondary_container, height, &head); + let (x, mut y) = (rect.left() + space::M, rect.top() + space::M); + left(ui.painter(), pos2(x, y + 9.0), line(ui.painter(), &head, fonts::med(text::BODY), t.on_secondary_container, wide)); + y += 20.0; + ui.painter().galley(pos2(x, y), why.clone(), t.on_secondary_container); + y += why.size().y + space::XS; + let area = Rect::from_min_size(pos2(x - space::XS, y), vec2(wide, rows * size::HIT)); + let mut child = ui.new_child(UiBuilder::new().max_rect(area).id_salt("known")); + child.spacing_mut().item_spacing.y = 0.0; + for (i, c) in known.choices.iter().enumerate() { + if Pick1::new(&c.label()).enabled(!self.check.busy()).radio(&mut child, t, known.chosen == i).clicked() { + known.chosen = i; + } + } + if let Some(verdict) = verdict { + ui.painter().galley(pos2(x, area.bottom() + space::S), verdict, t.on_secondary_container); + } + } + + /// Many links: which of them. + fn list(&mut self, ui: &mut Ui, t: &Theme) { + let on = self.lines.iter().filter(|l| l.on).count(); + let twins = self.lines.iter().filter(|l| l.known.is_some()).count(); + let mut all = on == self.lines.len(); + ui.horizontal(|ui| { + let words = tr!("add.chosen", n = on, all = self.lines.len()); + if Pick1::new(&words).mixed(on > 0 && !all).checkbox(ui, t, &mut all).changed() { + self.lines.iter_mut().for_each(|l| l.on = all); + } + }); + let side = size::HIT + space::XS; + let height = (self.lines.len() as f32).min(SEEN) * side + 2.0 * space::XS; + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + ui.painter().rect_filled(rect, cr(radius::M), t.lowest); + let mut child = ui.new_child(UiBuilder::new().max_rect(rect.shrink2(vec2(space::S, space::XS))).id_salt("batch")); + child.spacing_mut().item_spacing.y = space::XS; + let area = ScrollArea::vertical().id_salt("batch").max_height(height - 2.0 * space::XS).auto_shrink(false); + area.show_rows(&mut child, size::HIT, self.lines.len(), |ui, seen| { + for l in &mut self.lines[seen] { + let width = ui.available_width() - space::S; + let (row, r) = ui.allocate_exact_size(vec2(width, size::HIT), Sense::hover()); + let word = if l.known.is_some() { tr!("add.known") } else { String::new() }; + let note = line(ui.painter(), &word, fonts::ui(text::LABEL), t.warning, width / 2.0); + let end = row.right() - note.size().x; + left(ui.painter(), pos2(end, row.center().y), note); + let room = Rect::from_min_max(row.min, pos2(end - space::S, row.bottom())); + let mut place = ui.new_child(UiBuilder::new().max_rect(room).id_salt(&l.url)); + let label = if l.name.is_empty() { &l.url } else { &l.name }; + Pick1::new(label).checkbox(&mut place, t, &mut l.on); + tip(&r, t, &l.url, ""); + } + }); + if twins > 0 { + let options = [Twice::Skip, Twice::Resume, Twice::Download]; + let words = ["skip", "resume", "again"].map(|w| strings::text(&format!("add.twice.{w}"), &[])); + let mut chosen = options.iter().position(|o| *o == self.twice).unwrap_or(0); + if Combo::new(&tr!("add.twice", n = twins), &words, ui.available_width()).show(ui, t, &mut chosen) { + self.twice = options[chosen]; + let again = self.twice == Twice::Download; + self.lines.iter_mut().filter(|l| l.known.is_some()).for_each(|l| l.on = again); + } + } + } + + fn where_to(&mut self, ui: &mut Ui, t: &Theme, cx: &Cx, wrong: &Wrong) { + let free = match self.space { + Some(space) if self.no_room() => tr!("add.no_room", free = amount(space), size = amount(self.size().unwrap_or_default())), + Some(space) => tr!("add.free", free = amount(space)), + None => String::new(), + }; + let error = wrong.folder.clone().or_else(|| self.no_room().then(|| free.clone())); + let buttons = 2.0 * size::CONTROL + space::S; + let wide = ui.available_width() - buttons - space::S; + ui.horizontal_top(|ui| { + let r = Field::new(&tr!("add.folder")).help(&free).error(error.as_deref()).width(wide).show(ui, t, &mut self.folder); + if r.changed() { + self.folder_own = true; + } else if self.folder.trim().is_empty() && !r.has_focus() { + // The usual one again. + self.folder_own = false; + } + let (rect, _) = ui.allocate_exact_size(vec2(buttons, size::CONTROL), Sense::hover()); + let at = |i: f32| Rect::from_center_size(pos2(rect.left() + (size::CONTROL + space::S) * i + size::CONTROL / 2.0, r.rect.center().y), Vec2::splat(size::CONTROL)); + let mut child = ui.new_child(UiBuilder::new().max_rect(at(0.0)).id_salt("recent")); + let recent = Button::icon("history", &tr!("add.recent")).enabled(!cx.folders.recent.is_empty()).show(&mut child, t); + let items = || cx.folders.recent.iter().map(|f| Item::new(f.display().to_string(), f.clone()).icon("folder")).collect(); + if let Some(folder) = menu::below(&child, t, &recent, items) { + (self.folder, self.folder_own) = (folder.display().to_string(), true); + } + let mut child = ui.new_child(UiBuilder::new().max_rect(at(1.0)).id_salt("choose")); + if Button::icon("folder_open", &tr!("add.choose")).show(&mut child, t).clicked() && self.picker.is_none() { + self.choose(Pick::Folder); + } + }); + } + + fn how(&mut self, ui: &mut Ui, t: &Theme, cx: &Cx, wrong: &Wrong) { + let queues: Vec = cx.lists.queues.iter().map(|q| q.id).collect(); + let names: Vec = queues.iter().map(|q| queue_name(cx.lists, *q)).collect(); + let priorities: Vec = Priority::ALL.iter().map(|p| strings::text(&format!("priority.{}", p.name()), &[])).collect(); + let starts = [tr!("add.start_now"), tr!("add.start_later"), tr!("add.start_at")]; + columns(ui, "how", 3, size::CONTROL + space::L + space::XS, |ui, i, width| match i { + 0 => { + let mut chosen = queues.iter().position(|q| *q == self.queue).unwrap_or(0); + if Combo::new(&tr!("add.queue"), &names, width).show(ui, t, &mut chosen) { + self.queue = queues[chosen]; + } + } + 1 => { + let mut chosen = Priority::ALL.iter().position(|p| *p == self.priority).unwrap_or(0); + if Combo::new(&tr!("add.priority"), &priorities, width).show(ui, t, &mut chosen) { + self.priority = Priority::ALL[chosen]; + } + } + _ => { + let all = [When::Now, When::Later, When::At]; + let mut chosen = all.iter().position(|w| *w == self.when).unwrap_or(0); + if Combo::new(&tr!("add.start"), &starts, width).show(ui, t, &mut chosen) { + self.when = all[chosen]; + } + } + }); + if self.when == When::At { + // Before anything is written it only says how. + let bad = wrong.at.as_deref().filter(|_| !self.at.trim().is_empty()); + Field::new(&tr!("add.at")).hint("22:30").help(&tr!("add.at_help")).error(bad).show(ui, t, &mut self.at); + } + } + + fn rest(&mut self, ui: &mut Ui, t: &Theme, wrong: &Wrong) { + columns(ui, "much", 2, NUMBER, |ui, i, width| { + if i == 0 { + Number { label: &tr!("add.limit"), unit: &tr!("unit.kb_s"), range: 0.0..=10_000_000.0, step: 64.0, enabled: true, width, bare: false }.show(ui, t, &mut self.limit); + } else { + Number { label: &tr!("add.most_parts"), unit: "", range: 0.0..=64.0, step: 1.0, enabled: true, width, bare: false }.show(ui, t, &mut self.parts); + } + }); + let host = self.batch.links.first().map(String::as_str).and_then(super::super::settings::site_of); + let whose = host.map_or_else(|| tr!("add.login_help"), |host| tr!("add.login_for", host = host)); + columns(ui, "login", 2, NUMBER, |ui, i, width| { + if i == 0 { + let r = Field::new(&tr!("login.user")).help(&whose).width(width).show(ui, t, &mut self.login.user); + // A field gives the focus up in the frame of a click beside it. + if self.focus_login && !ui.input(|i| i.pointer.any_click()) { + self.focus_login = false; + r.request_focus(); + r.scroll_to_me(None); + } + } else { + Field::new(&tr!("login.password")).password().width(width).show(ui, t, &mut self.login.password); + } + }); + Field::new(&tr!("add.referrer")).show(ui, t, &mut self.referrer); + Field::new(&tr!("site.agent")).show(ui, t, &mut self.agent); + Field::new(&tr!("add.cookies")).hint("name=value; other=value").password().show(ui, t, &mut self.cookies); + Field::new(&tr!("add.headers")).hint("X-Name: value").rows(2).error(wrong.headers.as_deref()).show(ui, t, &mut self.headers); + Field::new(&tr!("set.proxy")).hint("socks5://127.0.0.1:1080").help(&tr!("add.proxy_help")).error(wrong.proxy.as_deref()).show(ui, t, &mut self.proxy); + if !self.many() { + Field::new(&tr!("add.mirrors")).rows(2).error(wrong.mirrors.as_deref()).show(ui, t, &mut self.mirrors); + Field::new(&tr!("add.checksum")).hint("sha256:…").error(wrong.checksum.as_deref()).show(ui, t, &mut self.checksum); + } + } +} diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs new file mode 100644 index 0000000..562ede9 --- /dev/null +++ b/crates/app/src/views/add/mod.rs @@ -0,0 +1,938 @@ +//! Adding downloads: what the dialog knows and does. `Adding::ask` opens it from anywhere. + +mod draw; +mod relink; + +pub use relink::Relink; + +use crate::bridge::{Bridge, Lists, beside, download_folder, poll}; +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 chrono::{Days, Local, NaiveDateTime, NaiveTime}; +use eframe::egui::{Context, Ui}; +use medlar_core::auth::{Login, take_login}; +use medlar_core::batch::Batch; +use medlar_core::duplicate::{By, Duplicate, Known, New}; +use medlar_core::error::Fix; +use medlar_core::http::safe_name; +use medlar_core::manager::{self, Command, Probed, Reply}; +use medlar_core::model::{ErrorKind, Priority, QueueId, State, Task, TaskId, Time}; +use medlar_core::net_state::Bus; +use medlar_core::portal::{self, Pick}; +use medlar_core::relink::{Checked, Incoming, NewLink, Strength, Verdict, find}; +use medlar_core::secret::{self, Secret}; +use medlar_core::settings::Settings; +use medlar_core::snapshot::Snapshot; +use medlar_core::verify::Checksum; +use medlar_core::{disk, metalink, redact, site, tr}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use tokio::sync::oneshot; +use url::Url; + +/// Seconds without a change before a link is looked at. +const PAUSE: f64 = 0.5; +/// Folders that are remembered. +const RECENT: usize = 8; +/// A list is not larger. +const LIST: u64 = 8 << 20; + +/// What is to be added. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Request { + /// The links, among anything else. + pub text: String, + /// Brackets are parts of the links, as in all that comes from a program. + pub literal: bool, + /// A file with links. + pub list: Option, + pub name: Option, + pub size: Option, + pub mime: Option, + /// The page the link is on. + pub page: Option, + pub user_agent: Option, + /// As in a `Cookie` header. + pub cookies: Option, + pub headers: Vec<(String, String)>, +} + +/// The folders that were chosen. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Folders { + /// The latest first. + pub recent: Vec, + /// By what the file is. + pub by_kind: BTreeMap, +} + +impl Folders { + fn chose(&mut self, folder: &Path, kind: Option) { + self.recent.retain(|f| f != folder); + self.recent.insert(0, folder.into()); + self.recent.truncate(RECENT); + if let Some(kind) = kind.filter(|k| *k != Kind::Other) { + self.by_kind.insert(kind_key(kind).into(), folder.into()); + } + } + + fn of(&self, kind: Kind) -> Option { + self.by_kind.get(kind_key(kind)).cloned() + } +} + +/// What the dialog needs of the app. +pub struct Cx<'a> { + pub settings: &'a Settings, + pub bridge: &'a Bridge, + pub shot: &'a Snapshot, + pub lists: &'a Lists, + pub folders: &'a mut Folders, + pub toasts: &'a mut Toasts, + pub outside: fn(&str), +} + +/// The dialog, and what waits for it. +#[derive(Default)] +pub struct Adding { + open: Option>, + next: VecDeque, + relink: Option, +} + +impl Adding { + /// Opens the dialog, now or after the one that is open. + pub fn ask(&mut self, request: Request) { + if self.next.len() < 100 && !self.next.contains(&request) { + self.next.push_back(request); + } + } + + /// Opens the dialog without asking any server, for tests and pictures: `set` says what it answered. + pub fn open_still(&mut self, request: Request, settings: &Settings, set: impl FnOnce(&mut Add)) { + let mut add = Add::new(request, settings); + add.still = true; + add.space = Some(212_000_000_000); + add.read_text(); + if let Some(link) = add.single() { + add.name = name_of(link); + } + set(&mut add); + self.open = Some(Box::new(add)); + } + + /// Asks for a new link for a download. + pub fn relink(&mut self, task: &Task) { + self.relink = Some(Relink::new(task)); + } + + /// The dialog that is open. + pub fn now(&mut self) -> Option<&mut Add> { + self.open.as_deref_mut() + } + + pub fn relinking(&mut self) -> Option<&mut Relink> { + self.relink.as_mut() + } + + /// Draws what is open. The download to go to comes back. + pub fn show(&mut self, ui: &Ui, t: &crate::theme::Theme, cx: &mut Cx) -> Option { + if let Some(relink) = &mut self.relink + && relink.show(ui, t, cx) + { + self.relink = None; + } + if self.open.is_none() && self.relink.is_none() { + self.open = self.next.pop_front().map(|r| Box::new(Add::new(r, cx.settings))); + } + let add = self.open.as_mut()?; + let gone = add.show(ui, t, cx); + let show = add.go_to.take(); + if gone { + self.open = None; + if !self.next.is_empty() { + ui.ctx().request_repaint(); + } + } + show + } +} + +/// What can be done with a link that is known. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Choice { + Continue, + Resume, + Show, + /// As a new file. + Download, +} + +impl Choice { + fn label(self) -> String { + match self { + Choice::Continue => tr!("add.continue"), + Choice::Resume => tr!("add.resume"), + Choice::Show => tr!("add.show"), + Choice::Download => tr!("add.again"), + } + } + + fn verb(self) -> String { + match self { + Choice::Continue => tr!("add.continue_do"), + Choice::Resume => tr!("fix.resume"), + Choice::Show => tr!("add.show_do"), + Choice::Download => tr!("add.do"), + } + } +} + +/// A download in the list that the link has to do with. +pub struct Match { + pub task: Arc, + pub why: String, + pub choices: Vec, + pub chosen: usize, +} + +/// A comparison with a new link, before anything changes. +#[derive(Default)] +pub struct Checking { + asked: Option>>, + pub found: Option>, +} + +impl Checking { + fn start(&mut self, bridge: &Bridge, id: TaskId, link: NewLink, secret: Option) { + self.found = None; + self.asked = bridge.check(id, link, secret); + if self.asked.is_none() { + self.found = Some(Err(tr!("manager.closed"))); + } + } + + /// True when the answer has just come. + fn follow(&mut self, ctx: &Context) -> bool { + let Some(answer) = self.asked.as_mut().and_then(|a| poll(a, ctx)) else { return false }; + self.asked = None; + self.found = Some(answer.unwrap_or_else(|_| Err(tr!("manager.closed")))); + true + } + + pub fn busy(&self) -> bool { + self.asked.is_some() + } + + fn good(&self) -> Option<&Checked> { + self.found.as_ref()?.as_ref().ok().filter(|c| c.verdict() != Verdict::Different) + } + + fn refused(&self) -> bool { + matches!(&self.found, Some(Ok(c)) if c.verdict() == Verdict::Different) + } + + /// Forgets it and what it left in the keyring. + fn clear(&mut self, bridge: &Bridge, kept: Option<&String>) { + self.asked = None; + if let Some(Ok(checked)) = self.found.take() { + bridge.drop_check(&checked, kept); + } + } + + fn go_on(&mut self, bridge: &Bridge, id: TaskId) { + if let Some(Ok(checked)) = self.found.take() { + bridge.send(Command::Continue { id, checked: Box::new(checked) }); + } + } +} + +/// What is asked of the server; a change asks anew. +#[derive(Debug, Clone, PartialEq)] +struct Asked { + task: Task, + secret: Option, +} + +/// What the server says about the link. +#[derive(Default)] +pub enum Look { + #[default] + Nothing, + /// Until this time. + Waits(f64), + Asks(Reply), + Found(Probed), + Failed(Option, String), +} + +impl Look { + fn busy(&self) -> bool { + matches!(self, Look::Waits(_) | Look::Asks(_)) + } +} + +/// One of many links. +pub struct Line { + pub url: String, + pub name: String, + pub known: Option, + pub on: bool, +} + +/// What happens with links of a batch that are in the list already. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Twice { + Skip, + Resume, + Download, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum When { + #[default] + Now, + /// Paused. + Later, + At, +} + +/// Whether and why not. +#[derive(Default)] +struct Wrong { + name: Option, + folder: Option, + at: Option, + headers: Option, + proxy: Option, + mirrors: Option, + checksum: Option, +} + +impl Wrong { + fn any(&self) -> bool { + self.in_more() || [&self.name, &self.folder, &self.at].iter().any(|w| w.is_some()) + } + + fn in_more(&self) -> bool { + [&self.headers, &self.proxy, &self.mirrors, &self.checksum].iter().any(|w| w.is_some()) + } +} + +/// What the file chooser gave; an error when there is none. +type Picked = Result, ()>; + +pub struct Add { + open: bool, + from: Request, + pub text: String, + pub patterns: bool, + /// Of this text. + read: Option<(String, bool)>, + batch: Batch, + pub lines: Vec, + pub twice: Twice, + pub name: String, + /// The user wrote it. + name_own: bool, + pub folder: String, + folder_own: bool, + pub queue: QueueId, + pub priority: Priority, + /// KiB per second. + pub limit: f64, + pub parts: f64, + pub when: When, + pub at: String, + /// The second half is open. + pub more: bool, + pub referrer: String, + pub agent: String, + pub cookies: String, + pub headers: String, + pub login: Login, + pub proxy: String, + pub mirrors: String, + pub checksum: String, + focus_login: bool, + focus_links: bool, + asked: Option, + pub look: Look, + /// Tests put answers here themselves. + pub still: bool, + /// What `known` was found for. + sought: Option<(String, String, String, String, Option)>, + pub known: Option, + pub check: Checking, + space_of: Option, + space_asked: Option>>, + pub space: Option, + list: Option>>, + picker: Option<(Pick, oneshot::Receiver)>, + go_to: Option, +} + +impl Add { + pub fn new(mut from: Request, settings: &Settings) -> Add { + // Secrets among the headers are cookies and logins. + let (secret, plain): (Vec<_>, Vec<_>) = std::mem::take(&mut from.headers).into_iter().partition(|(n, _)| redact::is_secret_header(n)); + let take = |from: &mut Vec<(String, String)>, name: &str| from.iter().position(|(n, _)| n.eq_ignore_ascii_case(name)).map(|i| from.remove(i).1); + let (mut secret, mut plain) = (secret, plain); + let cookies = from.cookies.take().or_else(|| take(&mut secret, "cookie")).unwrap_or_default(); + let referrer = take(&mut plain, "referer").or_else(|| from.page.clone()).unwrap_or_default(); + let agent = from.user_agent.take().or_else(|| take(&mut plain, "user-agent")).unwrap_or_default(); + let headers: Vec<_> = plain.iter().chain(&secret).map(|(n, v)| format!("{n}: {v}")).collect(); + let mut add = Add { + open: true, + text: from.text.clone(), + patterns: !from.literal, + read: None, + batch: Batch::default(), + lines: vec![], + twice: Twice::Skip, + name: from.name.clone().unwrap_or_default(), + name_own: from.name.is_some(), + folder: download_folder(settings).display().to_string(), + folder_own: false, + queue: medlar_core::model::MAIN_QUEUE, + priority: Priority::Normal, + limit: 0.0, + parts: 0.0, + when: When::Now, + at: String::new(), + more: false, + referrer, + agent, + cookies, + headers: headers.join("\n"), + login: Login::default(), + proxy: String::new(), + mirrors: String::new(), + checksum: String::new(), + focus_login: false, + focus_links: true, + asked: None, + look: Look::Nothing, + still: false, + sought: None, + known: None, + check: Checking::default(), + space_of: None, + space_asked: None, + space: None, + list: None, + picker: None, + go_to: None, + from, + }; + if let Some(file) = add.from.list.clone() { + add.read_list(file); + } + add + } + + /// The only link. + pub fn single(&self) -> Option<&str> { + match &self.batch.links[..] { + [one] => Some(one), + _ => None, + } + } + + pub fn many(&self) -> bool { + self.batch.links.len() > 1 + } + + fn kind(&self) -> Kind { + let mime = match &self.look { + Look::Found(p) => p.mime.as_deref(), + _ => self.from.mime.as_deref(), + }; + kind_of(&self.name, mime) + } + + fn size(&self) -> Option { + match &self.look { + Look::Found(p) => p.size, + _ => self.from.size, + } + } + + /// Reads a list beside the window. + pub fn read_list(&mut self, file: PathBuf) { + self.list = Some(beside(move || { + let name = file.file_name().unwrap_or_default().to_string_lossy().into_owned(); + // One file from many servers, not many files. + let small = !metalink::is(&name, None) && std::fs::metadata(&file).is_ok_and(|m| m.is_file() && m.len() <= LIST); + if !small { + return Err(tr!("add.list_bad", name = name)); + } + std::fs::read(&file).map(|b| String::from_utf8_lossy(&b).into_owned()).map_err(|_| tr!("add.list_unread", name = name)) + })); + } + + fn choose(&mut self, pick: Pick) { + let title = if pick == Pick::File { tr!("add.open_list") } else { tr!("add.folder") }; + let asked = beside(move || { + let made = tokio::runtime::Builder::new_current_thread().enable_all().build(); + let runtime = made.map_err(|e| log::warn!("file chooser: {e}"))?; + runtime.block_on(portal::choose(&Bus::Session, pick, &title)).map_err(|e| log::warn!("file chooser: {e}")) + }); + self.picker = Some((pick, asked)); + } + + /// Everything that comes by itself: lists, the server's answer, what is known, free space. + fn follow(&mut self, ctx: &Context, cx: &mut Cx) { + if let Some(answer) = self.list.as_mut().and_then(|l| poll(l, ctx)) { + self.list = None; + match answer { + Ok(Ok(text)) => self.take_list(&text, cx), + Ok(Err(why)) => cx.toasts.error(why, None), + Err(_) => {} + } + } + if let Some((pick, answer)) = self.picker.as_mut().and_then(|(pick, asked)| Some((*pick, poll(asked, ctx)?))) { + self.picker = None; + match answer { + Ok(Ok(Some(path))) if pick == Pick::File => self.read_list(path), + Ok(Ok(Some(path))) => (self.folder, self.folder_own) = (path.display().to_string(), true), + Ok(Ok(None)) | Err(_) => {} + Ok(Err(())) => cx.toasts.error(tr!("add.no_chooser"), None), + } + } + self.read_text(); + self.usual_folder(cx); + self.ask_server(ctx, cx); + self.seek(cx); + self.ask_space(ctx); + if self.check.follow(ctx) && self.check.good().is_some_and(|c| c.verdict() == Verdict::Same) { + self.finish_check(cx); + } else if self.check.refused() + && let Some(known) = &mut self.known + { + // What is left to do. + known.choices.retain(|c| *c != Choice::Continue); + known.chosen = known.chosen.min(known.choices.len() - 1); + } + } + + fn take_list(&mut self, text: &str, cx: &mut Cx) { + let found = Batch::of(text, false).links; + if found.is_empty() { + return cx.toasts.error(tr!("add.list_empty"), None); + } + if self.text.trim().is_empty() { + (self.text, self.patterns) = (String::new(), false); + } else if !self.text.ends_with('\n') { + self.text.push('\n'); + } + self.text += &found.join("\n"); + } + + fn read_text(&mut self) { + let now = (self.text.clone(), self.patterns); + if self.read.as_ref() == Some(&now) { + return; + } + self.batch = Batch::of(&now.0, now.1); + self.read = Some(now); + let off: HashSet = self.lines.drain(..).filter(|l| !l.on).map(|l| l.url).collect(); + self.sought = None; + if self.many() { + let line = |url: &String| Line { url: url.clone(), name: name_of(url), known: None, on: !off.contains(url) }; + self.lines = self.batch.links.iter().map(line).collect(); + } + } + + /// Until the user wrote another. + fn usual_folder(&mut self, cx: &Cx) { + if self.folder_own { + return; + } + let url = self.batch.links.first().and_then(|l| Url::parse(l).ok()); + let site = url.and_then(|u| site::rules(&cx.settings.sites, &u).folder); + let queue = cx.lists.queues.iter().find(|q| q.id == self.queue).and_then(|q| q.folder.clone()); + let kind = if self.single().is_some() { cx.folders.of(self.kind()) } else { None }; + self.folder = site.or(queue).or(kind).unwrap_or_else(|| download_folder(cx.settings)).display().to_string(); + } + + fn ask_server(&mut self, ctx: &Context, cx: &Cx) { + let now = ctx.input(|i| i.time); + let single = self.single().map(str::to_string).filter(|l| Url::parse(l).is_ok_and(|u| u.has_host())); + let asked = single.map(|link| { + let (url, login) = take_login(&link); + let task = Task { url: url.clone(), headers: self.plain_headers(), proxy: some(&self.proxy), added_at: 0, ..Task::default() }; + Asked { task, secret: self.secret(&url, login) } + }); + if self.still { + return; + } + if self.asked != asked { + self.look = if asked.is_some() { Look::Waits(now + PAUSE) } else { Look::Nothing }; + self.asked = asked; + if !self.name_own { + self.name = self.single().map(name_of).unwrap_or_default(); + } + } + match &mut self.look { + Look::Waits(until) if now < *until => ctx.request_repaint_after_secs((*until - now) as f32), + Look::Waits(_) => { + let reply = self.asked.clone().and_then(|a| cx.bridge.probe(a.task, a.secret)); + self.look = reply.map_or(Look::Nothing, Look::Asks); + ctx.request_repaint(); + } + Look::Asks(reply) => match poll(reply, ctx) { + Some(Ok(found)) => 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 => {} + }, + _ => {} + } + } + + /// What the server said. + pub fn learned(&mut self, found: Probed) { + if !self.name_own { + self.name = found.name.clone(); + } + self.look = Look::Found(found); + } + + pub fn failed(&mut self, kind: ErrorKind, why: &str) { + self.look = Look::Failed(Some(kind), why.into()); + } + + fn ask_again(&mut self) { + self.asked = None; + } + + /// What the list has of this already. + fn seek(&mut self, cx: &Cx) { + let sum = self.checksum_text().unwrap_or_default(); + let now = (self.single().unwrap_or_default().to_string(), self.name.clone(), self.folder.clone(), sum, self.size()); + if self.sought.as_ref() == Some(&now) { + return; + } + let (link, name, folder, sum, size) = &now; + let known = Known::new(cx.shot.iter().map(|v| &*v.task)); + let folder = Path::new(folder.trim()); + for line in &mut self.lines { + let was = line.known; + line.known = known.find(&New { url: &line.url, ..New::default() }); + if line.known.is_some() && was.is_none() { + line.on = false; + } + } + let checksum = Some(sum.as_str()).filter(|s| !s.is_empty()); + let found = self.single().and_then(|_| known.find(&New { url: link, name, folder: Some(folder), checksum })); + let incoming = Incoming { url: take_login(link).0, name: self.name_own.then(|| name.clone()), size: *size, page: some(&self.referrer) }; + let best = self.single().and_then(|_| find(&incoming, cx.shot.iter().map(|v| &*v.task)).into_iter().find(|m| m.awaited || m.strength >= Strength::Likely)); + self.sought = Some(now.clone()); + // The same link with nothing new to send is simply resumed. + let fresh = !self.cookies.is_empty() || !self.login.user.is_empty(); + let twin = found.filter(|d| d.by != By::Name && !(d.by == By::Link && fresh && best.is_some_and(|m| m.id == d.id))); + let said = match (twin, best, found) { + (Some(d), ..) => cx.shot.get(d.id).map(|v| (v.task.clone(), by_words(d.by, v.state()), twin_choices(v.state()))), + (None, Some(m), _) => cx.shot.get(m.id).map(|v| { + let why = match (m.awaited, size.is_some() && *size == v.task.size, m.strength) { + (true, ..) => tr!("add.awaited"), + (_, true, _) => tr!("add.same_size"), + (_, _, Strength::Strong) => tr!("add.same_link"), + _ => tr!("add.alike"), + }; + (v.task.clone(), why, vec![Choice::Continue, Choice::Download]) + }), + (None, None, Some(d)) => cx.shot.get(d.id).map(|v| (v.task.clone(), by_words(d.by, v.state()), vec![Choice::Download, Choice::Show])), + _ => None, + }; + let same = |k: &Match, id| k.task.id == id; + let before = self.known.take(); + let id = said.as_ref().map(|s| s.0.id); + if before.as_ref().is_some_and(|k| Some(k.task.id) != id) { + let kept = before.as_ref().and_then(|k| k.task.secret.clone()); + self.check.clear(cx.bridge, kept.as_ref()); + } + self.known = said.map(|(task, why, choices)| { + let old = before.filter(|k| same(k, task.id) && k.choices == choices).map_or(0, |k| k.chosen); + Match { task, why, choices, chosen: old } + }); + } + + fn ask_space(&mut self, ctx: &Context) { + let folder = PathBuf::from(self.folder.trim()); + if folder.is_absolute() && self.space_of.as_ref() != Some(&folder) && !self.still { + self.space_of = Some(folder.clone()); + self.space_asked = Some(beside(move || disk::free(&folder))); + } + if let Some(answer) = self.space_asked.as_mut().and_then(|s| poll(s, ctx)) { + self.space_asked = None; + self.space = answer.ok().flatten(); + } + } + + /// The file doesn't fit. + fn no_room(&self) -> bool { + self.size().zip(self.space).is_some_and(|(size, space)| size > space) + } + + fn checksum_text(&self) -> Option { + self.checksum.parse::().ok().map(|c| c.to_string()) + } + + fn header_lines(&self) -> Option> { + let parse = |l: &str| { + let (name, value) = l.split_once(':')?; + let (name, value) = (name.trim(), value.trim()); + let good = !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) && !value.chars().any(char::is_control); + good.then(|| (name.to_string(), value.to_string())) + }; + self.headers.lines().map(str::trim).filter(|l| !l.is_empty()).map(parse).collect() + } + + /// Those that are no secret. + fn plain_headers(&self) -> Vec<(String, String)> { + let own = self.header_lines().unwrap_or_default().into_iter().filter(|(n, _)| !redact::is_secret_header(n)); + let usual = [("Referer", &self.referrer), ("User-Agent", &self.agent)].into_iter().filter_map(|(n, v)| Some((n.to_string(), some(v)?))); + usual.chain(own).collect() + } + + /// For this link and others of its site. A login in the link counts before the one in the field. + fn secret(&self, url: &str, login: Option) -> Option { + let own = Some(self.login.clone()).filter(|l| !l.user.is_empty()); + let headers: Vec<_> = self.header_lines().unwrap_or_default().into_iter().filter(|(n, _)| redact::is_secret_header(n)).collect(); + let secret = Secret { home: Some(url.into()), login: login.or(own), cookies: some(&self.cookies), headers }; + (secret.login.is_some() || secret.cookies.is_some() || !secret.headers.is_empty()).then_some(secret) + } + + fn wrong(&self) -> Wrong { + let name = self.name.trim(); + let bad = |is: bool, words: &dyn Fn() -> String| is.then(words); + let proxy = self.proxy.trim(); + let mirrors = self.mirrors.lines().any(|l| !l.trim().is_empty() && Batch::of(l, false).links.len() != 1); + Wrong { + name: bad(!self.many() && !name.is_empty() && safe_name(name).is_none(), &|| tr!("manager.name")), + folder: bad(!Path::new(self.folder.trim()).is_absolute(), &|| tr!("set.folder.relative")), + at: bad(self.when == When::At && start_of(&self.at, Local::now().naive_local()).is_none(), &|| tr!("add.at_bad")), + headers: bad(self.header_lines().is_none(), &|| tr!("add.headers_bad")), + proxy: if matches!(proxy, "" | "system" | "direct") { None } else { super::settings::network::proxy_error(proxy) }, + mirrors: bad(mirrors, &|| tr!("add.mirrors_bad")), + checksum: bad(!self.checksum.trim().is_empty() && self.checksum_text().is_none(), &|| tr!("add.checksum_bad")), + } + } + + fn choice(&self) -> Choice { + self.known.as_ref().and_then(|k| k.choices.get(k.chosen)).copied().unwrap_or(Choice::Download) + } + + /// How many the main button adds or resumes. + fn count(&self) -> usize { + if self.many() { self.lines.iter().filter(|l| l.on || l.known.is_some() && self.twice != Twice::Skip).count() } else { self.batch.links.len() } + } + + /// The downloads as they would be, and the secrets under the names they have. + pub fn tasks(&self) -> (Vec, Vec<(String, Secret)>) { + let (state, start_at) = match self.when { + When::Now => (State::Queued, None), + When::Later => (State::Paused, None), + When::At => (State::Queued, start_of(&self.at, Local::now().naive_local())), + }; + let single = self.single(); + let links: Vec<&str> = match single { + Some(link) => vec![link], + None => self.lines.iter().filter(|l| l.on || l.known.is_some() && self.twice == Twice::Download).map(|l| &*l.url).collect(), + }; + let common = Task { + folder: PathBuf::from(self.folder.trim()), + queue: self.queue, + priority: self.priority, + speed_limit: Some((self.limit * 1024.0) as u64).filter(|n| *n > 0), + max_parts: Some(self.parts as u32).filter(|n| *n > 0), + headers: self.plain_headers(), + proxy: some(&self.proxy), + source_page: self.from.page.clone().or_else(|| some(&self.referrer)).filter(|p| p.starts_with("http://") || p.starts_with("https://")), + state, + start_at, + ..Task::default() + }; + // One item for each site and login. Others can't use it: it has a home. + let mut names: HashMap<(String, Option<(String, String)>), String> = HashMap::new(); + let (mut tasks, mut secrets) = (vec![], vec![]); + // What was typed is for the site of the first link. + let home = links.first().and_then(|l| place(l)); + for link in links { + let (url, login) = take_login(link); + let at = place(&url); + let mut secret = if at == home { self.secret(&url, login) } else { login.map(|l| Secret { home: Some(url.clone()), login: Some(l), ..Secret::default() }) }; + let name = secret.take().zip(at).map(|(secret, at)| { + names.entry((at, secret.login.clone().map(|l| (l.user, l.password)))).or_insert_with(|| { + let name = secret::task_name(); + secrets.push((name.clone(), secret)); + name + }) + }); + let secret = name.map(|n| n.clone()); + tasks.push(Task { url, secret, ..common.clone() }); + } + if let ([task], Some(_)) = (&mut tasks[..], single) { + // Without one the server names it. + task.name = if self.name_own { self.name.trim().to_string() } else { String::new() }; + task.mirrors = Batch::of(&self.mirrors, false).links.iter().map(|m| take_login(m).0).collect(); + task.checksum = self.checksum_text(); + } + (tasks, secrets) + } + + fn new_link(&self) -> Option<(NewLink, Option)> { + let (url, login) = take_login(self.single()?); + let secret = self.secret(&url, login); + let link = NewLink { url, headers: self.plain_headers(), secret: None, source_page: self.from.page.clone() }; + Some((link, secret)) + } + + fn finish_check(&mut self, cx: &mut Cx) { + let Some(known) = &self.known else { return }; + self.check.go_on(cx.bridge, known.task.id); + cx.toasts.info("play_arrow", tr!("add.continues", name = known.task.name)); + self.open = false; + } + + /// The main button. + fn act(&mut self, cx: &mut Cx) { + let known = self.known.as_ref().map(|k| k.task.clone()); + match (self.choice(), known) { + (Choice::Continue, Some(task)) => { + if self.check.good().is_some() { + self.finish_check(cx); + } else if let Some((link, secret)) = self.new_link() { + self.check.start(cx.bridge, task.id, link, secret); + } + return; + } + (Choice::Resume, Some(task)) => cx.bridge.send(Command::Resume(task.id)), + (Choice::Show, Some(task)) => self.go_to = Some(task.id), + _ => self.download(cx), + } + self.leave(cx); + } + + fn download(&mut self, cx: &mut Cx) { + if self.many() && self.twice == Twice::Resume { + for d in self.lines.iter().filter(|l| !l.on).filter_map(|l| l.known) { + cx.bridge.send(Command::Resume(d.id)); + } + } + let (tasks, secrets) = self.tasks(); + if self.folder_own { + let kind = self.single().is_some().then(|| self.kind()); + cx.folders.chose(Path::new(self.folder.trim()), kind); + } + if tasks.len() > 1 { + cx.toasts.info("download", tr!("add.added", n = tasks.len())); + } + cx.bridge.add(tasks, secrets); + } + + fn leave(&mut self, cx: &Cx) { + let kept = self.known.as_ref().and_then(|k| k.task.secret.clone()); + self.check.clear(cx.bridge, kept.as_ref()); + self.open = false; + } + + /// What helps after the server refused. + fn fix(&self) -> Option<(Fix, String)> { + let Look::Failed(kind, _) = &self.look else { return None }; + let page = some(&self.referrer).is_some_and(|p| p.starts_with("http")); + match kind.map(ErrorKind::fix) { + Some(Fix::SignIn) => Some((Fix::SignIn, Fix::SignIn.label())), + _ if page && matches!(kind, Some(ErrorKind::Expired | ErrorKind::Forbidden | ErrorKind::NotFound)) => Some((Fix::NewLink, tr!("add.open_page"))), + Some(Fix::EditLink) => Some((Fix::EditLink, Fix::EditLink.label())), + _ => Some((Fix::TryAgain, Fix::TryAgain.label())), + } + } + + fn mend(&mut self, fix: Fix, cx: &Cx) { + match fix { + Fix::SignIn => (self.more, self.focus_login) = (true, true), + Fix::NewLink => (cx.outside)(self.referrer.trim()), + Fix::EditLink => self.focus_links = true, + _ => self.ask_again(), + } + } +} + +fn by_words(by: By, state: State) -> String { + match (by, state) { + (By::Name, _) => tr!("add.by_name"), + (By::Checksum, _) => tr!("add.by_checksum"), + (By::Link, State::Done) => tr!("add.by_link_done"), + (By::Link, _) => tr!("add.by_link"), + } +} + +fn twin_choices(state: State) -> Vec { + match state { + State::Paused | State::Failed | State::Waiting => vec![Choice::Resume, Choice::Show, Choice::Download], + _ => vec![Choice::Show, Choice::Download], + } +} + +fn some(text: &str) -> Option { + Some(text.trim().to_string()).filter(|s| !s.is_empty()) +} + +fn place(link: &str) -> Option { + let url = Url::parse(link).ok()?; + Some(format!("{}://{}:{:?}", url.scheme(), url.host_str()?, url.port_or_known_default())) +} + +/// What a link seems to lead to. +fn name_of(link: &str) -> String { + let path = Url::parse(link).ok().and_then(|u| u.path_segments().and_then(|mut s| s.rfind(|p| !p.is_empty()).map(str::to_string))); + let name = path.map(|p| percent_encoding::percent_decode_str(&p).decode_utf8_lossy().into_owned()); + name.and_then(|n| safe_name(&n)).unwrap_or_default() +} + +/// `22:30` is the next one, `2026-12-24 08:00` is that day. +fn start_of(text: &str, now: NaiveDateTime) -> Option