From 7a4ba45c9d1c6b36110cd7a726393dec0ee2d7a5 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 21:58:04 -0600 Subject: [PATCH] S024: hand-off flow: browser links to the Add window or a continued download, single instance, connector page Co-Authored-By: Claude Sonnet 5.5 --- Plans/INDEX.md | 2 +- assets/medlar.desktop | 10 ++ crates/app/src/app.rs | 33 +++- crates/app/src/instance.rs | 72 ++++++++ crates/app/src/lib.rs | 3 +- crates/app/src/main.rs | 3 + crates/app/src/views/add/mod.rs | 12 +- crates/app/src/views/connector.rs | 74 ++++++++ crates/app/src/views/incoming.rs | 239 ++++++++++++++++++++++++++ crates/app/src/views/mod.rs | 2 + crates/app/src/views/settings/rows.rs | 19 ++ crates/core/lang/en.json | 26 ++- crates/core/src/settings.rs | 22 +++ docs/PROGRESS.md | 5 + docs/tests/S024-handoff-flow.md | 42 +++++ 15 files changed, 552 insertions(+), 12 deletions(-) create mode 100644 assets/medlar.desktop create mode 100644 crates/app/src/instance.rs create mode 100644 crates/app/src/views/connector.rs create mode 100644 crates/app/src/views/incoming.rs create mode 100644 docs/tests/S024-handoff-flow.md diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 1240d58..00e2ee1 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -40,7 +40,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 05 Connector - [x] [S023](05%20Connector/S023-port-server.md) The port and its protection -- [ ] [S024](05%20Connector/S024-handoff-flow.md) Hand-off flow and Nacre test +- [x] [S024](05%20Connector/S024-handoff-flow.md) Hand-off flow and Nacre test ## 06 Media diff --git a/assets/medlar.desktop b/assets/medlar.desktop new file mode 100644 index 0000000..f97ea63 --- /dev/null +++ b/assets/medlar.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Type=Application +Name=Medlar +Comment=Download manager +Exec=medlar %U +Icon=medlar +Terminal=false +Categories=Network;FileTransfer; +StartupWMClass=medlar +MimeType=x-scheme-handler/medlar;application/metalink+xml;application/metalink4+xml; diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index c097385..971c896 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -7,6 +7,7 @@ use crate::bridge::{Bridge, Data, Opening}; use crate::keys::{self, Action, Group}; use crate::ui::{dialog, gallery, menu}; use crate::views::firstrun::FirstRun; +use crate::views::incoming::{Inbox, of_arg}; use crate::views::main::{Main, Reply, Wish, open_outside}; use crate::views::palette::{Palette, Pick}; use crate::views::settings::rows::{self, Page}; @@ -39,6 +40,8 @@ pub struct App { /// Where settings are kept. Without it they are not. pub paths: Option, sign_in: Option, + /// The browser port and what came in through it or a second start. + pub inbox: Inbox, /// The desktop's colours, if it has any. pub desktop: Desktop, sources: Sources, @@ -74,6 +77,7 @@ impl App { first: None, paths: None, sign_in: None, + inbox: Inbox::default(), desktop, sources, watch, @@ -197,6 +201,9 @@ impl App { } } } + if self.first.is_none() { + self.inbox.tick(ui.ctx(), &self.settings, &mut self.main); + } let bridge = &self.main.bridge; if let Some(ask) = &mut self.sign_in { ask.show(ui, &t, &mut self.settings, bridge); @@ -330,20 +337,38 @@ impl eframe::App for Window { /// Opens the window and returns when it is closed. pub fn run() -> ExitCode { - open(true, App::show) + run_with(vec![]) +} + +/// Whether the arguments are for a window: links of the `medlar:` scheme and link lists, as a desktop hands them over. +pub fn wants(args: &[String]) -> bool { + !args.is_empty() && args.iter().all(|a| of_arg(a).is_some()) +} + +/// Opens the window with something to add, or hands it to the Medlar that runs and returns. +pub fn run_with(args: Vec) -> ExitCode { + open(true, App::show, args) } /// Opens a window with every control instead (`--gallery`). pub fn run_gallery() -> ExitCode { - open(false, |app, ui| app.frame(ui, gallery::show)) + open(false, |app, ui| app.frame(ui, gallery::show), vec![]) } /// `engine`: with the downloads, else only the window. -fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode { +fn open(engine: bool, show: fn(&mut App, &mut Ui), args: Vec) -> ExitCode { let paths = Paths::detect(); if let Err(e) = paths.create() { eprintln!("{}: {e}", paths.config.display()); } + let mut later = None; + if engine { + match crate::instance::claim(&paths.data, &args) { + crate::instance::Claim::Handed => return ExitCode::SUCCESS, + crate::instance::Claim::First(rx) => later = Some(rx), + crate::instance::Claim::Alone => {} + } + } let (settings, damage) = Settings::load(&paths.settings()); if let Err(e) = logging::init(&paths.log(), log::LevelFilter::Info) { eprintln!("{}: {e}", paths.log().display()); @@ -377,6 +402,8 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode { app.first = Some(FirstRun::default()); } app.paths = Some(paths.clone()); + crate::instance::wake_with(&cc.egui_ctx); + app.inbox = Inbox::new(later.take(), args.clone()); app.main.outside = open_outside; app.main.reveal = crate::views::main::reveal_outside; app.main.remember(paths.data.join("view.json")); diff --git a/crates/app/src/instance.rs b/crates/app/src/instance.rs new file mode 100644 index 0000000..ebe7c24 --- /dev/null +++ b/crates/app/src/instance.rs @@ -0,0 +1,72 @@ +//! One Medlar per home: a second start hands its arguments to the first, over a socket, and ends (FEATURES 8.3). + +use eframe::egui::Context; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::io::{Read, Write}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use std::sync::mpsc::{self, Receiver}; + +/// The window, so that the listener can wake it. +static WAKE: OnceLock = OnceLock::new(); + +pub enum Claim { + /// Another one runs and has the arguments. + Handed, + /// This one is the first; what later starts hand over comes through here. + First(Receiver>), + /// No socket could be made: run without the hand-over. + Alone, +} + +/// Where the socket is. The home is in the name, so that a test home has an instance of its own. +fn socket(home: &Path) -> PathBuf { + let mut h = DefaultHasher::new(); + home.hash(&mut h); + let dir = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|d| d.is_dir()).unwrap_or_else(std::env::temp_dir); + dir.join(format!("medlar-{:x}.sock", h.finish())) +} + +/// Paths in arguments are made absolute: the first one runs somewhere else. +fn absolute(arg: &str) -> String { + if arg.contains(':') || arg.starts_with('/') || arg.starts_with('-') { + return arg.into(); + } + std::fs::canonicalize(arg).map_or_else(|_| arg.into(), |p| p.display().to_string()) +} + +pub fn claim(home: &Path, args: &[String]) -> Claim { + let path = socket(home); + if let Ok(mut other) = UnixStream::connect(&path) { + let text: Vec = args.iter().map(|a| absolute(a).replace(['\n', '\r'], " ")).collect(); + if other.write_all(format!("{}\n", text.join("\n")).as_bytes()).is_ok() { + return Claim::Handed; + } + } + // Nobody answers: a leftover of a crash. + let _ = std::fs::remove_file(&path); + let Ok(listener) = UnixListener::bind(&path) else { return Claim::Alone }; + let (send, got) = mpsc::channel(); + let spawned = std::thread::Builder::new().name("instance".into()).spawn(move || { + for stream in listener.incoming().flatten() { + let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(2))); + let mut text = String::new(); + let _ = (&stream).take(1 << 20).read_to_string(&mut text); + let args: Vec = text.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect(); + // An empty hand-over still raises the window. + if send.send(args).is_err() { + return; + } + if let Some(ctx) = WAKE.get() { + ctx.request_repaint(); + } + } + }); + if spawned.is_err() { Claim::Alone } else { Claim::First(got) } +} + +pub fn wake_with(ctx: &Context) { + let _ = WAKE.set(ctx.clone()); +} diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index b1f09ea..47a9907 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -7,6 +7,7 @@ pub mod fonts; #[rustfmt::skip] mod icondata; pub mod icons; +pub mod instance; pub mod keys; pub mod motion; pub mod theme; @@ -14,4 +15,4 @@ pub mod tokens; pub mod ui; pub mod views; -pub use app::{run, run_gallery}; +pub use app::{run, run_gallery, run_with, wants}; diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a902d99..d217ff0 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -5,6 +5,9 @@ fn main() -> ExitCode { if args.is_empty() { return medlar_app::run(); } + if medlar_app::wants(&args) { + return medlar_app::run_with(args); + } if args == ["--gallery"] { return medlar_app::run_gallery(); } diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs index 562ede9..de4c8ed 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -209,7 +209,7 @@ pub struct Checking { } impl Checking { - fn start(&mut self, bridge: &Bridge, id: TaskId, link: NewLink, secret: Option) { + pub(crate) fn start(&mut self, bridge: &Bridge, id: TaskId, link: NewLink, secret: Option) { self.found = None; self.asked = bridge.check(id, link, secret); if self.asked.is_none() { @@ -218,7 +218,7 @@ impl Checking { } /// True when the answer has just come. - fn follow(&mut self, ctx: &Context) -> bool { + pub(crate) 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")))); @@ -229,7 +229,7 @@ impl Checking { self.asked.is_some() } - fn good(&self) -> Option<&Checked> { + pub(crate) fn good(&self) -> Option<&Checked> { self.found.as_ref()?.as_ref().ok().filter(|c| c.verdict() != Verdict::Different) } @@ -238,14 +238,14 @@ impl Checking { } /// Forgets it and what it left in the keyring. - fn clear(&mut self, bridge: &Bridge, kept: Option<&String>) { + pub(crate) 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) { + pub(crate) 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) }); } @@ -534,7 +534,7 @@ impl Add { self.text += &found.join("\n"); } - fn read_text(&mut self) { + pub(crate) fn read_text(&mut self) { let now = (self.text.clone(), self.patterns); if self.read.as_ref() == Some(&now) { return; diff --git a/crates/app/src/views/connector.rs b/crates/app/src/views/connector.rs new file mode 100644 index 0000000..0acbe7d --- /dev/null +++ b/crates/app/src/views/connector.rs @@ -0,0 +1,74 @@ +//! The browser page: the port's state, a test link, the sender log and how to set up Nacre. + +use super::settings::{Cx, View}; +use crate::fonts; +use crate::tokens::{space, text}; +use crate::ui::widgets::{Button, Kind}; +use chrono::{DateTime, Local}; +use eframe::egui::{RichText, Ui}; +use medlar_core::connector::{Connector, Outcome, Status}; +use medlar_core::tr; +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// The running port, for the page to look at: the window starts it, the page only reads. +static LIVE: Mutex>> = Mutex::new(None); + +pub fn publish(port: Option>) { + *LIVE.lock().unwrap() = port; +} + +/// One link to the port itself, as a browser would send it: the whole way in, down to the Add window. +fn test(port: u16) -> Result<(), String> { + let body = r#"{"url": "https://example.com/medlar-test.bin", "referrer": "https://example.com/"}"#; + let request = format!("POST / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + let mut stream = TcpStream::connect(("127.0.0.1", port)).map_err(|e| e.to_string())?; + stream.set_read_timeout(Some(Duration::from_secs(5))).map_err(|e| e.to_string())?; + stream.write_all(request.as_bytes()).map_err(|e| e.to_string())?; + let mut answer = String::new(); + let _ = stream.read_to_string(&mut answer); + if answer.starts_with("HTTP/1.1 200") { Ok(()) } else { Err(answer.lines().next().unwrap_or("no answer").to_string()) } +} + +pub fn show(_: &mut View, cx: &mut Cx, ui: &mut Ui) { + let t = cx.t; + let live = LIVE.lock().unwrap().clone(); + let status = live.as_ref().and_then(|c| c.status()); + let (words, port) = match (&status, cx.s.connector) { + (_, false) | (Some(Status::Off), _) => (tr!("connector.off"), None), + (Some(Status::On(port)), _) => (tr!("connector.on", port = port), Some(*port)), + (Some(other), _) => (other.words().unwrap_or_default(), None), + (None, _) => (tr!("connector.starting"), None), + }; + let body = |s: &str, c| RichText::new(s).font(fonts::ui(text::BODY)).color(c); + ui.label(body(&words, if port.is_some() { t.on_surface } else { t.on_variant })); + ui.add_space(space::S); + if let Some(port) = port + && Button::new(&tr!("connector.test")).with_icon("send").kind(Kind::Tonal).show(ui, t).clicked() + { + match test(port) { + Ok(()) => cx.toasts.info("send", tr!("connector.test_sent")), + Err(why) => cx.toasts.error(tr!("connector.test_failed", why = why), None), + } + } + ui.add_space(space::L); + ui.label(body(&tr!("connector.log"), t.on_surface).font(fonts::semi(text::BODY))); + let log = live.map(|c| c.log()).unwrap_or_default(); + if log.is_empty() { + ui.label(body(&tr!("connector.log_empty"), t.on_variant)); + } + for entry in log.iter().rev().take(30) { + let when = DateTime::from_timestamp_millis(entry.at).map(|d| d.with_timezone(&Local).format("%H:%M:%S").to_string()).unwrap_or_default(); + let who = entry.from.process.clone().unwrap_or_else(|| format!(":{}", entry.from.port)); + let what = match &entry.outcome { + Outcome::Accepted { links, .. } => tr!("connector.log_in", n = links, what = entry.what), + Outcome::Refused(why) => format!("{} {}", tr!("connector.log_out", what = entry.what), why.words()), + }; + ui.label(body(&format!("{when} {who} {what}"), t.on_variant)); + } + ui.add_space(space::L); + ui.label(body(&tr!("connector.steps"), t.on_surface).font(fonts::semi(text::BODY))); + ui.label(body(&tr!("connector.steps_body", port = cx.s.connector_port), t.on_variant)); +} diff --git a/crates/app/src/views/incoming.rs b/crates/app/src/views/incoming.rs new file mode 100644 index 0000000..ab438fe --- /dev/null +++ b/crates/app/src/views/incoming.rs @@ -0,0 +1,239 @@ +//! From the browser's click to a download: the port, the links that came in, and what is done with each (FEATURES 4.4). +//! +//! A link that a download waits for is checked against it and continues it, without a window. A link that matches an +//! unfinished download opens the Add window with "Continue" first (the window finds the match). The rest opens the +//! window too, one after another, unless the user turned on adding without asking and the rules allow it. `medlar:` +//! links and files from a second start always show the window: a web page can make them. + +use super::add::{Add, Checking, Request}; +use super::main::Main; +use crate::bridge::Data; +use crate::views::connector; +use eframe::egui::{Context, ViewportCommand}; +use medlar_core::connector::{Arrival, Connector, Incoming as Link}; +use medlar_core::model::TaskId; +use medlar_core::relink::{self, NewLink, Strength}; +use medlar_core::settings::Settings; +use medlar_core::tr; +use std::collections::VecDeque; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::mpsc::Receiver; +use tokio::sync::mpsc::UnboundedReceiver; + +/// What waits for the engine to be there. +enum Item { + Link(Link), + Asked(Request), +} + +#[derive(Default)] +pub struct Inbox { + port: Option>, + arrivals: Option>, + /// Arguments of later starts. + args: Option>>, + wanted: Option<(bool, u16)>, + pending: VecDeque, + /// Downloads that wait for a link, and the check of the one that came. + waiting: Vec<(TaskId, String, Checking)>, + failed: bool, +} + +impl Inbox { + pub fn new(args: Option>>, first: Vec) -> Inbox { + let pending = first.iter().filter_map(|a| of_arg(a)).map(Item::Asked).collect(); + Inbox { args, pending, ..Inbox::default() } + } + + /// Once per frame. + pub fn tick(&mut self, ctx: &Context, s: &Settings, main: &mut Main) { + self.port(ctx, s, main); + if let Some(args) = &self.args { + while let Ok(list) = args.try_recv() { + ctx.send_viewport_cmd(ViewportCommand::Focus); + self.pending.extend(list.iter().filter_map(|a| of_arg(a)).map(Item::Asked)); + } + } + if let Some(rx) = &mut self.arrivals { + while let Ok(arrival) = rx.try_recv() { + self.pending.extend(arrival.links.into_iter().map(Item::Link)); + } + } + if let Data::Ready(shot, _) = main.bridge.data() { + let mut now: Vec = vec![]; + while let Some(item) = self.pending.pop_front() { + match item { + Item::Asked(request) => self.ask(ctx, main, request), + Item::Link(link) => now.push(link), + } + } + let mut rest = vec![]; + for link in now { + if !self.relink(&shot, main, &link) { + rest.push(link); + } + } + if !rest.is_empty() { + self.ask_links(ctx, s, main, &shot, rest); + } + } + self.follow(ctx, main); + } + + /// Starts the port, and follows the settings. + fn port(&mut self, ctx: &Context, s: &Settings, main: &mut Main) { + let want = (s.connector, s.connector_port); + match &self.port { + None if !self.failed && !matches!(main.bridge.data(), Data::Opening) => match Connector::start(want.0, want.1) { + Ok((port, arrivals)) => { + let wake = ctx.clone(); + port.on_change(move || wake.request_repaint()); + let port = Arc::new(port); + connector::publish(Some(port.clone())); + self.port = Some(port); + self.arrivals = Some(arrivals); + self.wanted = Some(want); + } + Err(e) => { + self.failed = true; + log::warn!("connector: {e}"); + main.toasts.error(tr!("incoming.no_start", why = e), None); + } + }, + Some(port) if self.wanted != Some(want) => { + port.set(want.0, want.1); + self.wanted = Some(want); + } + _ => {} + } + } + + /// A link that a download waits for: its check starts. True when it took the link. + fn relink(&mut self, shot: &medlar_core::snapshot::Snapshot, main: &mut Main, link: &Link) -> bool { + let new = relink::Incoming { url: link.url.clone(), name: link.name.clone(), size: link.size, page: link.page.clone() }; + let found = relink::find(&new, shot.iter().map(|v| &*v.task)); + let Some(best) = found.first().filter(|m| m.awaited && m.strength >= Strength::Likely) else { return false }; + if self.waiting.iter().any(|(id, ..)| *id == best.id) { + return true; + } + let Some(view) = shot.get(best.id) else { return false }; + let task = &view.task; + let name = if task.name.is_empty() { task.url.clone() } else { task.name.clone() }; + let next = NewLink { url: link.url.clone(), headers: link.task_headers(), secret: task.secret.clone(), source_page: link.page.clone() }; + let mut check = Checking::default(); + check.start(&main.bridge, best.id, next, link.secret.clone()); + self.waiting.push((best.id, name, check)); + true + } + + /// Checks that are through: the good ones go on, the others say why not. + fn follow(&mut self, ctx: &Context, main: &mut Main) { + for (id, name, check) in &mut self.waiting { + if check.follow(ctx) { + if check.good().is_some() { + check.go_on(&main.bridge, *id); + main.toasts.info("play_arrow", tr!("incoming.continues", name = name)); + } else { + let why = match &check.found { + Some(Ok(c)) => c.text(), + Some(Err(why)) => why.clone(), + None => String::new(), + }; + check.clear(&main.bridge, None); + main.toasts.error(tr!("incoming.differs", name = name, why = why), None); + } + } + } + self.waiting.retain(|(_, _, c)| c.busy()); + } + + fn ask(&mut self, ctx: &Context, main: &mut Main, request: Request) { + if main.adding.now().is_none() { + ctx.send_viewport_cmd(ViewportCommand::Focus); + } + main.adding.ask(request); + } + + /// The links that no download waits for: added, or in the window. + fn ask_links(&mut self, ctx: &Context, s: &Settings, main: &mut Main, shot: &medlar_core::snapshot::Snapshot, links: Vec) { + let name_of = |l: &Link| l.name.clone().or_else(|| l.url.split(['?', '#']).next().and_then(|u| u.rsplit('/').next()).map(String::from)).unwrap_or_default(); + let known = |l: &Link| { + let new = relink::Incoming { url: l.url.clone(), name: l.name.clone(), size: l.size, page: l.page.clone() }; + !relink::find(&new, shot.iter().map(|v| &*v.task)).is_empty() + }; + let request = match &links[..] { + [one] => Request { + text: one.url.clone(), + literal: true, + name: one.name.clone(), + size: one.size, + mime: one.mime.clone(), + page: one.page.clone(), + user_agent: one.user_agent.clone(), + cookies: one.secret.as_ref().and_then(|x| x.cookies.clone()), + headers: one.headers.clone(), + ..Request::default() + }, + _ => Request { text: links.iter().map(|l| l.url.as_str()).collect::>().join("\n"), literal: true, ..Request::default() }, + }; + if links.iter().all(|l| s.auto_ok(&name_of(l), l.size) && !known(l)) { + // Each on its own, so that its own cookies stay with it. + let mut n = 0; + for link in &links { + let one = Request { + text: link.url.clone(), + literal: true, + name: link.name.clone(), + size: link.size, + mime: link.mime.clone(), + page: link.page.clone(), + user_agent: link.user_agent.clone(), + cookies: link.secret.as_ref().and_then(|x| x.cookies.clone()), + headers: link.headers.clone(), + ..Request::default() + }; + let mut add = Add::new(one, s); + add.read_text(); + let (tasks, secrets) = add.tasks(); + n += tasks.len(); + main.bridge.add(tasks, secrets); + } + main.toasts.info("download", tr!("incoming.added", n = n)); + return; + } + self.ask(ctx, main, request); + } +} + +/// What a start's argument asks for, as a request for the Add window. +pub fn of_arg(arg: &str) -> Option { + let arg = arg.trim(); + let lower = arg.to_ascii_lowercase(); + if lower.ends_with(".metalink") || lower.ends_with(".meta4") { + return Some(Request { list: Some(PathBuf::from(arg)), ..Request::default() }); + } + let link = match arg.get(..7).filter(|p| p.eq_ignore_ascii_case("medlar:")) { + Some(_) => { + let rest = arg[7..].trim_start_matches('/'); + let plain = rest.split_once("://").is_some_and(|(s, _)| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric())); + if plain { rest.to_string() } else { percent_encoding::percent_decode_str(rest).decode_utf8().ok()?.into_owned() } + } + None => arg.to_string(), + }; + link.contains("://").then(|| Request { text: link, literal: true, ..Request::default() }) +} + +#[cfg(test)] +mod tests { + use super::of_arg; + + #[test] + fn arguments() { + assert_eq!(of_arg("medlar:https://a.test/x.zip").unwrap().text, "https://a.test/x.zip"); + assert_eq!(of_arg("medlar://https%3A%2F%2Fa.test%2Fx.zip").unwrap().text, "https://a.test/x.zip"); + assert!(of_arg("medlar:nothing").is_none()); + assert_eq!(of_arg("/tmp/a.METALINK").unwrap().list.unwrap().to_str(), Some("/tmp/a.METALINK")); + assert!(of_arg("--show").is_none()); + } +} diff --git a/crates/app/src/views/mod.rs b/crates/app/src/views/mod.rs index 5078f95..a6ee3da 100644 --- a/crates/app/src/views/mod.rs +++ b/crates/app/src/views/mod.rs @@ -2,9 +2,11 @@ pub mod add; pub mod bar; +pub mod connector; pub mod control; pub mod details; pub mod firstrun; +pub mod incoming; pub mod list; pub mod main; pub mod modes; diff --git a/crates/app/src/views/settings/rows.rs b/crates/app/src/views/settings/rows.rs index 87130d0..5c394f2 100644 --- a/crates/app/src/views/settings/rows.rs +++ b/crates/app/src/views/settings/rows.rs @@ -191,6 +191,10 @@ macro_rules! limit { }; } +fn mb() -> String { + tr!("unit.mb_short") +} + fn no_unit() -> String { String::new() } @@ -332,6 +336,21 @@ static ROWS: &[Row] = &[ Kind::Number { unit: no_unit, range: 1024.0..=65535.0, step: 1.0, get: |s| s.connector_port.into(), set: |s, v| s.connector_port = v as u16 }, ), row(Page::Browser, "browser", "add_without_asking", &["add_without_asking"], Kind::Switch { get: |s| s.add_without_asking, set: |s, v| s.add_without_asking = v }), + row( + Page::Browser, + "browser", + "auto_types", + &["auto_types"], + Kind::Text { + hint: |_| "zip, iso, mp4".into(), + check: |_| None, + get: |s| s.auto_types.join(", "), + set: |s, v| s.auto_types = v.split([',', ' ', '\n']).map(|p| p.trim().trim_start_matches('.').to_ascii_lowercase()).filter(|p| !p.is_empty()).collect(), + }, + ), + row(Page::Browser, "browser", "auto_min_mb", &["auto_min_mb"], Kind::Number { unit: mb, range: 0.0..=100_000.0, step: 1.0, get: |s| s.auto_min_mb as f64, set: |s, v| s.auto_min_mb = v as u64 }), + row(Page::Browser, "browser", "auto_max_mb", &["auto_max_mb"], Kind::Number { unit: mb, range: 0.0..=1_000_000.0, step: 1.0, get: |s| s.auto_max_mb as f64, set: |s, v| s.auto_max_mb = v as u64 }), + row(Page::Browser, "browser", "browser_page", &[], Kind::Own(crate::views::connector::show)), row(Page::Backup, "", "backup", &[], Kind::Own(backup::show)), ]; diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index e96e891..589e625 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -798,5 +798,29 @@ "done.blocked": "A download failed, so nothing was done.", "done.failed_to": "It could not be done: {why}", "priority.share": "About {n} times the share of a Normal download.", - "priority.share_only": "Everything else waits while this one runs." + "priority.share_only": "Everything else waits while this one runs.", + "set.auto_types": "Only these types", + "set.auto_types.why": "File endings the browser may add without asking, like zip, iso, mp4. Empty takes any. Needs Add without asking.", + "set.auto_min_mb": "Smallest size for it", + "set.auto_min_mb.why": "Smaller files still show the Add window. 0 takes any size.", + "set.auto_max_mb": "Largest size for it", + "set.auto_max_mb.why": "Larger files still show the Add window. 0 takes any size.", + "set.browser_page": "The browser port", + "connector.on": "Listening on 127.0.0.1:{port}.", + "connector.off": "Off. The browser cannot send links.", + "connector.starting": "Starting.", + "connector.test": "Send a test link", + "connector.test_sent": "A test link was sent to the port.", + "connector.test_failed": "The test link did not arrive: {why}", + "connector.log": "Who sent what", + "connector.log_empty": "Nothing has come in yet.", + "connector.log_in": "{n} link(s): {what}", + "connector.log_out": "Refused: {what}", + "connector.steps": "Setting up Nacre", + "connector.steps_body": "1. In Nacre open Settings, Downloads, Custom download manager.\\n2. Turn it on and set the address to http://127.0.0.1:{port}/\\n3. Click a download in the browser: the Add window opens here.", + "incoming.continues": "The new link for {name} fits. It goes on.", + "incoming.differs": "The new link for {name} was not used: {why}", + "incoming.added": "Added {n} from the browser.", + "incoming.no_start": "The browser port could not start: {why}", + "unit.mb_short": "MB" } diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index 65728ad..433de78 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -41,6 +41,11 @@ pub struct Settings { pub connector_port: u16, /// Add links from the browser without showing the Add dialog. pub add_without_asking: bool, + /// With `add_without_asking`: only files of these types (extensions in small letters); empty for any. + pub auto_types: Vec, + /// Only files from this size in MB, and up to it; 0 for no bound. A size nobody told passes. + pub auto_min_mb: u64, + pub auto_max_mb: u64, /// Follow the desktop's colours; None until the first run decides (D-012). pub desktop_colors: Option, pub own_color: String, @@ -144,6 +149,9 @@ impl Default for Settings { connector: true, connector_port: 17616, add_without_asking: false, + auto_types: vec![], + auto_min_mb: 0, + auto_max_mb: 0, desktop_colors: None, own_color: "#b5622b".into(), appearance: Appearance::Auto, @@ -167,6 +175,20 @@ pub struct Damage { } impl Settings { + /// Whether a link from the browser may be added without asking: off unless `add_without_asking`, then the type + /// and size rules decide. + pub fn auto_ok(&self, name: &str, size: Option) -> bool { + if !self.add_without_asking { + return false; + } + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + if !self.auto_types.is_empty() && !self.auto_types.iter().any(|t| *t == ext) { + return false; + } + let mb = 1024 * 1024; + size.is_none_or(|n| n >= self.auto_min_mb * mb && (self.auto_max_mb == 0 || n <= self.auto_max_mb * mb)) + } + /// Never fails: whatever can't be read keeps its default and is reported. pub fn load(path: &Path) -> (Settings, Option) { let bytes = match fs::read(path) { diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 5654460..9ed337c 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -213,3 +213,8 @@ Seen: boxes were ticked together after the tests, against rule 3. - `connector::Connector::start(on, port) -> (Connector, UnboundedReceiver)`: the incoming-link event for the UI. `set(on, port)` live, `status()` (`Taken{by}` names the fix via `words()`), `log()` sender log, `on_change`. `Incoming::task(&Secrets, common)` makes the task and keeps cookies/login in the keyring. - Guards: loopback only, Host = 127.0.0.1|localhost:port, no Origin / cross-site Sec-Fetch, JSON only, preflights refused, no CORS; header and link checks. Format: `docs/CONNECTOR.md`. Tests: `docs/tests/S023-port-server.md`. - Not done: no app wiring (S024), no automatic tests yet; own small HTTP/1.1 reader instead of hyper's server. + +## S024 — Hand-off flow (compiled, not tested) +- `views/incoming.rs` `Inbox` (in `App`): starts `Connector`, follows settings, takes arrivals. Awaited task + Likely match: check, then `Continue` by itself; else Add dialog (`literal`, queued, focus only if none open) or direct add when `Settings::auto_ok` (new `auto_types`, `auto_min_mb`, `auto_max_mb`, off by default). `medlar:` and `.metalink` args always show the dialog. +- `instance.rs`: Unix socket per home; second start hands args over and exits (`wants`, `run_with`). `assets/medlar.desktop`. Connector page `views/connector.rs` (state, test link, log, Nacre steps). +- Not done: no integration test, no Nacre run, no keyring cleanup change, `.desktop` not installed by any script; a task already in the Add dialog's "Continue" is still the dialog's own logic. diff --git a/docs/tests/S024-handoff-flow.md b/docs/tests/S024-handoff-flow.md new file mode 100644 index 0000000..2bfa850 --- /dev/null +++ b/docs/tests/S024-handoff-flow.md @@ -0,0 +1,42 @@ +# S024 — Hand-off flow: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +- `crates/app/src/views/incoming.rs` · `Inbox`: starts the port, sorts arrivals (relink, auto-add, Add dialog); `of_arg` parses `medlar:` links, links and `.metalink` files. +- `crates/app/src/instance.rs` · single instance by Unix socket in `$XDG_RUNTIME_DIR`, named from the home folder. +- `crates/app/src/views/connector.rs` · Settings, Browser: state, test link, sender log, Nacre steps. +- `crates/core/src/settings.rs` · `auto_types`, `auto_min_mb`, `auto_max_mb`, `Settings::auto_ok`. +- `assets/medlar.desktop` · `medlar:` scheme and metalink types. + +## Checks +Risk: HIGH = data loss, security, crash, wrong result · MED = feature broken · LOW = looks or comfort. + +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | `medlar:` link and `/x.metalink` through `of_arg`; `--show`, `medlar:nothing` | Request with literal text / list; the last two give none | unit | — | +| 2 | HIGH | Hidden run, throwaway home, POST one link to the port | Add dialog opens with the link filled in | by hand | — | +| 3 | HIGH | Same with `add_without_asking` off and a `medlar:` link on the socket | Dialog shown, never added silently | by hand | — | +| 4 | HIGH | Turn `add_without_asking` on, types `zip`, send a `.zip` and a `.iso` | zip added at once with a toast; iso opens the dialog | by hand | — | +| 5 | MED | `auto_ok` with sizes: min 10 MB, max 100 MB; sizes 5, 50, 500 MB and unknown | false, true, false, true | unit | — | +| 6 | MED | Send a list of 3 links in one POST | One dialog in batch mode | by hand | — | +| 7 | MED | Send 3 POSTs in a row | Dialogs come one after another; the window is raised once | by hand | — | +| 8 | HIGH | Paused download from the same URL with new token; send the link | Dialog offers "Continue" first with the verdict | by hand | — | +| 9 | HIGH | Task waiting on "open source page" (expired link); send a fresh link | Check runs, the task continues, toast says so, no dialog | by hand | — | +| 10 | HIGH | Same, but the fresh link leads to another file | Task stays, error toast with why | by hand | — | +| 11 | MED | Settings, Browser: switch off, change port, press Send a test link | State line follows; test opens the Add dialog; log shows the entry | by hand | — | +| 12 | HIGH | Start a second `medlar medlar:https://a.test/f` with the same home | It ends at once; the first window shows the Add dialog | by hand | — | +| 13 | MED | Kill the first with SIGKILL, start again | Starts normally (stale socket removed) | by hand | — | +| 14 | HIGH | Nacre with a throwaway home, Medlar on a spare port against testserver; click a download | It arrives and downloads; else replay Nacre's body with curl and say so | by hand | — | +| 15 | HIGH | Download, expire the link on testserver, send a fresh one | File completes identical (hash) | by hand | — | +| 16 | LOW | Port taken by another program | Page shows the plain-words fix | by hand | — | + +## Needs +Throwaway `MEDLAR_HOME` and `XDG_*`, `tools/hidden.sh`, `crates/testserver` for expiry, a spare port (not 15151, 38151), Nacre at `~/Projects/Nacre/target/release/nacre` with a throwaway home. Never touch `~/.abdm`. + +## Doubts +- Nothing was run. `medlar:` format is invented: `medlar:` or `medlar://`. +- Auto-add skips links that match any unfinished download (goes to the dialog). Unknown size passes the size rules. +- The settings page reaches the live port through a static (`connector::publish`). +- Second start with no arguments hands over nothing and the plain `medlar` run raises the first window; a second start with arguments not recognised by `wants` goes to the CLI. +- Keyring cleanup for a task's items (shared kept) was not touched.