S016: Add dialog, batch and duplicates
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
cac5f242d4
commit
08488b4df2
29 changed files with 2809 additions and 78 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -2769,11 +2769,13 @@ dependencies = [
|
|||
"medlar-cli",
|
||||
"medlar-core",
|
||||
"medlar-testserver",
|
||||
"percent-encoding",
|
||||
"resvg",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -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<Secret>) -> Option<Reply<Probed>> {
|
||||
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<Task>, 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<Secret>) -> Option<Check> {
|
||||
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<Result<Checked, String>>;
|
||||
|
||||
/// The answer, if it is there. Draws a frame when it comes; ask no more after it.
|
||||
pub fn poll<F: Future + Unpin>(asked: &mut F, ctx: &Context) -> Option<F::Output> {
|
||||
struct Frame(Context);
|
||||
impl std::task::Wake for Frame {
|
||||
fn wake(self: Arc<Self>) {
|
||||
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<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> oneshot::Receiver<T> {
|
||||
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 },
|
||||
|
|
|
|||
|
|
@ -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::<State>(Id::unique(("dialog", id))).is_some())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct State {
|
||||
open: bool,
|
||||
|
|
|
|||
398
crates/app/src/views/add/draw.rs
Normal file
398
crates/app/src/views/add/draw.rs
Normal file
|
|
@ -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<QueueId> = cx.lists.queues.iter().map(|q| q.id).collect();
|
||||
let names: Vec<String> = queues.iter().map(|q| queue_name(cx.lists, *q)).collect();
|
||||
let priorities: Vec<String> = 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
938
crates/app/src/views/add/mod.rs
Normal file
938
crates/app/src/views/add/mod.rs
Normal file
|
|
@ -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<PathBuf>,
|
||||
pub name: Option<String>,
|
||||
pub size: Option<u64>,
|
||||
pub mime: Option<String>,
|
||||
/// The page the link is on.
|
||||
pub page: Option<String>,
|
||||
pub user_agent: Option<String>,
|
||||
/// As in a `Cookie` header.
|
||||
pub cookies: Option<String>,
|
||||
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<PathBuf>,
|
||||
/// By what the file is.
|
||||
pub by_kind: BTreeMap<String, PathBuf>,
|
||||
}
|
||||
|
||||
impl Folders {
|
||||
fn chose(&mut self, folder: &Path, kind: Option<Kind>) {
|
||||
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<PathBuf> {
|
||||
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<Click>,
|
||||
pub outside: fn(&str),
|
||||
}
|
||||
|
||||
/// The dialog, and what waits for it.
|
||||
#[derive(Default)]
|
||||
pub struct Adding {
|
||||
open: Option<Box<Add>>,
|
||||
next: VecDeque<Request>,
|
||||
relink: Option<Relink>,
|
||||
}
|
||||
|
||||
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<TaskId> {
|
||||
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<Task>,
|
||||
pub why: String,
|
||||
pub choices: Vec<Choice>,
|
||||
pub chosen: usize,
|
||||
}
|
||||
|
||||
/// A comparison with a new link, before anything changes.
|
||||
#[derive(Default)]
|
||||
pub struct Checking {
|
||||
asked: Option<oneshot::Receiver<Result<Checked, String>>>,
|
||||
pub found: Option<Result<Checked, String>>,
|
||||
}
|
||||
|
||||
impl Checking {
|
||||
fn start(&mut self, bridge: &Bridge, id: TaskId, link: NewLink, secret: Option<Secret>) {
|
||||
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<Secret>,
|
||||
}
|
||||
|
||||
/// What the server says about the link.
|
||||
#[derive(Default)]
|
||||
pub enum Look {
|
||||
#[default]
|
||||
Nothing,
|
||||
/// Until this time.
|
||||
Waits(f64),
|
||||
Asks(Reply<Probed>),
|
||||
Found(Probed),
|
||||
Failed(Option<ErrorKind>, 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<Duplicate>,
|
||||
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<String>,
|
||||
folder: Option<String>,
|
||||
at: Option<String>,
|
||||
headers: Option<String>,
|
||||
proxy: Option<String>,
|
||||
mirrors: Option<String>,
|
||||
checksum: Option<String>,
|
||||
}
|
||||
|
||||
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<Option<PathBuf>, ()>;
|
||||
|
||||
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<Line>,
|
||||
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<Asked>,
|
||||
pub look: Look,
|
||||
/// Tests put answers here themselves.
|
||||
pub still: bool,
|
||||
/// What `known` was found for.
|
||||
sought: Option<(String, String, String, String, Option<u64>)>,
|
||||
pub known: Option<Match>,
|
||||
pub check: Checking,
|
||||
space_of: Option<PathBuf>,
|
||||
space_asked: Option<oneshot::Receiver<Option<u64>>>,
|
||||
pub space: Option<u64>,
|
||||
list: Option<oneshot::Receiver<Result<String, String>>>,
|
||||
picker: Option<(Pick, oneshot::Receiver<Picked>)>,
|
||||
go_to: Option<TaskId>,
|
||||
}
|
||||
|
||||
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<u64> {
|
||||
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<String> = 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<String> {
|
||||
self.checksum.parse::<Checksum>().ok().map(|c| c.to_string())
|
||||
}
|
||||
|
||||
fn header_lines(&self) -> Option<Vec<(String, String)>> {
|
||||
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<Login>) -> Option<Secret> {
|
||||
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<Task>, 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<Secret>)> {
|
||||
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<Choice> {
|
||||
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<String> {
|
||||
Some(text.trim().to_string()).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
fn place(link: &str) -> Option<String> {
|
||||
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<Time> {
|
||||
let text = text.trim();
|
||||
let at = match NaiveTime::parse_from_str(text, "%H:%M") {
|
||||
Ok(time) if time > now.time() => now.date().and_time(time),
|
||||
Ok(time) => now.date().checked_add_days(Days::new(1))?.and_time(time),
|
||||
Err(_) => NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").ok().filter(|at| *at > now)?,
|
||||
};
|
||||
Some(at.and_local_timezone(Local).earliest()?.timestamp_millis())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn start_times() {
|
||||
let now = NaiveDateTime::parse_from_str("2026-11-25 12:00", "%Y-%m-%d %H:%M").unwrap();
|
||||
let at = |text: &str| Some(NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap().and_local_timezone(Local).earliest()?.timestamp_millis());
|
||||
assert_eq!(start_of(" 12:30", now), at("2026-11-25 12:30"));
|
||||
assert_eq!(start_of("8:05", now), at("2026-11-26 08:05"));
|
||||
assert_eq!(start_of("2026-12-24 08:00", now), at("2026-12-24 08:00"));
|
||||
for bad in ["", "25:00", "noon", "2026-11-25 11:59", "2026-12-24"] {
|
||||
assert_eq!(start_of(bad, now), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_are_remembered() {
|
||||
let mut folders = Folders::default();
|
||||
for i in 0..20 {
|
||||
folders.chose(Path::new(&format!("/d/{i}")), Some(Kind::Video));
|
||||
}
|
||||
folders.chose(Path::new("/d/15"), Some(Kind::Other));
|
||||
assert_eq!((folders.recent.len(), folders.recent[0].clone(), folders.of(Kind::Video)), (RECENT, "/d/15".into(), Some("/d/19".into())));
|
||||
assert_eq!(folders.of(Kind::Other), None);
|
||||
}
|
||||
}
|
||||
110
crates/app/src/views/add/relink.rs
Normal file
110
crates/app/src/views/add/relink.rs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
//! Another link for an unfinished download. What it leads to is compared before anything changes.
|
||||
|
||||
use super::{Checking, Cx};
|
||||
use crate::theme::Theme;
|
||||
use crate::tokens::{space, text};
|
||||
use crate::ui::dialog::{self, Answer, Dialog};
|
||||
use crate::ui::field::Field;
|
||||
use crate::ui::odometer::amount;
|
||||
use crate::ui::widgets::{Button, Kind};
|
||||
use crate::fonts;
|
||||
use eframe::egui::{RichText, Ui};
|
||||
use medlar_core::auth::take_login;
|
||||
use medlar_core::batch::Batch;
|
||||
use medlar_core::manager::Command;
|
||||
use medlar_core::model::Task;
|
||||
use medlar_core::relink::{NewLink, Verdict};
|
||||
use medlar_core::secret::Secret;
|
||||
use medlar_core::tr;
|
||||
|
||||
pub struct Relink {
|
||||
task: Task,
|
||||
pub text: String,
|
||||
/// What was compared.
|
||||
asked: String,
|
||||
pub check: Checking,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
impl Relink {
|
||||
pub fn new(task: &Task) -> Relink {
|
||||
Relink { task: task.clone(), text: String::new(), asked: String::new(), check: Checking::default(), open: true }
|
||||
}
|
||||
|
||||
fn link(&self) -> Option<String> {
|
||||
match &Batch::of(&self.text, false).links[..] {
|
||||
[one] => Some(one.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
self.check.follow(&ctx);
|
||||
let link = self.link();
|
||||
if self.open && self.asked != link.clone().unwrap_or_default() && (self.check.busy() || self.check.found.is_some()) {
|
||||
// Another one.
|
||||
self.check.clear(cx.bridge, self.task.secret.as_ref());
|
||||
}
|
||||
let good = self.check.good().is_some();
|
||||
let verb = match self.check.found {
|
||||
Some(Ok(_)) => tr!("add.continue_do"),
|
||||
Some(Err(_)) => tr!("add.check_again"),
|
||||
None => tr!("relink.check"),
|
||||
};
|
||||
let here = cx.shot.get(self.task.id).map_or(self.task.downloaded, |v| v.downloaded);
|
||||
let title = tr!("relink.title");
|
||||
let name = if self.task.name.is_empty() { &self.task.url } else { &self.task.name };
|
||||
let body = tr!("relink.body", name = name, here = amount(here));
|
||||
let page = self.task.source_page.clone().filter(|p| p.starts_with("http://") || p.starts_with("https://"));
|
||||
let dialog = Dialog::new("relink", &title, &verb).body(&body).enabled(link.is_some() && !self.check.refused()).busy(self.check.busy());
|
||||
let mut to_page = false;
|
||||
let answer = dialog.show(&ctx, t, self.open, |ui| {
|
||||
let r = Field::new(&tr!("relink.link")).busy(self.check.busy()).show(ui, t, &mut self.text);
|
||||
if ui.memory(|m| m.focused().is_none()) {
|
||||
r.request_focus();
|
||||
}
|
||||
if let Some(found) = &self.check.found {
|
||||
let (words, bad) = match found {
|
||||
Ok(c) => (c.text(), c.verdict() == Verdict::Different),
|
||||
Err(why) => (why.clone(), true),
|
||||
};
|
||||
ui.label(RichText::new(words).font(fonts::ui(text::BODY)).color(if bad { t.error } else { t.on_surface }));
|
||||
}
|
||||
if page.is_some() {
|
||||
ui.add_space(space::XS);
|
||||
to_page = Button::new(&tr!("relink.page_open")).with_icon("open_in_new").kind(Kind::Tonal).show(ui, t).clicked();
|
||||
}
|
||||
});
|
||||
if let Some(page) = page.filter(|_| to_page && self.open) {
|
||||
cx.bridge.send(Command::AwaitLink(self.task.id));
|
||||
(cx.outside)(&page);
|
||||
cx.toasts.info("hourglass_empty", tr!("relink.waits"));
|
||||
self.leave(cx);
|
||||
}
|
||||
match (answer, link) {
|
||||
(Some(Answer::Main), _) if good => {
|
||||
self.check.go_on(cx.bridge, self.task.id);
|
||||
self.open = false;
|
||||
}
|
||||
(Some(Answer::Main), Some(link)) => {
|
||||
let (url, login) = take_login(&link);
|
||||
let secret = login.map(|login| Secret { home: Some(url.clone()), login: Some(login), ..Secret::default() });
|
||||
// The old ones count at their own site only.
|
||||
let new = NewLink { url, headers: self.task.headers.clone(), secret: self.task.secret.clone(), source_page: None };
|
||||
self.asked = link;
|
||||
self.check.start(cx.bridge, self.task.id, new, secret);
|
||||
}
|
||||
(Some(Answer::Cancel), _) => self.leave(cx),
|
||||
_ => {}
|
||||
}
|
||||
!self.open && !dialog::shown(&ctx, "relink")
|
||||
}
|
||||
|
||||
fn leave(&mut self, cx: &Cx) {
|
||||
self.check.clear(cx.bridge, self.task.secret.as_ref());
|
||||
self.open = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -193,7 +193,12 @@ impl Group {
|
|||
}
|
||||
|
||||
pub fn kind_label(kind: Kind) -> String {
|
||||
let name = match kind {
|
||||
strings::text(&format!("kind.{}", kind_key(kind)), &[])
|
||||
}
|
||||
|
||||
/// Its name in files and texts.
|
||||
pub fn kind_key(kind: Kind) -> &'static str {
|
||||
match kind {
|
||||
Kind::Video => "video",
|
||||
Kind::Audio => "audio",
|
||||
Kind::Picture => "picture",
|
||||
|
|
@ -201,8 +206,7 @@ pub fn kind_label(kind: Kind) -> String {
|
|||
Kind::Archive => "archive",
|
||||
Kind::Program => "program",
|
||||
Kind::Other => "other",
|
||||
};
|
||||
strings::text(&format!("kind.{name}"), &[])
|
||||
}
|
||||
}
|
||||
|
||||
/// What a file is, by the end of its name, else by what the server calls it.
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@
|
|||
use super::list::model::{Filter, Group, Sort, Status, title};
|
||||
use super::list::row::Column;
|
||||
use super::list::{self, Act, List, Order, layout::Form};
|
||||
use super::add::{self, Adding, Folders, Request};
|
||||
use super::{bar, rail};
|
||||
use crate::bridge::{Bridge, Data, Lists, download_folder};
|
||||
use crate::bridge::{Bridge, Data, Lists};
|
||||
use crate::keys::{Action, Group as Where};
|
||||
use crate::motion::spring;
|
||||
use crate::theme::Theme;
|
||||
|
|
@ -17,8 +18,9 @@ use crate::ui::toast::Toasts;
|
|||
use crate::ui::widgets::{Button, Kind, centered, line};
|
||||
use crate::{fonts, icons, motion};
|
||||
use eframe::egui::{Id, Pos2, Rect, Ui, UiBuilder, Vec2, pos2, text::LayoutJob, vec2};
|
||||
use medlar_core::batch::Batch;
|
||||
use medlar_core::manager::{Command, Files};
|
||||
use medlar_core::model::{State, Task, TaskId};
|
||||
use medlar_core::model::{State, TaskId};
|
||||
use medlar_core::settings::Settings;
|
||||
use medlar_core::snapshot::{Snapshot, TaskView};
|
||||
use medlar_core::tr;
|
||||
|
|
@ -37,11 +39,13 @@ pub struct Prefs {
|
|||
pub columns: Vec<Column>,
|
||||
/// None until the user opens or closes it: it follows the window.
|
||||
pub rail: Option<bool>,
|
||||
/// Where downloads were saved.
|
||||
pub folders: Folders,
|
||||
}
|
||||
|
||||
impl Default for Prefs {
|
||||
fn default() -> Prefs {
|
||||
Prefs { form: Form::Compact, sort: Sort::Queue, down: false, group: Group::State, columns: Column::USUAL.to_vec(), rail: None }
|
||||
Prefs { form: Form::Compact, sort: Sort::Queue, down: false, group: Group::State, columns: Column::USUAL.to_vec(), rail: None, folders: Folders::default() }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -66,8 +70,6 @@ pub enum Wish {
|
|||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum What {
|
||||
Add,
|
||||
Link,
|
||||
Folder,
|
||||
Name,
|
||||
}
|
||||
|
|
@ -89,7 +91,9 @@ pub struct Main {
|
|||
prefs: Prefs,
|
||||
prefs_file: Option<PathBuf>,
|
||||
speeds: bar::Speeds,
|
||||
folders: Folders,
|
||||
ask: Option<Ask>,
|
||||
pub adding: Adding,
|
||||
focus_search: bool,
|
||||
/// Orders from elsewhere, done in the next frame.
|
||||
asked: Vec<Order>,
|
||||
|
|
@ -108,7 +112,9 @@ impl Default for Main {
|
|||
prefs: Prefs::default(),
|
||||
prefs_file: None,
|
||||
speeds: bar::Speeds::default(),
|
||||
folders: Folders::default(),
|
||||
ask: None,
|
||||
adding: Adding::default(),
|
||||
focus_search: false,
|
||||
asked: vec![],
|
||||
wish: None,
|
||||
|
|
@ -149,12 +155,13 @@ impl Main {
|
|||
let q = &mut self.list.query;
|
||||
(self.list.form, q.sort, q.down, q.group) = (prefs.form, prefs.sort, prefs.down, prefs.group);
|
||||
self.list.columns = prefs.columns.clone();
|
||||
self.folders = prefs.folders.clone();
|
||||
self.prefs = prefs;
|
||||
}
|
||||
|
||||
fn keep_prefs(&mut self) {
|
||||
let q = &self.list.query;
|
||||
let now = Prefs { form: self.list.form, sort: q.sort, down: q.down, group: q.group, columns: self.list.columns.clone(), rail: self.prefs.rail };
|
||||
let now = Prefs { form: self.list.form, sort: q.sort, down: q.down, group: q.group, columns: self.list.columns.clone(), rail: self.prefs.rail, folders: self.folders.clone() };
|
||||
if now == self.prefs {
|
||||
return;
|
||||
}
|
||||
|
|
@ -184,7 +191,8 @@ impl Main {
|
|||
Data::Ready(shot, lists) => self.ready(ui, t, settings, window, &shot, &lists),
|
||||
}
|
||||
self.messages(ui, t, window.bottom() - self.floor());
|
||||
self.asking(ui, t, settings);
|
||||
self.asking(ui, t);
|
||||
self.adding(ui, t, settings);
|
||||
self.keep_prefs();
|
||||
}
|
||||
|
||||
|
|
@ -268,7 +276,7 @@ impl Main {
|
|||
if shot.is_empty() {
|
||||
let add = tr!("add.button");
|
||||
if self.state(ui, t, rest, Face::App, &tr!("empty.title"), &tr!("empty.body"), Some(("add", &add))) {
|
||||
self.begin(What::Add, 0, String::new());
|
||||
self.adding.ask(Request::default());
|
||||
}
|
||||
let mut orders = std::mem::take(&mut self.asked);
|
||||
self.list.keys(ui, &mut orders);
|
||||
|
|
@ -326,10 +334,26 @@ impl Main {
|
|||
self.prefs = Prefs { rail, columns: vec![], ..self.prefs.clone() };
|
||||
}
|
||||
|
||||
/// Files let go over the window. What becomes of them is the Add dialog's business.
|
||||
/// Files let go over the window: lists of links.
|
||||
fn dropped(&mut self, ui: &Ui) {
|
||||
if ui.input(|i| !i.raw.dropped_files.is_empty()) {
|
||||
self.begin(What::Add, 0, String::new());
|
||||
for file in ui.input(|i| i.raw.dropped_files.clone()) {
|
||||
self.adding.ask(Request { list: Some(file.path().to_path_buf()), ..Request::default() });
|
||||
}
|
||||
}
|
||||
|
||||
fn adding(&mut self, ui: &Ui, t: &Theme, settings: &Settings) {
|
||||
let Data::Ready(shot, lists) = self.bridge.data() else { return };
|
||||
let mut cx = add::Cx {
|
||||
settings,
|
||||
bridge: &self.bridge,
|
||||
shot: &shot,
|
||||
lists: &lists,
|
||||
folders: &mut self.folders,
|
||||
toasts: &mut self.toasts,
|
||||
outside: self.outside,
|
||||
};
|
||||
if let Some(id) = self.adding.show(ui, t, &mut cx) {
|
||||
self.list.go_to(id);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -372,26 +396,20 @@ impl Main {
|
|||
self.ask = Some(Ask { what, id, text, open: true });
|
||||
}
|
||||
|
||||
/// Adding, and changing the link, folder or name of a download.
|
||||
fn asking(&mut self, ui: &Ui, t: &Theme, settings: &Settings) {
|
||||
/// Changing the folder or name of a download.
|
||||
fn asking(&mut self, ui: &Ui, t: &Theme) {
|
||||
let Some(ask) = &mut self.ask else { return };
|
||||
let (head, label, main) = match ask.what {
|
||||
What::Add => (tr!("add.title"), tr!("add.links"), tr!("add.do")),
|
||||
What::Link => (tr!("ask.link"), tr!("ask.link_field"), tr!("ask.save")),
|
||||
What::Folder => (tr!("ask.folder"), tr!("ask.folder_field"), tr!("ask.move")),
|
||||
What::Name => (tr!("ask.name"), tr!("ask.name_field"), tr!("ask.rename")),
|
||||
};
|
||||
let good = match ask.what {
|
||||
What::Add => !links(&ask.text).is_empty(),
|
||||
What::Link => links(&ask.text).len() == 1,
|
||||
What::Folder => Path::new(ask.text.trim()).is_absolute(),
|
||||
What::Name => !ask.text.trim().is_empty(),
|
||||
};
|
||||
let body = if ask.what == What::Add { tr!("add.body", folder = download_folder(settings).display()) } else { String::new() };
|
||||
let text = &mut ask.text;
|
||||
let rows = if ask.what == What::Add { 4 } else { 1 };
|
||||
let answer = Dialog::new("ask", &head, &main).body(&body).width(size::DIALOG_M).enabled(good).show(ui.ctx(), t, ask.open, |ui| {
|
||||
let r = Field::new(&label).rows(rows).show(ui, t, text);
|
||||
let answer = Dialog::new("ask", &head, &main).width(size::DIALOG_M).enabled(good).show(ui.ctx(), t, ask.open, |ui| {
|
||||
let r = Field::new(&label).show(ui, t, text);
|
||||
if ui.memory(|m| m.focused().is_none()) {
|
||||
r.request_focus();
|
||||
}
|
||||
|
|
@ -403,16 +421,6 @@ impl Main {
|
|||
}
|
||||
let (what, id, text) = (ask.what, ask.id, ask.text.trim().to_string());
|
||||
match what {
|
||||
What::Add => {
|
||||
for url in links(&text) {
|
||||
self.bridge.send(Command::Add(Box::new(Task { url, folder: download_folder(settings), ..Task::default() })));
|
||||
}
|
||||
}
|
||||
What::Link => {
|
||||
let url = links(&text).remove(0);
|
||||
self.bridge.send(Command::Edit { id, edit: Box::new(move |t| t.url = url) });
|
||||
self.bridge.send(Command::Resume(id));
|
||||
}
|
||||
What::Folder => self.bridge.send(Command::Move { id, folder: PathBuf::from(text) }),
|
||||
What::Name => self.bridge.send(Command::Rename { id, name: text }),
|
||||
}
|
||||
|
|
@ -420,11 +428,11 @@ impl Main {
|
|||
|
||||
fn order(&mut self, ui: &Ui, shot: &Snapshot, order: Order) {
|
||||
match order {
|
||||
Order::Add => self.begin(What::Add, 0, String::new()),
|
||||
Order::Add => self.adding.ask(Request::default()),
|
||||
Order::Find => self.focus_search = true,
|
||||
Order::Paste(text) => {
|
||||
if !links(&text).is_empty() {
|
||||
self.begin(What::Add, 0, text);
|
||||
if !Batch::of(&text, false).links.is_empty() {
|
||||
self.adding.ask(Request { text, ..Request::default() });
|
||||
}
|
||||
}
|
||||
Order::Place(moves) => {
|
||||
|
|
@ -498,7 +506,7 @@ impl Main {
|
|||
Act::Portal => (self.outside)(&format!("http://{}/", first.server)),
|
||||
Act::SignIn => self.wish = Some(Wish::SignIn(first.task.url.clone(), views.iter().filter(|v| v.server == first.server).map(|v| v.id()).collect())),
|
||||
Act::Network => self.wish = Some(Wish::Network),
|
||||
Act::EditLink => self.begin(What::Link, first.id(), first.task.url.clone()),
|
||||
Act::EditLink => self.adding.relink(&first.task),
|
||||
Act::EditFolder => self.begin(What::Folder, first.id(), first.task.folder.to_string_lossy().into_owned()),
|
||||
Act::EditName => self.begin(What::Name, first.id(), first.task.name.clone()),
|
||||
}
|
||||
|
|
@ -509,10 +517,3 @@ enum Face {
|
|||
App,
|
||||
Icon(&'static str),
|
||||
}
|
||||
|
||||
/// The web addresses in a text, one after another.
|
||||
pub fn links(text: &str) -> Vec<String> {
|
||||
let is = |w: &&str| ["http://", "https://"].iter().any(|s| w.len() > s.len() && w.get(..s.len()).is_some_and(|h| h.eq_ignore_ascii_case(s)));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
text.split_whitespace().filter(is).filter(|w| seen.insert(w.to_string())).map(String::from).collect()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
//! The screens.
|
||||
|
||||
pub mod add;
|
||||
pub mod bar;
|
||||
pub mod firstrun;
|
||||
pub mod list;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
mod backup;
|
||||
pub mod look;
|
||||
mod network;
|
||||
pub(super) mod network;
|
||||
pub mod rows;
|
||||
mod shortcuts;
|
||||
mod sites;
|
||||
|
|
|
|||
488
crates/app/tests/add.rs
Normal file
488
crates/app/tests/add.rs
Normal file
|
|
@ -0,0 +1,488 @@
|
|||
//! The Add dialog: what is asked of servers, what comes of it, batches, duplicates, and going on from a new link.
|
||||
|
||||
#[path = "main/fixture.rs"]
|
||||
mod fixture;
|
||||
|
||||
use eframe::egui::{Event, Key, Modifiers, PointerButton, Rect, Vec2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use fixture::{MB, all, lists, shot};
|
||||
use medlar_app::app::App;
|
||||
use medlar_app::bridge::{Bridge, Opening};
|
||||
use medlar_app::desktop::Sources;
|
||||
use medlar_app::views::add::{Add, Look, Request, Twice, When};
|
||||
use medlar_core::auth::Login;
|
||||
use medlar_core::manager::{Command, Probed};
|
||||
use medlar_core::model::{ErrorKind, Priority, State, Task, TaskId};
|
||||
use medlar_core::net_state::Bus;
|
||||
use medlar_core::paths::Paths;
|
||||
use medlar_core::settings::{Motion, Settings};
|
||||
use medlar_core::snapshot::TaskView;
|
||||
use medlar_testserver::{Faults, TestServer, expected};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
type H = Harness<'static, Option<App>>;
|
||||
|
||||
fn bare(size: Vec2) -> H {
|
||||
let frame = move |ui: &mut eframe::egui::Ui, s: &mut Option<App>| {
|
||||
let Some(app) = s else {
|
||||
let nowhere = Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() };
|
||||
let settings = Settings { motion: Motion::Normal, download_folder: "/home/you/Downloads".into(), ..Settings::default() };
|
||||
*s = Some(App::new(ui.ctx(), settings, nowhere));
|
||||
ui.ctx().request_repaint();
|
||||
return;
|
||||
};
|
||||
app.show(ui);
|
||||
};
|
||||
let mut h = Harness::builder().with_size(size).with_step_dt(1.0 / 60.0).build_ui_state(frame, None);
|
||||
h.run_steps(5);
|
||||
h
|
||||
}
|
||||
|
||||
fn harness(views: Vec<TaskView>) -> H {
|
||||
let mut h = bare(vec2(1280.0, 1000.0));
|
||||
app(&mut h).main.bridge = Bridge::still(shot(views), lists());
|
||||
h.run_steps(30);
|
||||
h
|
||||
}
|
||||
|
||||
fn app(h: &mut H) -> &mut App {
|
||||
h.state_mut().as_mut().unwrap()
|
||||
}
|
||||
|
||||
fn now(h: &mut H) -> &mut Add {
|
||||
app(h).main.adding.now().expect("the dialog")
|
||||
}
|
||||
|
||||
fn ask(h: &mut H, text: &str) {
|
||||
app(h).main.adding.ask(Request { text: text.into(), ..Request::default() });
|
||||
h.run_steps(60);
|
||||
}
|
||||
|
||||
/// Without any server.
|
||||
fn still(h: &mut H, text: &str, set: impl FnOnce(&mut Add)) {
|
||||
let app = app(h);
|
||||
app.main.adding.open_still(Request { text: text.into(), ..Request::default() }, &app.settings, set);
|
||||
h.run_steps(60);
|
||||
}
|
||||
|
||||
/// The one on top.
|
||||
fn last(h: &H, label: &str) -> Rect {
|
||||
h.get_all_by_label(label).last().unwrap().rect()
|
||||
}
|
||||
|
||||
fn click(h: &mut H, label: &str) {
|
||||
let pos = last(h, label).center();
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
}
|
||||
h.run_steps(60);
|
||||
}
|
||||
|
||||
fn sent(h: &mut H) -> Vec<Command> {
|
||||
app(h).main.bridge.take_sent()
|
||||
}
|
||||
|
||||
fn added(h: &mut H) -> Vec<Task> {
|
||||
let one = |c| match c {
|
||||
Command::Add(task) => *task,
|
||||
_ => panic!("another command"),
|
||||
};
|
||||
sent(h).into_iter().map(one).collect()
|
||||
}
|
||||
|
||||
fn open(h: &mut H) -> bool {
|
||||
h.query_all_by_label("Add downloads").count() > 0
|
||||
}
|
||||
|
||||
fn disabled(h: &H, label: &str) -> bool {
|
||||
h.get_by_label(label).accesskit_node().is_disabled()
|
||||
}
|
||||
|
||||
fn file(name: &str, size: u64) -> Probed {
|
||||
Probed { name: name.into(), size: Some(size), mime: None, ranges: true, page: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_link_with_all_that_can_be_said() {
|
||||
let mut h = harness(all());
|
||||
ask(&mut h, "");
|
||||
assert!(disabled(&h, "Download"));
|
||||
let add = now(&mut h);
|
||||
add.text = "https://me:[email protected]/x.zip".into();
|
||||
(add.queue, add.priority, add.limit, add.parts, add.when) = (2, Priority::High, 100.0, 3.0, When::Later);
|
||||
add.referrer = "https://a.example.org/page".into();
|
||||
add.agent = "Agent/1".into();
|
||||
add.cookies = "sid=S3CRET".into();
|
||||
add.headers = "X-Plain: yes\nAuthorization: Bearer S3CRET".into();
|
||||
add.mirrors = "https://b.example.org/x.zip\nhttps://c.example.org/x.zip".into();
|
||||
add.checksum = "AB".repeat(32);
|
||||
add.proxy = "direct".into();
|
||||
h.run_steps(60);
|
||||
let (_, secrets) = now(&mut h).tasks();
|
||||
click(&mut h, "Download");
|
||||
assert!(!open(&mut h));
|
||||
let [task] = &added(&mut h)[..] else { panic!("not one") };
|
||||
assert_eq!((&*task.url, &*task.name, task.state), ("https://a.example.org/x.zip", "", State::Paused));
|
||||
assert_eq!((task.queue, task.priority, task.speed_limit, task.max_parts), (2, Priority::High, Some(102_400), Some(3)));
|
||||
assert_eq!(task.folder, PathBuf::from("/home/you/Downloads"));
|
||||
assert_eq!((task.mirrors.len(), task.checksum.clone(), task.proxy.as_deref()), (2, Some(format!("sha256:{}", "ab".repeat(32))), Some("direct")));
|
||||
assert_eq!(task.source_page.as_deref(), Some("https://a.example.org/page"));
|
||||
let headers: Vec<_> = task.headers.iter().map(|(n, v)| format!("{n}={v}")).collect();
|
||||
assert_eq!(headers, ["Referer=https://a.example.org/page", "User-Agent=Agent/1", "X-Plain=yes"]);
|
||||
assert!(!format!("{task:?}").contains("S3CRET") && task.secret.as_ref().unwrap().starts_with("task:"));
|
||||
let [(_, secret)] = &secrets[..] else { panic!("not one secret") };
|
||||
assert_eq!((secret.login.as_ref().unwrap().user.as_str(), secret.cookies.as_deref()), ("me", Some("sid=S3CRET")));
|
||||
assert_eq!((secret.home.as_deref(), secret.headers.len()), (Some("https://a.example.org/x.zip"), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_wrong_is_said_and_nothing_is_added() {
|
||||
let mut h = harness(all());
|
||||
ask(&mut h, "https://a.example.org/x.zip");
|
||||
type Case = (&'static str, fn(&mut Add));
|
||||
let cases: [Case; 5] = [
|
||||
("Each line is a name, a colon and a value", |a| a.headers = "no colon".into()),
|
||||
("Not a checksum that Medlar knows", |a| a.checksum = "12".into()),
|
||||
("Each line is one link", |a| a.mirrors = "not a link".into()),
|
||||
("Not a time to come, such as 22:30 or 2026-12-24 08:00", |a| (a.when, a.at) = (When::At, "25:00".into())),
|
||||
("The name can't be used for a file", |a| a.name = "..".into()),
|
||||
];
|
||||
for (words, set) in cases {
|
||||
let add = now(&mut h);
|
||||
(add.headers, add.checksum, add.mirrors, add.when) = (String::new(), String::new(), String::new(), When::Now);
|
||||
add.more = true;
|
||||
set(add);
|
||||
h.run_steps(10);
|
||||
assert!(disabled(&h, "Download"), "{words}");
|
||||
assert!(words.starts_with("The name") || h.query_by_label(words).is_some(), "{words}");
|
||||
}
|
||||
now(&mut h).name = "x.zip".into();
|
||||
h.run_steps(10);
|
||||
h.key_press(Key::Escape);
|
||||
h.run_steps(60);
|
||||
assert!(!open(&mut h) && sent(&mut h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns_lists_and_choosing_among_them() {
|
||||
let mut h = harness(all());
|
||||
ask(&mut h, "https://share.example.org/files/[098-103].jpg\nhttps://share.example.org/files/fonts-collection.zip\nno link here");
|
||||
let add = now(&mut h);
|
||||
assert_eq!((add.lines.len(), add.lines[3].url.as_str()), (7, "https://share.example.org/files/101.jpg"));
|
||||
// The zip is in the list: it is skipped unless asked for.
|
||||
assert!(add.lines[6].known.is_some() && !add.lines[6].on);
|
||||
assert!(h.query_by_label("6 of 7 links chosen").is_some() && h.query_by_label("1 line without a link is left out.").is_some());
|
||||
click(&mut h, "099.jpg");
|
||||
click(&mut h, "Download 5");
|
||||
let urls: Vec<_> = added(&mut h).into_iter().map(|t| t.url.rsplit('/').next().unwrap().to_string()).collect();
|
||||
assert_eq!(urls, ["098.jpg", "100.jpg", "101.jpg", "102.jpg", "103.jpg"]);
|
||||
|
||||
ask(&mut h, "https://h.example.org/{a,b}/[1-2].zip\nhttps://share.example.org/files/fonts-collection.zip");
|
||||
now(&mut h).twice = Twice::Download;
|
||||
h.run_steps(5);
|
||||
click(&mut h, "Download 5");
|
||||
assert_eq!(added(&mut h).len(), 5);
|
||||
|
||||
// Brackets that are none.
|
||||
ask(&mut h, "https://h.example.org/[1-2].zip");
|
||||
assert!(now(&mut h).many());
|
||||
click(&mut h, "Fill in patterns");
|
||||
assert!(!now(&mut h).many());
|
||||
click(&mut h, "Download");
|
||||
assert_eq!(added(&mut h)[0].url, "https://h.example.org/[1-2].zip");
|
||||
|
||||
ask(&mut h, "https://h.example.org/[1-99999].zip");
|
||||
assert!(h.query_by_label_contains("The first 10000 are taken").is_some());
|
||||
click(&mut h, "Download 10000");
|
||||
assert_eq!(added(&mut h).len(), 10_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_of_many_links_stays_at_its_site() {
|
||||
let mut h = harness(all());
|
||||
ask(&mut h, "https://a.example.org/1\nhttps://a.example.org/2\nhttps://b.example.org/3\nhttps://me:[email protected]/4");
|
||||
now(&mut h).login = Login { user: "u".into(), password: "p".into() };
|
||||
let (tasks, secrets) = now(&mut h).tasks();
|
||||
assert_eq!(secrets.len(), 2);
|
||||
assert!(tasks[0].secret.is_some() && tasks[0].secret == tasks[1].secret);
|
||||
assert_eq!(tasks[2].secret, None);
|
||||
assert_eq!((secrets[1].1.login.as_ref().unwrap().user.as_str(), tasks[3].url.as_str()), ("me", "https://c.example.org/4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_from_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let list = dir.path().join("list.txt");
|
||||
std::fs::write(&list, "https://a.example.org/[1-2].zip\nhttps://a.example.org/b.zip").unwrap();
|
||||
let mut h = harness(all());
|
||||
app(&mut h).main.adding.ask(Request { list: Some(list), ..Request::default() });
|
||||
until(&mut h, "the list", |h| h.query_by_label("2 of 2 links chosen").is_some());
|
||||
assert_eq!(now(&mut h).lines[0].url, "https://a.example.org/[1-2].zip");
|
||||
h.key_press(Key::Escape);
|
||||
h.run_steps(60);
|
||||
app(&mut h).main.adding.ask(Request { list: Some(dir.path().into()), ..Request::default() });
|
||||
until(&mut h, "the reason", |h| !h.state().as_ref().unwrap().main.toasts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicates_are_resumed_shown_or_loaded_again() {
|
||||
let mut h = harness(all());
|
||||
let paused = "https://audio.example.edu/files/podcast-archive.flac";
|
||||
ask(&mut h, paused);
|
||||
assert!(h.query_by_label("Resume that download").is_some());
|
||||
click(&mut h, "Resume");
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Resume(8)]));
|
||||
|
||||
ask(&mut h, paused);
|
||||
click(&mut h, "Download as a new file");
|
||||
click(&mut h, "Download");
|
||||
assert_eq!(added(&mut h)[0].url, paused);
|
||||
|
||||
// Done: nothing to resume.
|
||||
ask(&mut h, "https://images.example.org/files/wallpaper-forest.png");
|
||||
assert!(h.query_by_label("Resume that download").is_none());
|
||||
click(&mut h, "Show");
|
||||
assert!(sent(&mut h).is_empty() && app(&mut h).main.list.chosen() == [11]);
|
||||
|
||||
// Only the name is the same: it gets a number, unless it gets another name.
|
||||
let other = "https://other.example.net/wallpaper-forest.png";
|
||||
ask(&mut h, other);
|
||||
assert!(h.query_by_label("A download with this name is in the folder already. A new file gets a number.").is_none(), "the size is not known");
|
||||
h.key_press(Key::Escape);
|
||||
h.run_steps(60);
|
||||
still(&mut h, other, |a| a.learned(file("wallpaper-forest.png", 5)));
|
||||
assert!(now(&mut h).known.as_ref().unwrap().why.starts_with("A download with this name"));
|
||||
click(&mut h, "Download");
|
||||
assert_eq!(added(&mut h).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfinished_download_goes_on_first() {
|
||||
let mut h = harness(all());
|
||||
ask(&mut h, "https://files.example.com/files/report-final.docx?X-Amz-Date=20261125T120000Z&X-Amz-Expires=300&X-Amz-Signature=ab12");
|
||||
let known = now(&mut h).known.as_ref().unwrap();
|
||||
assert_eq!((known.task.id, &*known.why), (9, "An unfinished download has the same link, apart from its signature."));
|
||||
assert!(h.query_by_label("Continue").is_some() && h.query_by_label("Download").is_none());
|
||||
click(&mut h, "Download as a new file");
|
||||
click(&mut h, "Download");
|
||||
assert_eq!(added(&mut h).len(), 1);
|
||||
|
||||
// The same link with a new login: sent along, not simply resumed.
|
||||
app(&mut h).main.adding.ask(Request { text: "https://files.example.com/files/report-final.docx".into(), cookies: Some("a=b".into()), ..Request::default() });
|
||||
h.run_steps(60);
|
||||
assert!(h.query_by_label("Continue").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_server_refuses_has_its_fix() {
|
||||
let mut h = harness(all());
|
||||
still(&mut h, "https://h.example.org/a.zip", |a| a.failed(ErrorKind::Login, "Login needed: h.example.org wants a user name and password."));
|
||||
assert!(h.query_by_label("Login needed: h.example.org wants a user name and password.").is_some());
|
||||
click(&mut h, "Sign in");
|
||||
assert!(now(&mut h).more);
|
||||
h.input_mut().events.push(Event::Text("me".into()));
|
||||
h.run_steps(5);
|
||||
assert_eq!(now(&mut h).login.user, "me");
|
||||
click(&mut h, "Add anyway");
|
||||
assert_eq!(added(&mut h).len(), 1);
|
||||
|
||||
still(&mut h, "https://h.example.org/a.zip", |a| {
|
||||
a.referrer = "https://h.example.org/page".into();
|
||||
a.failed(ErrorKind::Forbidden, "Not allowed: h.example.org refuses.");
|
||||
});
|
||||
assert!(h.query_by_label("Open its page").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_dialog_after_the_other_and_never_wider() {
|
||||
let mut h = harness(all());
|
||||
ask(&mut h, "https://a.example.org/1.zip");
|
||||
ask(&mut h, "https://a.example.org/2.zip");
|
||||
let width = |h: &H| last(h, "Links, one per line").width();
|
||||
let before = width(&h);
|
||||
let add = now(&mut h);
|
||||
add.more = true;
|
||||
add.name = "a-very-long-name".repeat(40);
|
||||
add.failed(ErrorKind::Timeout, &"words ".repeat(200));
|
||||
h.run_steps(30);
|
||||
assert_eq!(width(&h), before);
|
||||
now(&mut h).text = format!("https://a.example.org/{}.zip\nhttps://a.example.org/2", "x".repeat(900));
|
||||
h.run_steps(30);
|
||||
assert_eq!(width(&h), before);
|
||||
h.key_press(Key::Escape);
|
||||
h.run_steps(90);
|
||||
assert_eq!(now(&mut h).text, "https://a.example.org/2.zip");
|
||||
h.key_press(Key::Escape);
|
||||
h.run_steps(90);
|
||||
assert!(app(&mut h).main.adding.now().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_are_remembered_by_type() {
|
||||
let mut h = harness(all());
|
||||
still(&mut h, "https://h.example.org/film.mkv", |a| a.learned(file("film.mkv", MB)));
|
||||
let click_into = last(&h, "Folder").center();
|
||||
h.input_mut().events.push(Event::PointerMoved(click_into));
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(Event::PointerButton { pos: click_into, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
}
|
||||
(0..40).for_each(|_| h.key_press(Key::Backspace));
|
||||
h.run_steps(100);
|
||||
assert_eq!(now(&mut h).folder, "");
|
||||
h.input_mut().events.push(Event::Text("/media/films".into()));
|
||||
h.run_steps(5);
|
||||
click(&mut h, "Download");
|
||||
assert_eq!(added(&mut h)[0].folder, PathBuf::from("/media/films"));
|
||||
still(&mut h, "https://h.example.org/other.mp4", |a| a.learned(file("other.mp4", MB)));
|
||||
assert_eq!(now(&mut h).folder, "/media/films");
|
||||
now(&mut h).text = "https://h.example.org/b.zip".into();
|
||||
now(&mut h).learned(file("b.zip", MB));
|
||||
h.run_steps(5);
|
||||
assert_eq!(now(&mut h).folder, "/home/you/Downloads");
|
||||
}
|
||||
|
||||
// With the engine.
|
||||
|
||||
struct Bench {
|
||||
h: H,
|
||||
server: TestServer,
|
||||
dir: tempfile::TempDir,
|
||||
_runtime: tokio::runtime::Runtime,
|
||||
}
|
||||
|
||||
fn until(h: &mut H, what: &str, is: impl Fn(&H) -> bool) {
|
||||
let end = Instant::now() + Duration::from_secs(60);
|
||||
while !is(h) {
|
||||
assert!(Instant::now() < end, "{what}");
|
||||
std::thread::sleep(Duration::from_millis(16));
|
||||
h.step();
|
||||
}
|
||||
}
|
||||
|
||||
impl Bench {
|
||||
fn new() -> Bench {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let server = runtime.block_on(TestServer::start());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let at = |name: &str| dir.path().join(name);
|
||||
let paths = Paths { config: at("config"), data: at("data"), state: at("state"), cache: at("cache"), portable: false };
|
||||
paths.create().unwrap();
|
||||
let mut h = bare(vec2(1280.0, 1000.0));
|
||||
let ctx = h.ctx.clone();
|
||||
let settings = Settings { download_folder: at("files").display().to_string(), motion: Motion::Normal, ..Settings::default() };
|
||||
app(&mut h).settings = settings.clone();
|
||||
app(&mut h).main.bridge = Bridge::open(Opening { paths, settings, bus: Bus::Off }, &ctx);
|
||||
until(&mut h, "the engine", |h| h.state().as_ref().unwrap().main.bridge.manager().is_some());
|
||||
Bench { h, server, dir, _runtime: runtime }
|
||||
}
|
||||
|
||||
fn state(h: &H, id: TaskId) -> Option<(State, u64)> {
|
||||
let manager = h.state().as_ref().unwrap().main.bridge.manager().unwrap();
|
||||
manager.snapshot().get(id).map(|v| (v.state(), v.downloaded))
|
||||
}
|
||||
|
||||
fn found(&mut self) -> Probed {
|
||||
until(&mut self.h, "the answer", |h| h.query_by_label_contains("can be continued").is_some());
|
||||
match &now(&mut self.h).look {
|
||||
Look::Found(p) => p.clone(),
|
||||
_ => panic!("no answer"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A download that stands still with some of it here.
|
||||
fn half(&mut self, path: &str) -> TaskId {
|
||||
self.server.set_faults(path, Faults { throttle_total: Some(1 << 20), ..Faults::default() });
|
||||
let folder = Path::new(&app(&mut self.h).settings.download_folder).to_path_buf();
|
||||
let manager = app(&mut self.h).main.bridge.manager().unwrap();
|
||||
let id = manager.send(Command::Add(Box::new(Task { url: self.server.url(path), folder, ..Task::default() }))).wait().unwrap();
|
||||
until(&mut self.h, "some of it", |h| Bench::state(h, id).is_some_and(|s| s.1 > 300_000));
|
||||
manager.send(Command::Pause(id)).wait().unwrap();
|
||||
until(&mut self.h, "the pause", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Paused));
|
||||
// The last bytes are saved when its connections have ended.
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_server_is_asked_as_you_type() {
|
||||
let mut b = Bench::new();
|
||||
let slow = "/data/5/8m/slow.bin";
|
||||
b.server.set_faults(slow, Faults { latency_ms: Some(30_000), ..Faults::default() });
|
||||
let url = b.server.url(slow);
|
||||
ask(&mut b.h, &url);
|
||||
until(&mut b.h, "the question", |h| h.query_by_label_contains("Asking").is_some());
|
||||
// Another link is asked about at once.
|
||||
let begun = Instant::now();
|
||||
now(&mut b.h).text = b.server.url("/data/5/2m/quick.bin");
|
||||
let found = b.found();
|
||||
assert!(begun.elapsed() < Duration::from_secs(20));
|
||||
assert_eq!((&*found.name, found.size, found.ranges), ("quick.bin", Some(2 << 20), true));
|
||||
now(&mut b.h).text = b.server.url("/basic/me/S3CRET/data/5/1m/private.bin");
|
||||
until(&mut b.h, "the refusal", |h| h.query_by_label("Sign in").is_some());
|
||||
now(&mut b.h).login = Login { user: "me".into(), password: "S3CRET".into() };
|
||||
assert_eq!(b.found().size, Some(1 << 20));
|
||||
click(&mut b.h, "Download");
|
||||
let files = b.dir.path().join("files/private.bin");
|
||||
until(&mut b.h, "the file", |_| files.exists());
|
||||
assert!(std::fs::read(&files).unwrap() == expected(5, 0, 1 << 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_link_is_compared_before_anything_changes() {
|
||||
let mut b = Bench::new();
|
||||
let id = b.half("/data/7/4m/film.bin");
|
||||
let before = Bench::state(&b.h, id);
|
||||
let url = |h: &H| h.state().as_ref().unwrap().main.bridge.manager().unwrap().snapshot().get(id).unwrap().task.url.clone();
|
||||
let old = url(&b.h);
|
||||
let task = (*app(&mut b.h).main.bridge.manager().unwrap().snapshot().get(id).unwrap().task).clone();
|
||||
app(&mut b.h).main.adding.relink(&task);
|
||||
b.h.run_steps(60);
|
||||
// Another file.
|
||||
app(&mut b.h).main.adding.relinking().unwrap().text = b.server.url("/data/8/4m/film.bin?etag=0&lm=0");
|
||||
b.h.run_steps(2);
|
||||
click(&mut b.h, "Check the link");
|
||||
until(&mut b.h, "the verdict", |h| h.query_by_label_contains("Different file").is_some());
|
||||
assert!((Bench::state(&b.h, id), url(&b.h)) == (before, old.clone()));
|
||||
assert!(disabled(&b.h, "Continue"));
|
||||
// The same one.
|
||||
app(&mut b.h).main.adding.relinking().unwrap().text = b.server.url("/data/7/4m/film.bin?token=2");
|
||||
b.h.run_steps(2);
|
||||
click(&mut b.h, "Check the link");
|
||||
until(&mut b.h, "the verdict", |h| h.query_by_label("Continue").is_some());
|
||||
assert_eq!((Bench::state(&b.h, id), url(&b.h)), (before, old));
|
||||
click(&mut b.h, "Continue");
|
||||
until(&mut b.h, "the rest", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done));
|
||||
assert!(std::fs::read(b.dir.path().join("files/film.bin")).unwrap() == expected(7, 0, 4 << 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_add_dialog_continues_what_is_unfinished() {
|
||||
let mut b = Bench::new();
|
||||
let id = b.half("/data/9/4m/tape.bin");
|
||||
let url = b.server.url("/data/9/4m/tape.bin?token=abc&expires=1764090000");
|
||||
ask(&mut b.h, &url);
|
||||
until(&mut b.h, "the match", |h| h.query_by_label("Continue").is_some());
|
||||
click(&mut b.h, "Continue");
|
||||
until(&mut b.h, "the rest", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done));
|
||||
assert_eq!(std::fs::read_dir(b.dir.path().join("files")).unwrap().count(), 1);
|
||||
assert!(std::fs::read(b.dir.path().join("files/tape.bin")).unwrap() == expected(9, 0, 4 << 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_time_is_kept() {
|
||||
let mut b = Bench::new();
|
||||
let folder = b.dir.path().join("files");
|
||||
let url = b.server.url("/data/3/100000/late.bin");
|
||||
let at = medlar_core::model::now() + 1500;
|
||||
let manager = app(&mut b.h).main.bridge.manager().unwrap();
|
||||
let id = manager.send(Command::Add(Box::new(Task { url, folder, start_at: Some(at), ..Task::default() }))).wait().unwrap();
|
||||
assert_eq!(Bench::state(&b.h, id).unwrap().0, State::Waiting);
|
||||
until(&mut b.h, "the start", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done));
|
||||
assert!(medlar_core::model::now() >= at);
|
||||
}
|
||||
|
|
@ -13,7 +13,6 @@ use medlar_app::desktop::Sources;
|
|||
use medlar_app::ui::shape::Kind;
|
||||
use medlar_app::views::list::layout::Form;
|
||||
use medlar_app::views::list::model::{Age, Filter, Group, Listing, Query, Sort, Status, places};
|
||||
use medlar_app::views::main::links;
|
||||
use medlar_core::manager::{Command, Files};
|
||||
use medlar_core::model::{ErrorKind, State, Task, TaskId};
|
||||
use medlar_core::net_state::Bus;
|
||||
|
|
@ -168,11 +167,6 @@ fn new_places_are_between_the_neighbours() {
|
|||
assert!(places(&l, &[99], 2).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_are_found_in_any_text() {
|
||||
assert_eq!(links("see https://a.org/x\n HTTP://b.org/y, file:///etc/passwd https:// https://a.org/x"), ["https://a.org/x", "HTTP://b.org/y,"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_selects_one_some_and_ranges() {
|
||||
let mut h = harness(simple(8));
|
||||
|
|
@ -315,9 +309,9 @@ fn problems_offer_their_fix() {
|
|||
let link = h.get_by_label("Get new link").rect().center();
|
||||
click(&mut h, link);
|
||||
h.run_steps(60);
|
||||
let save = h.get_by_label("Save and resume").rect().center();
|
||||
click(&mut h, save);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Edit { id: 9, .. }, Command::Resume(9)]));
|
||||
// Nothing changes before the new link was compared, see tests/add.rs.
|
||||
assert!(h.get_by_label("Check the link").accesskit_node().is_disabled());
|
||||
assert!(sent(&mut h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -17,8 +17,11 @@ use medlar_app::ui::gallery;
|
|||
use medlar_app::views::list::layout::Form;
|
||||
use medlar_app::{fonts, icons};
|
||||
use medlar_app::views::firstrun::FirstRun;
|
||||
use medlar_app::views::add::{Add, Request, When};
|
||||
use medlar_app::views::main::Wish;
|
||||
use medlar_app::views::settings::rows::Page;
|
||||
use medlar_core::manager::Probed;
|
||||
use medlar_core::model::ErrorKind;
|
||||
use medlar_core::settings::{Appearance, Settings};
|
||||
use medlar_core::site::Site;
|
||||
|
||||
|
|
@ -47,6 +50,31 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame
|
|||
("main-nothing", |app, ui| main_view(app, ui, |app| app.main.list.query.filter.search = "no such thing".into())),
|
||||
("main-failed", |app, ui| main_view(app, ui, |app| app.main.bridge = Bridge::stuck(Some("The download list was made by a newer Medlar (format 9, this one knows 2). Update Medlar to open it.")))),
|
||||
("main-opening", |app, ui| main_view(app, ui, |app| app.main.bridge = Bridge::stuck(None))),
|
||||
("add-empty", |app, ui| main_view(app, ui, |app| app.main.adding.ask(Request::default()))),
|
||||
("add", |app, ui| main_view(app, ui, |app| add(app, "https://mirror.example.org/iso/linux-2026.11.iso", |a| {
|
||||
a.learned(Probed { name: "linux-2026.11.iso".into(), size: Some(1_240 * downloads::MB), mime: None, ranges: true, page: false });
|
||||
}))),
|
||||
("add-more", |app, ui| main_view(app, ui, |app| add(app, "https://mirror.example.org/iso/linux-2026.11.iso", |a| {
|
||||
(a.more, a.when) = (true, When::At);
|
||||
(a.headers, a.checksum, a.at) = ("no colon".into(), "12".into(), "25:00".into());
|
||||
a.learned(Probed { name: "linux-2026.11.iso".into(), size: Some(900_000 * downloads::MB), mime: None, ranges: false, page: false });
|
||||
}))),
|
||||
("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-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 });
|
||||
}))),
|
||||
("add-continue", |app, ui| main_view(app, ui, |app| add(app, "https://files.example.com/files/report-final.docx?X-Amz-Date=20261125T120000Z&X-Amz-Expires=300&X-Amz-Signature=ab12", |a| {
|
||||
a.learned(Probed { name: "report-final.docx".into(), size: Some(4 * downloads::MB), mime: None, ranges: true, page: false });
|
||||
a.check.found = Some(Err("Connection failed: files.example.com can't be reached.".into()));
|
||||
}))),
|
||||
("relink", |app, ui| main_view(app, ui, |app| {
|
||||
let mut task = (*downloads::all()[8].task).clone();
|
||||
task.source_page = Some("https://example.com/report".into());
|
||||
app.main.adding.relink(&task);
|
||||
})),
|
||||
("set-look", |app, ui| main_view(app, ui, |app| app.open_settings(Page::Look))),
|
||||
("set-look-desktop", |app, ui| main_view(app, ui, |app| {
|
||||
app.desktop.seed = Some(Color32::from_rgb(0x5a, 0x8f, 0x3c));
|
||||
|
|
@ -168,6 +196,11 @@ fn main_view(app: &mut App, ui: &mut Ui, set: fn(&mut App)) {
|
|||
app.show(ui);
|
||||
}
|
||||
|
||||
/// The Add dialog with an answer from no server.
|
||||
fn add(app: &mut App, text: &str, set: fn(&mut Add)) {
|
||||
app.main.adding.open_still(Request { text: text.into(), ..Request::default() }, &app.settings, set);
|
||||
}
|
||||
|
||||
fn over(app: &mut App, ui: &mut Ui, what: &str) {
|
||||
gallery::open(ui, what);
|
||||
app.frame(ui, |app, ui| gallery::page(app, ui, 3));
|
||||
|
|
|
|||
|
|
@ -118,11 +118,89 @@
|
|||
"add.button": "Add",
|
||||
"add.title": "Add downloads",
|
||||
"add.links": "Links, one per line",
|
||||
"add.body": "They are saved to {folder}.",
|
||||
"add.do": "Download",
|
||||
"ask.link": "Change the link",
|
||||
"ask.link_field": "Link",
|
||||
"ask.save": "Save and resume",
|
||||
"add.name": "Name",
|
||||
"add.name_hint": "The one the server gives",
|
||||
"add.folder": "Folder",
|
||||
"add.paste": "Paste",
|
||||
"add.open_list": "Open a list",
|
||||
"add.patterns": "Fill in patterns",
|
||||
"add.too_many": "These are {n} links. The first {most} are taken.",
|
||||
"add.left_out": {"one": "{n} line without a link is left out.", "other": "{n} lines without a link are left out."},
|
||||
"add.nothing": "Paste a link to see what it leads to. Several links, lists and patterns such as [001-120] or {a,b} work too.",
|
||||
"add.unknown": "What the link leads to is found out when it starts.",
|
||||
"add.asking": "Asking {host}",
|
||||
"add.page": "The link leads to a web page, not to a file.",
|
||||
"add.no_size": "Size unknown",
|
||||
"add.parts": "{size}, can be continued, up to {n} parts",
|
||||
"add.one_part": "{size}, one part, starts over when it is interrupted",
|
||||
"add.of": "{here} of {size}",
|
||||
"add.known": "In the list",
|
||||
"add.chosen": "{n} of {all} links chosen",
|
||||
"add.twice": {"one": "{n} of them is in the list already", "other": "{n} of them are in the list already"},
|
||||
"add.twice.skip": "Skip",
|
||||
"add.twice.resume": "Resume what is unfinished",
|
||||
"add.twice.again": "Download again as new files",
|
||||
"add.do_n": "Download {n}",
|
||||
"add.resume_n": "Resume {n}",
|
||||
"add.added": {"one": "{n} download added", "other": "{n} downloads added"},
|
||||
"add.anyway": "Add anyway",
|
||||
"add.continue": "Continue that download",
|
||||
"add.continue_do": "Continue",
|
||||
"add.continue_anyway": "Continue anyway",
|
||||
"add.check_again": "Check again",
|
||||
"add.continues": "{name} continues from the new link",
|
||||
"add.resume": "Resume that download",
|
||||
"add.show": "Show it in the list",
|
||||
"add.show_do": "Show",
|
||||
"add.again": "Download as a new file",
|
||||
"add.awaited": "This download waits for a new link.",
|
||||
"add.same_size": "An unfinished download has the same name or address, and the same size.",
|
||||
"add.same_link": "An unfinished download has the same link, apart from its signature.",
|
||||
"add.alike": "An unfinished download looks like the same file.",
|
||||
"add.by_name": "A download with this name is in the folder already. A new file gets a number.",
|
||||
"add.by_link": "A download with this link is in the list already.",
|
||||
"add.by_link_done": "This link was downloaded before.",
|
||||
"add.by_checksum": "A download with this checksum is in the list already.",
|
||||
"add.free": "{free} free",
|
||||
"add.no_room": "Not enough space: {size} needed, {free} free",
|
||||
"add.recent": "Recent folders",
|
||||
"add.choose": "Choose a folder",
|
||||
"add.no_chooser": "Couldn't open a file chooser: the desktop has none",
|
||||
"add.list_bad": "Couldn't read {name}: it is no list of links",
|
||||
"add.list_unread": "Couldn't read {name}: the file can't be opened",
|
||||
"add.list_empty": "Nothing added: the file has no links",
|
||||
"add.queue": "Queue",
|
||||
"add.priority": "Priority",
|
||||
"add.start": "Start",
|
||||
"add.start_now": "Now",
|
||||
"add.start_later": "Later, add paused",
|
||||
"add.start_at": "At a time",
|
||||
"add.at": "Start at",
|
||||
"add.at_help": "A time such as 22:30, or a day such as 2026-12-24 08:00",
|
||||
"add.at_bad": "Not a time to come, such as 22:30 or 2026-12-24 08:00",
|
||||
"add.limit": "Speed limit, 0 for none",
|
||||
"add.most_parts": "Parts at most, 0 for the setting",
|
||||
"add.more": "More options",
|
||||
"add.less": "Fewer options",
|
||||
"add.open_page": "Open its page",
|
||||
"add.login_help": "Kept in the keyring, for this site only",
|
||||
"add.login_for": "Kept in the keyring, for {host} only",
|
||||
"add.referrer": "Page the link is on",
|
||||
"add.cookies": "Cookies",
|
||||
"add.headers": "Other headers, one per line",
|
||||
"add.headers_bad": "Each line is a name, a colon and a value",
|
||||
"add.proxy_help": "Empty for the usual one, direct for none",
|
||||
"add.mirrors": "Other links to the same file, one per line",
|
||||
"add.mirrors_bad": "Each line is one link",
|
||||
"add.checksum": "Checksum",
|
||||
"add.checksum_bad": "Not a checksum that Medlar knows",
|
||||
"relink.title": "Continue from a new link",
|
||||
"relink.body": "{name} keeps the {here} that are here. The new link is compared first; nothing changes before that.",
|
||||
"relink.link": "New link",
|
||||
"relink.check": "Check the link",
|
||||
"relink.page_open": "Get it from its page",
|
||||
"relink.waits": "The next link from that page continues the download",
|
||||
"ask.folder": "Move to another folder",
|
||||
"ask.folder_field": "Folder",
|
||||
"ask.move": "Move",
|
||||
|
|
|
|||
230
crates/core/src/batch.rs
Normal file
230
crates/core/src/batch.rs
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
//! Many links at once: the links in a text, and patterns that stand for many.
|
||||
//!
|
||||
//! `[001-120]` and `[a-f]` count, also in steps (`[0-100:10]`) and down; `[2026-01-30..2026-02-02]` goes day by day, in the way
|
||||
//! the dates are written; `{one,two}` takes each. Several patterns in a link give every combination.
|
||||
|
||||
use chrono::{Days, NaiveDate};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// So many links at most.
|
||||
pub const MOST: usize = 10_000;
|
||||
|
||||
const SCHEMES: [&str; 6] = ["http://", "https://", "ftp://", "ftps://", "ftpes://", "sftp://"];
|
||||
const DATES: [&str; 7] = ["%Y-%m-%d", "%Y%m%d", "%Y/%m/%d", "%Y_%m_%d", "%Y.%m.%d", "%d-%m-%Y", "%d.%m.%Y"];
|
||||
|
||||
/// The links of a text.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Batch {
|
||||
/// Each once, in order, `MOST` at most.
|
||||
pub links: Vec<String>,
|
||||
/// How many there would be.
|
||||
pub total: u64,
|
||||
/// Some came from patterns.
|
||||
pub patterns: bool,
|
||||
/// Lines that hold something, but no link.
|
||||
pub left_out: usize,
|
||||
}
|
||||
|
||||
impl Batch {
|
||||
/// `patterns`: whether they count, or are parts of links like any other.
|
||||
pub fn of(text: &str, patterns: bool) -> Batch {
|
||||
let mut batch = Batch::default();
|
||||
let mut seen = HashSet::new();
|
||||
for line in text.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let mut found = false;
|
||||
for link in links_in(line) {
|
||||
found = true;
|
||||
let pieces = pieces(link);
|
||||
batch.patterns |= pieces.iter().any(|p| !matches!(p, Piece::Text(_)));
|
||||
let pieces = if patterns { pieces } else { vec![Piece::Text(link)] };
|
||||
let count = pieces.iter().fold(1u64, |n, p| n.saturating_mul(p.len()));
|
||||
let room = MOST - batch.links.len();
|
||||
let mut twice = 0;
|
||||
for i in 0..count.min(room as u64 * 2) {
|
||||
let link = nth(&pieces, i);
|
||||
if batch.links.len() < MOST && seen.insert(link.clone()) {
|
||||
batch.links.push(link);
|
||||
} else if batch.links.len() < MOST {
|
||||
twice += 1;
|
||||
}
|
||||
}
|
||||
batch.total = batch.total.saturating_add(count - twice);
|
||||
}
|
||||
batch.left_out += usize::from(!found);
|
||||
}
|
||||
batch
|
||||
}
|
||||
|
||||
/// There are more than are taken.
|
||||
pub fn cut(&self) -> bool {
|
||||
self.total > self.links.len() as u64
|
||||
}
|
||||
}
|
||||
|
||||
/// The links in a line of a list, a table or a page.
|
||||
fn links_in(line: &str) -> impl Iterator<Item = &str> {
|
||||
line.split(|c: char| c.is_whitespace() || matches!(c, '"' | '<' | '>' | '`')).filter_map(|word| {
|
||||
let at = word.match_indices("://").find_map(|(i, _)| {
|
||||
let start = word[..i].rfind(|c: char| !c.is_ascii_alphabetic()).map_or(0, |j| j + word[j..].chars().next().map_or(1, char::len_utf8));
|
||||
let scheme = word[start..i + 3].to_ascii_lowercase();
|
||||
SCHEMES.contains(&scheme.as_str()).then_some((start, i + 3))
|
||||
});
|
||||
let (start, host) = at?;
|
||||
let link = word[start..].trim_end_matches([',', ';']);
|
||||
(link.len() > host - start).then_some(link)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Piece<'a> {
|
||||
Text(&'a str),
|
||||
/// From, to, step and the digits it has at least.
|
||||
Count(u64, u64, u64, usize),
|
||||
Letters(u8, u8, u8),
|
||||
Days(NaiveDate, NaiveDate, &'static str),
|
||||
Each(Vec<&'a str>),
|
||||
}
|
||||
|
||||
impl Piece<'_> {
|
||||
fn len(&self) -> u64 {
|
||||
match self {
|
||||
Piece::Text(_) => 1,
|
||||
Piece::Count(a, b, step, _) => (a.abs_diff(*b) / step).saturating_add(1),
|
||||
Piece::Letters(a, b, step) => u64::from(a.abs_diff(*b) / step) + 1,
|
||||
Piece::Days(a, b, _) => (*b - *a).num_days().unsigned_abs() + 1,
|
||||
Piece::Each(all) => all.len() as u64,
|
||||
}
|
||||
}
|
||||
|
||||
fn put(&self, i: u64, out: &mut String) {
|
||||
match self {
|
||||
Piece::Text(t) => out.push_str(t),
|
||||
Piece::Count(a, b, step, digits) => {
|
||||
let n = if a <= b { a + i * step } else { a - i * step };
|
||||
out.push_str(&format!("{n:0digits$}"));
|
||||
}
|
||||
Piece::Letters(a, b, step) => {
|
||||
let i = i as u8 * step;
|
||||
out.push(char::from(if a <= b { a + i } else { a - i }));
|
||||
}
|
||||
Piece::Days(a, b, format) => {
|
||||
let day = if a <= b { a.checked_add_days(Days::new(i)) } else { a.checked_sub_days(Days::new(i)) };
|
||||
out.push_str(&day.unwrap_or(*b).format(format).to_string());
|
||||
}
|
||||
Piece::Each(all) => out.push_str(all[i as usize]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The last pattern changes first.
|
||||
fn nth(pieces: &[Piece], mut i: u64) -> String {
|
||||
let mut at = vec![0; pieces.len()];
|
||||
for (at, p) in at.iter_mut().zip(pieces).rev() {
|
||||
(*at, i) = (i % p.len(), i / p.len());
|
||||
}
|
||||
let mut out = String::new();
|
||||
pieces.iter().zip(at).for_each(|(p, at)| p.put(at, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
/// What is no pattern stays as it is, such as the brackets of `http://[::1]/`.
|
||||
fn pieces(link: &str) -> Vec<Piece<'_>> {
|
||||
let mut out = vec![];
|
||||
let (mut from, mut at) = (0, 0);
|
||||
while let Some(open) = link[at..].find(['[', '{']).map(|i| at + i) {
|
||||
at = open + 1;
|
||||
let close = if link.as_bytes()[open] == b'[' { ']' } else { '}' };
|
||||
let Some(end) = link[at..].find(close).map(|i| at + i) else { continue };
|
||||
let inner = &link[at..end];
|
||||
let piece = if close == ']' { range(inner) } else { each(inner) };
|
||||
if let Some(piece) = piece {
|
||||
out.extend((from < open).then(|| Piece::Text(&link[from..open])));
|
||||
out.push(piece);
|
||||
(from, at) = (end + 1, end + 1);
|
||||
}
|
||||
}
|
||||
out.extend((from < link.len()).then(|| Piece::Text(&link[from..])));
|
||||
out
|
||||
}
|
||||
|
||||
fn each(inner: &str) -> Option<Piece<'_>> {
|
||||
let all: Vec<_> = inner.split(',').collect();
|
||||
(all.len() > 1 && !inner.contains(['{', '['])).then_some(Piece::Each(all))
|
||||
}
|
||||
|
||||
fn range(inner: &str) -> Option<Piece<'_>> {
|
||||
if let Some((a, b)) = inner.split_once("..") {
|
||||
return DATES.iter().find_map(|format| {
|
||||
let day = |s| NaiveDate::parse_from_str(s, format).ok().filter(|d| d.format(format).to_string() == s);
|
||||
Some(Piece::Days(day(a)?, day(b)?, format))
|
||||
});
|
||||
}
|
||||
let (span, step) = match inner.split_once(':') {
|
||||
Some((span, step)) => (span, step.parse().ok().filter(|s| (1..=1_000_000).contains(s))?),
|
||||
None => (inner, 1u64),
|
||||
};
|
||||
let (a, b) = span.split_once('-')?;
|
||||
if let ([x], [y]) = (a.as_bytes(), b.as_bytes())
|
||||
&& (x.is_ascii_lowercase() && y.is_ascii_lowercase() || x.is_ascii_uppercase() && y.is_ascii_uppercase())
|
||||
{
|
||||
return Some(Piece::Letters(*x, *y, u8::try_from(step).ok()?));
|
||||
}
|
||||
let number = |s: &str| s.bytes().all(|b| b.is_ascii_digit()).then(|| s.parse().ok()).flatten().filter(|_| s.len() <= 12);
|
||||
let padded = [a, b].iter().any(|s| s.len() > 1 && s.starts_with('0'));
|
||||
Some(Piece::Count(number(a)?, number(b)?, step, if padded { a.len().max(b.len()) } else { 1 }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn all(text: &str) -> Vec<String> {
|
||||
Batch::of(text, true).links
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_are_found_in_lists_tables_and_pages() {
|
||||
let text = "see https://a.org/x\n HTTP://b.org/y, file:///etc/passwd https:// https://a.org/x\n\n\
|
||||
name,ftp://c.org/z;\n<a href=\"https://d.org/ü?q=1\">no</a>\nnothing here\nsftp://[email protected]/f";
|
||||
let batch = Batch::of(text, true);
|
||||
assert_eq!(batch.links, ["https://a.org/x", "HTTP://b.org/y", "ftp://c.org/z", "https://d.org/ü?q=1", "sftp://[email protected]/f"]);
|
||||
assert_eq!((batch.total, batch.left_out, batch.patterns, batch.cut()), (5, 1, false, false));
|
||||
assert_eq!(Batch::of("éhttps://a/b x://y", true).links, ["https://a/b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns_count_in_every_way() {
|
||||
assert_eq!(all("http://h/[008-011].jpg"), ["http://h/008.jpg", "http://h/009.jpg", "http://h/010.jpg", "http://h/011.jpg"]);
|
||||
assert_eq!(all("http://h/[9-11]"), ["http://h/9", "http://h/10", "http://h/11"]);
|
||||
assert_eq!(all("http://h/[20-0:10]"), ["http://h/20", "http://h/10", "http://h/0"]);
|
||||
assert_eq!(all("http://h/[a-c]{x,,yy}").len(), 9);
|
||||
assert_eq!(all("http://h/{x,yy}/[1-2]"), ["http://h/x/1", "http://h/x/2", "http://h/yy/1", "http://h/yy/2"]);
|
||||
assert_eq!(all("http://h/[2024-02-28..2024-03-01].gif"), ["http://h/2024-02-28.gif", "http://h/2024-02-29.gif", "http://h/2024-03-01.gif"]);
|
||||
assert_eq!(all("http://h/[20260101..20251230]"), ["http://h/20260101", "http://h/20251231", "http://h/20251230"]);
|
||||
assert_eq!(all("http://h/[01.02.2026..02.02.2026]"), ["http://h/01.02.2026", "http://h/02.02.2026"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_no_pattern_stays() {
|
||||
for link in ["http://[::1]:80/a", "http://h/[720p-x264]", "http://h/{a}", "http://h/[]", "http://h/[1-", "http://h/[1-2:0]", "http://h/[a-9]", "http://h/[2026-13-01..2026-13-02]"] {
|
||||
let batch = Batch::of(link, true);
|
||||
assert_eq!((batch.links, batch.patterns), (vec![link.to_string()], false));
|
||||
}
|
||||
let literal = Batch::of("http://h/[1-3]", false);
|
||||
assert_eq!((literal.links, literal.patterns), (vec!["http://h/[1-3]".to_string()], true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_are_cut_and_counted() {
|
||||
let batch = Batch::of("http://h/[1-999999999999]/[1-999999999999]/[1-999999999999]", true);
|
||||
assert_eq!((batch.links.len(), batch.total, batch.cut()), (MOST, u64::MAX, true));
|
||||
let two = Batch::of(&format!("http://h/[1-{MOST}]\nhttp://h/x"), true);
|
||||
assert_eq!((two.links.len(), two.total, two.cut()), (MOST, MOST as u64 + 1, true));
|
||||
let twice = Batch::of("http://h/{a,a,b}\nhttp://h/a", true);
|
||||
assert_eq!((twice.links.len(), twice.total, twice.cut()), (2, 2, false));
|
||||
// As many links as fit, each looked at once.
|
||||
let started = std::time::Instant::now();
|
||||
Batch::of(&"http://h/[1-999999999999]\n".repeat(1000), true);
|
||||
assert!(started.elapsed().as_secs() < 5);
|
||||
}
|
||||
}
|
||||
|
|
@ -197,6 +197,13 @@ impl PartialFile {
|
|||
}
|
||||
}
|
||||
|
||||
/// Bytes left for a folder that may not be there yet. None when its drive doesn't say. May wait for a slow drive.
|
||||
pub fn free(folder: &Path) -> Option<u64> {
|
||||
let there = folder.ancestors().find(|f| f.is_dir())?;
|
||||
let stat = rustix::fs::statvfs(there).ok()?;
|
||||
Some(stat.f_bavail.saturating_mul(stat.f_frsize))
|
||||
}
|
||||
|
||||
pub fn partial_path(folder: &Path, name: &str) -> PathBuf {
|
||||
folder.join(format!("{name}{ENDING}"))
|
||||
}
|
||||
|
|
|
|||
95
crates/core/src/duplicate.rs
Normal file
95
crates/core/src/duplicate.rs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
//! What is in the list already.
|
||||
|
||||
use crate::model::{Task, TaskId};
|
||||
use std::path::Path;
|
||||
use url::Url;
|
||||
|
||||
/// Why it is the same.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum By {
|
||||
/// Another file may have this name in the same folder.
|
||||
Name,
|
||||
Link,
|
||||
/// The file itself.
|
||||
Checksum,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Duplicate {
|
||||
pub id: TaskId,
|
||||
pub by: By,
|
||||
}
|
||||
|
||||
/// What is about to be added.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct New<'a> {
|
||||
pub url: &'a str,
|
||||
/// Empty when not known.
|
||||
pub name: &'a str,
|
||||
pub folder: Option<&'a Path>,
|
||||
pub checksum: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// All downloads, to be asked for many links.
|
||||
pub struct Known<'a> {
|
||||
tasks: Vec<(&'a Task, Option<String>)>,
|
||||
links: std::collections::HashMap<String, TaskId>,
|
||||
}
|
||||
|
||||
impl<'a> Known<'a> {
|
||||
pub fn new(tasks: impl IntoIterator<Item = &'a Task>) -> Known<'a> {
|
||||
let tasks: Vec<_> = tasks.into_iter().filter(|t| t.removed_at.is_none()).map(|t| (t, plain(&t.url))).collect();
|
||||
// The latest counts.
|
||||
let links = tasks.iter().filter_map(|(t, link)| Some((link.clone()?, t.id))).collect();
|
||||
Known { tasks, links }
|
||||
}
|
||||
|
||||
/// What says most, then the latest.
|
||||
pub fn find(&self, new: &New) -> Option<Duplicate> {
|
||||
let by_checksum = |sum: &str| self.tasks.iter().rev().find(|(t, _)| t.checksum.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(sum)));
|
||||
if let Some((t, _)) = new.checksum.and_then(by_checksum) {
|
||||
return Some(Duplicate { id: t.id, by: By::Checksum });
|
||||
}
|
||||
if let Some(id) = plain(new.url).and_then(|link| self.links.get(&link)) {
|
||||
return Some(Duplicate { id: *id, by: By::Link });
|
||||
}
|
||||
let folder = new.folder.filter(|_| !new.name.is_empty())?;
|
||||
let (t, _) = self.tasks.iter().rev().find(|(t, _)| t.name == new.name && t.folder == folder)?;
|
||||
Some(Duplicate { id: t.id, by: By::Name })
|
||||
}
|
||||
}
|
||||
|
||||
/// Two ways to write a link are the same one: case of the host, usual port, what is behind `#`. A login doesn't count.
|
||||
fn plain(link: &str) -> Option<String> {
|
||||
let mut url = Url::parse(link).ok()?;
|
||||
url.set_fragment(None);
|
||||
// Fails only without a host.
|
||||
let _ = url.set_username("");
|
||||
let _ = url.set_password(None);
|
||||
Some(url.into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn task(id: TaskId, url: &str, name: &str) -> Task {
|
||||
Task { id, url: url.into(), name: name.into(), folder: "/d".into(), ..Task::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_names_and_checksums() {
|
||||
let sum = format!("sha256:{}", "a".repeat(64));
|
||||
let mut tasks = vec![task(1, "https://H.org:443/a.zip#x", "a.zip"), task(2, "https://h.org/b", "b.zip"), task(3, "https://h.org/a.zip", "c.zip")];
|
||||
tasks[1].checksum = Some(sum.clone());
|
||||
tasks[2].removed_at = Some(1);
|
||||
let known = Known::new(&tasks);
|
||||
let find = |new: New| known.find(&new).map(|d| (d.id, d.by));
|
||||
let folder = Some(Path::new("/d"));
|
||||
assert_eq!(find(New { url: "https://me:[email protected]/a.zip", ..New::default() }), Some((1, By::Link)));
|
||||
assert_eq!(find(New { url: "https://h.org/a.zip", checksum: Some(&sum), ..New::default() }), Some((2, By::Checksum)));
|
||||
assert_eq!(find(New { url: "https://x.org/q", name: "b.zip", folder, ..New::default() }), Some((2, By::Name)));
|
||||
assert_eq!(find(New { url: "https://x.org/q", name: "b.zip", folder: Some(Path::new("/e")), ..New::default() }), None);
|
||||
assert_eq!(find(New { url: "https://h.org/a.zip?v=2", name: "c.zip", folder, ..New::default() }), None);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue