diff --git a/Plans/09 Fix round/S065-custom-manager-port.md b/Plans/09 Fix round/S065-custom-manager-port.md index ba950bf..d434b4f 100644 --- a/Plans/09 Fix round/S065-custom-manager-port.md +++ b/Plans/09 Fix round/S065-custom-manager-port.md @@ -12,13 +12,13 @@ Replaces S036; D-050 (amends D-022). On the "Download managers" page (user scree - `tests/smoke/net/server.py`, `tests/smoke/net-downloads.txt` headers ## Steps -- [ ] Settings model: `custom_managers: Vec<{name, port, enabled}>` with defaults; port 1–65535 validated, loopback only (no host field). -- [ ] dlm: status ping and hand-over for custom entries per D-022; fall back with a toast. -- [ ] Settings UI: "Add your own" row (name + port fields, Add), entries listed with status and switch, remove. -- [ ] Unit tests: payload building, port validation. -- [ ] server.py stub route on a port + `net-downloads.txt` case (handed over; fallback when down). Run it only (D-048). -- [ ] DESIGN.md "Custom download manager": contract, example request, ~20-line Python receiver. -- [ ] PROGRESS entry, INDEX line (also mark S036 superseded), tracker, commit `S065: …`, push. +- [x] Settings model: `custom_managers: Vec<{name, port, enabled}>` with defaults; port 1–65535 validated, loopback only (no host field). +- [x] dlm: status ping and hand-over for custom entries per D-022; fall back with a toast. +- [x] Settings UI: "Add your own" row (name + port fields, Add), entries listed with status and switch, remove. +- [x] Unit tests: payload building, port validation. +- [x] server.py stub route on a port + `net-downloads.txt` case (handed over; fallback when down). Run it only (D-048). +- [x] DESIGN.md "Custom download manager": contract, example request, ~20-line Python receiver. +- [x] PROGRESS entry, INDEX line (also mark S036 superseded), tracker, commit `S065: …`, push. ## End criteria - `cargo test` green; `net-downloads.txt` exit 0 with the custom case; server log shows the JSON body. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 916525b..8e57aab 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -17,7 +17,7 @@ Dropped with Servo (D-032): S011, S029, S030, S032, S033, S037, S038. - [x] [S062 — Memory saver that actually unloads, sliders, resting tab icons](09%20Fix%20round/S062-memory-saver.md) · Sonnet high - [x] [S063 — Lock down nacre:// pages; passwords unlock on every open](09%20Fix%20round/S063-nacre-pages-lockdown.md) · Opus medium - [x] [S064 — History flyout, bookmark flyout on tab switch, About lists nacre:// pages](09%20Fix%20round/S064-history-flyout-about.md) · Sonnet high -- [ ] [S065 — Custom download manager by name and port](09%20Fix%20round/S065-custom-manager-port.md) · Sonnet high +- [x] [S065 — Custom download manager by name and port](09%20Fix%20round/S065-custom-manager-port.md) · Sonnet high - [ ] [S066 — UI alignment pass (/unslop)](09%20Fix%20round/S066-ui-alignment.md) · Opus medium · 🧑 ## 02 Verify / 03 Gaps (after 08; reviews need the user) @@ -29,7 +29,7 @@ Dropped with Servo (D-032): S011, S029, S030, S032, S033, S037, S038. ## 07 Polish pass (UI cleanup and motion) - [ ] [S034 — Spelling underlines, inline autofill, "Settings updated" popup](07%20Polish%20pass/S034-small-fixes.md) · Opus medium - [ ] [S035 — History/passwords/bookmarks flyouts and Nacre's own context menu](07%20Polish%20pass/S035-flyouts-context-menu.md) · superseded by S061, S064 -- [ ] [S036 — Custom download manager endpoint](07%20Polish%20pass/S036-custom-download-manager.md) · superseded by S065 +- [x] [S036 — Custom download manager endpoint](07%20Polish%20pass/S036-custom-download-manager.md) · superseded by S065 - [ ] [S039 — Motion rules and animations](07%20Polish%20pass/S039-motion.md) · Opus medium (+ `docs/ui-motion-audit.md` blocks A–E) - [ ] [S040 — Little things sweep](07%20Polish%20pass/S040-little-things.md) · Opus medium - [ ] [S041 — Site passes](07%20Polish%20pass/S041-site-passes.md) · Opus high · 🧑 diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 04ad534..16caf96 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -393,3 +393,49 @@ See `docs/FEATURES.md`; every row names the file that implements it and its revi to `Hub::blocked` (reset in the `load-changed` Started handler). Limits: depends on WebKit's console wording; WebKit may not log blocks for every load type (checked: script, image, fetch, module, async/defer, dynamic import); a block logged just after a new page starts may count for the new page. + +## Custom download manager (D-022, D-050, S065) + +Settings → Downloads → Download managers → "Add your own": a name and a port (1–65535, one entry per port). +Stored as `downloads.custom_managers` (`[{name, port, enabled}]`); chosen in "New downloads go to" as +`downloads.manager = "custom:"`. Loopback only: the endpoint is always `http://127.0.0.1:/` (no host +field), so cookies never leave the machine and the VPN is never used (`net/dlm.rs`, `fetch::local_agent`). + +- **Status ping**: `GET /`; any 2xx = "Found · port N", anything else = "Not running". +- **Hand-over**: `POST /` with `Content-Type: application/json`; any 2xx = taken (the download shows as + "Sent to "); any other answer or no answer = Nacre downloads the file itself and the toast says why. + +```http +POST / HTTP/1.1 +Host: 127.0.0.1:8123 +Content-Type: application/json + +{"url": "https://example.com/file.zip", "filename": "file.zip", "referrer": "https://example.com/", + "cookies": "session=abc", "user_agent": "Mozilla/5.0 …", + "headers": {"Cookie": "session=abc", "User-Agent": "Mozilla/5.0 …", "Referer": "https://example.com/"}, + "size": null, "mime": null} +``` + +`cookies` is the Cookie header Nacre would send for that URL (empty when none); `headers` holds only the ones that +are set; `size` and `mime` are null (not known before the download starts). A minimal receiver: + +```python +#!/usr/bin/env python3 +# Receives Nacre's downloads on 127.0.0.1:8123 and fetches them with curl. +import json, subprocess +from http.server import BaseHTTPRequestHandler, HTTPServer + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): # Nacre's status ping + self.send_response(200); self.end_headers() + + def do_POST(self): # a download handed over + item = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + args = ["curl", "-L", "-o", item["filename"] or "download", item["url"]] + for name, value in item["headers"].items(): + args += ["-H", f"{name}: {value}"] + subprocess.Popen(args) + self.send_response(200); self.end_headers() + +HTTPServer(("127.0.0.1", 8123), Handler).serve_forever() +``` diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index d65ff75..94d9894 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -515,6 +515,15 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor - Verified: hidden `flyouts.txt` (needs `python3 -m http.server 8765 --directory tests/smoke/pages`) exit 0, shots read; `cargo test` 92 + webext 1. - Not done: favicons in flyout rows (icon only, as on the page); no visible run. +## S065 — Custom download manager by name and port (2026-11-18) +- Done (D-050): Settings → Downloads → Download managers → "Add your own" (name + port, checked: name given, port 1–65535, one entry per port; the reason shows in the row); entries listed with "Found · port N" / "Not running", a switch and Remove; chosen in "New downloads go to" and the downloads flyout. Loopback only. +- Settings: `downloads.custom_managers` = `[{name, port, enabled}]`, chosen as `downloads.manager = "custom:"`. `net/dlm.rs`: `custom_key`, `is_on`, `label`, `enabled`, `parse_custom`, `custom_body`; ping = `GET http://127.0.0.1:/`, hand-over = `POST /` with D-022's JSON (no token, D-050); fallback = Nacre downloads it, toast says why. Contract + example request + Python receiver: DESIGN.md "Custom download manager". +- Smoke: `server.py` `POST /` records manager "custom" (port, Content-Type, body); `net-downloads.txt` custom case: handed over on 8767 (body checked in `/log`), fallback on port 9 → `file (3).zip`, `managers-custom` shot. Selftest `cmd ping_managers` (new). +- Verified: `net-downloads.txt` exit 0 (also at 1400x2600, shot read); `cargo test` 94 + webext 1 (2 new dlm tests). +- Not done: Add/Remove/switch not clicked in a smoke (set through settings JSON; the shot shows them). +- Later: the managers page is wider than a 1280 px window (intro line and Port fields clipped at the right edge, seen in the 1280x800 shot; not from this plan). +- Note: a stale `server.py` from an earlier session held port 8766; check `pgrep -f net/server.py` before starting one. + ## Later - A link followed inside a frame still goes through the tab's navigation policy (WebKit's GTK API has no frame info; S050). - file:// media outside the XDG user folders doesn't play (WebKit sandbox, D-043). diff --git a/src/actions.rs b/src/actions.rs index 7b024ce..5f40abf 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -1820,12 +1820,12 @@ impl App { let settings = self.shared.settings.borrow().downloads.clone(); let name = name.unwrap_or_else(|| util::file_name_from_url(&url)); // An external download manager takes it, if one is chosen and turned on. - if settings.manager != "builtin" && settings.managers.contains(&settings.manager) && path.is_none() { + if settings.manager != "builtin" && crate::net::dlm::is_on(&settings.manager, &settings) && path.is_none() { let key = settings.manager.clone(); let headers = self.request_headers(&url, &page); let cookie = headers.iter().find(|(k, _)| k == "cookie").map(|(_, v)| v.clone()).unwrap_or_default(); let item = crate::net::dlm::Handoff { url: url.to_string(), file_name: name.clone(), page_url: page.clone(), cookie, user_agent: self.shared.user_agent.borrow().clone() }; - let manager_name = crate::net::dlm::by_key(&key).map(|m| m.name).unwrap_or("the download manager").to_owned(); + let manager_name = crate::net::dlm::label(&key, &settings, false).unwrap_or_else(|| "the download manager".into()); self.spawn("dlm", move || crate::net::dlm::add(&key, &settings, &item), move |app, result| match result { Ok(()) => { app.shared.downloads.borrow_mut().add_handed_off(url.as_str(), &page, &name, &manager_name); @@ -2007,11 +2007,12 @@ impl App { pub fn ping_download_managers(&mut self) { let settings = self.shared.settings.borrow().downloads.clone(); - for manager in crate::net::dlm::available() { - let key = manager.key; + let keys = crate::net::dlm::available().map(|m| m.key.to_owned()).chain(settings.custom_managers.iter().map(|c| crate::net::dlm::custom_key(c.port))); + for key in keys.collect::>() { let cfg = settings.clone(); - self.spawn("dlm-ping", move || crate::net::dlm::ping(key, &cfg), move |app, result| { - app.shared.dlm_status.borrow_mut().insert(key.to_owned(), result); + let k = key.clone(); + self.spawn("dlm-ping", move || crate::net::dlm::ping(&k, &cfg), move |app, result| { + app.shared.dlm_status.borrow_mut().insert(key, result); app.redraw_all(); }); } diff --git a/src/net/dlm.rs b/src/net/dlm.rs index f8872b4..2080beb 100644 --- a/src/net/dlm.rs +++ b/src/net/dlm.rs @@ -1,6 +1,7 @@ //! External download managers. A download can be handed to one of them instead of Nacre's own //! downloader. HTTP ones are reached on their local port (never through the VPN); FDM and IDM are -//! started with the link on their command line. +//! started with the link on their command line. The user's own managers (D-050) get D-022's JSON on +//! `http://127.0.0.1:/`; see DESIGN.md "Custom download manager". use std::process::Command; use std::time::Duration; @@ -8,7 +9,7 @@ use std::time::Duration; use serde_json::json; use crate::net::fetch; -use crate::store::settings::Downloads; +use crate::store::settings::{CustomManager, Downloads}; use crate::util; pub struct Manager { @@ -37,6 +38,56 @@ pub fn by_key(key: &str) -> Option<&'static Manager> { available().find(|m| m.key == key) } +/// Settings key of one of the user's own managers. +pub fn custom_key(port: u16) -> String { + format!("custom:{port}") +} + +fn custom<'a>(key: &str, cfg: &'a Downloads) -> Option<&'a CustomManager> { + let port: u16 = key.strip_prefix("custom:")?.parse().ok()?; + cfg.custom_managers.iter().find(|c| c.port == port) +} + +/// Is the manager turned on in settings? +pub fn is_on(key: &str, cfg: &Downloads) -> bool { + match custom(key, cfg) { + Some(c) => c.enabled, + None => by_key(key).is_some() && cfg.managers.iter().any(|k| k == key), + } +} + +/// The manager's name (or its short name, for tight rows). +pub fn label(key: &str, cfg: &Downloads, short: bool) -> Option { + match custom(key, cfg) { + Some(c) => Some(c.name.clone()), + None => by_key(key).map(|m| if short { m.short } else { m.name }.to_owned()), + } +} + +/// Managers turned on, as (key, name, short name): the known ones first, then the user's own. +pub fn enabled(cfg: &Downloads) -> Vec<(String, String, String)> { + let known = available().filter(|m| cfg.managers.iter().any(|k| k == m.key)).map(|m| (m.key.to_owned(), m.name.to_owned(), m.short.to_owned())); + let own = cfg.custom_managers.iter().filter(|c| c.enabled).map(|c| (custom_key(c.port), c.name.clone(), c.name.clone())); + known.chain(own).collect() +} + +/// A custom manager typed in settings: a name and a port no other custom manager uses. Loopback only, so there is +/// no host to give. +pub fn parse_custom(name: &str, port: &str, cfg: &Downloads) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err("Give it a name".into()); + } + let port: u16 = match port.trim().parse() { + Ok(p) if p > 0 => p, + _ => return Err("The port is a number from 1 to 65535".into()), + }; + if cfg.custom_managers.iter().any(|c| c.port == port) { + return Err(format!("Port {port} is already in the list")); + } + Ok(CustomManager { name: name.to_owned(), port, enabled: true }) +} + /// What to hand over. #[derive(Clone, Debug, Default)] pub struct Handoff { @@ -47,6 +98,35 @@ pub struct Handoff { pub user_agent: String, } +/// Cookie, User-Agent and Referer as request headers. +fn headers(item: &Handoff) -> serde_json::Map { + let mut headers = serde_json::Map::new(); + if !item.cookie.is_empty() { + headers.insert("Cookie".into(), json!(item.cookie)); + } + if !item.user_agent.is_empty() { + headers.insert("User-Agent".into(), json!(item.user_agent)); + } + if !item.page_url.is_empty() { + headers.insert("Referer".into(), json!(item.page_url)); + } + headers +} + +/// D-022's hand-over body for the user's own managers. Size and type aren't known before the download starts. +pub fn custom_body(item: &Handoff) -> serde_json::Value { + json!({ + "url": item.url, + "filename": item.file_name, + "referrer": item.page_url, + "cookies": item.cookie, + "user_agent": item.user_agent, + "headers": headers(item), + "size": null, + "mime": null, + }) +} + fn post(url: &str, body: Vec, content_type: &str, timeout: Duration) -> Result, String> { let mut response = fetch::local_agent(timeout).post(url).header("content-type", content_type).send(&body[..]).map_err(|e| e.to_string())?; let status = response.status().as_u16(); @@ -120,7 +200,10 @@ pub fn ping(key: &str, cfg: &Downloads) -> Result { _ => Err("Not running".into()), }, "fdm" | "idm" => cli_exe(key, cfg).map(|p| p.display().to_string()).ok_or_else(|| "Not installed".into()), - _ => Err("Unknown download manager".into()), + _ => match custom(key, cfg) { + Some(c) => get(&format!("http://127.0.0.1:{}/", c.port), quick).map(|_| format!("port {}", c.port)).map_err(|_| "Not running".into()), + None => Err("Unknown download manager".into()), + }, } } @@ -129,18 +212,8 @@ pub fn add(key: &str, cfg: &Downloads, item: &Handoff) -> Result<(), String> { let slow = Duration::from_secs(4); match key { "abdm" => { - let mut headers = serde_json::Map::new(); - if !item.cookie.is_empty() { - headers.insert("Cookie".into(), json!(item.cookie)); - } - if !item.user_agent.is_empty() { - headers.insert("User-Agent".into(), json!(item.user_agent)); - } - if !item.page_url.is_empty() { - headers.insert("Referer".into(), json!(item.page_url)); - } let body = json!({ - "items": [{"link": item.url, "headers": headers, "downloadPage": item.page_url, "suggestedName": item.file_name, "type": "http"}], + "items": [{"link": item.url, "headers": headers(item), "downloadPage": item.page_url, "suggestedName": item.file_name, "type": "http"}], "options": {"silentAdd": false, "silentStart": false} }); post(&format!("http://127.0.0.1:{}/add", cfg.abdm_port), body.to_string().into_bytes(), "application/json", slow).map(|_| ()) @@ -193,6 +266,48 @@ pub fn add(key: &str, cfg: &Downloads, item: &Handoff) -> Result<(), String> { } command.spawn().map(|_| ()).map_err(|e| e.to_string()) }, - _ => Err("Unknown download manager".into()), + _ => match custom(key, cfg) { + Some(c) => post(&format!("http://127.0.0.1:{}/", c.port), custom_body(item).to_string().into_bytes(), "application/json", slow).map(|_| ()), + None => Err("Unknown download manager".into()), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn custom_body_follows_d022() { + let item = Handoff { url: "https://example.com/a.zip".into(), file_name: "a.zip".into(), page_url: "https://example.com/".into(), cookie: "k=v".into(), user_agent: "UA".into() }; + let body = custom_body(&item); + assert_eq!(body["url"], "https://example.com/a.zip"); + assert_eq!(body["filename"], "a.zip"); + assert_eq!(body["referrer"], "https://example.com/"); + assert_eq!(body["cookies"], "k=v"); + assert_eq!(body["user_agent"], "UA"); + assert_eq!(body["headers"]["Cookie"], "k=v"); + assert_eq!(body["headers"]["Referer"], "https://example.com/"); + assert!(body["size"].is_null() && body["mime"].is_null()); + let bare = custom_body(&Handoff { url: "https://example.com/b".into(), ..Default::default() }); + assert_eq!(bare["headers"], json!({})); + } + + #[test] + fn custom_manager_ports() { + let mut cfg = Downloads::default(); + let added = parse_custom(" Mine ", "8123", &cfg).expect("valid"); + assert_eq!((added.name.as_str(), added.port, added.enabled), ("Mine", 8123, true)); + assert!(parse_custom("Mine", "0", &cfg).is_err()); + assert!(parse_custom("Mine", "65536", &cfg).is_err()); + assert!(parse_custom("Mine", "port", &cfg).is_err()); + assert!(parse_custom(" ", "8123", &cfg).is_err()); + cfg.custom_managers.push(added); + assert!(parse_custom("Other", "8123", &cfg).is_err(), "one entry per port"); + assert!(is_on(&custom_key(8123), &cfg)); + assert_eq!(label("custom:8123", &cfg, true).as_deref(), Some("Mine")); + assert!(!is_on("custom:9000", &cfg)); + cfg.custom_managers[0].enabled = false; + assert!(!is_on("custom:8123", &cfg) && enabled(&cfg).is_empty()); } } diff --git a/src/selftest.rs b/src/selftest.rs index a555132..629d76f 100644 --- a/src/selftest.rs +++ b/src/selftest.rs @@ -21,7 +21,7 @@ //! blur leave the address field (as Escape does) //! hover [pip]|none move the pointer over the window (points; `pip`: the picture-in-picture window), or away //! do a shortcut action by its settings key, e.g. `do new_tab` -//! cmd [arg] back, forward, reload, bookmark, install_app, pip, exitpip, free_memory, +//! cmd [arg] back, forward, reload, bookmark, install_app, pip, exitpip, free_memory, ping_managers, //! update_lists, check_updates, close_tab, select , zoom , //! find , download , pause_download|resume_download|cancel_download [id] (newest), //! import (bookmarks, history, settings from the n-th found browser profile), @@ -463,6 +463,7 @@ impl App { "pip" => Command::EnterPip, "exitpip" => Command::ClosePip(tab), "free_memory" => Command::FreeMemory, + "ping_managers" => Command::PingManagers, "update_lists" => Command::UpdateFilterLists, "check_updates" => Command::CheckUpdates, "close_tab" => Command::CloseTab(tab), diff --git a/src/store/settings.rs b/src/store/settings.rs index f8a8761..485198c 100644 --- a/src/store/settings.rs +++ b/src/store/settings.rs @@ -277,7 +277,7 @@ pub struct Downloads { pub ask: bool, /// Show the downloads list when a download starts. pub auto_open: bool, - /// "builtin" or a key from `net::dlm::MANAGERS`: where new downloads go. + /// "builtin", a key from `net::dlm::MANAGERS` or `custom:`: where new downloads go. pub manager: String, /// Managers turned on in settings. pub managers: Vec, @@ -287,6 +287,22 @@ pub struct Downloads { pub jd_port: u16, pub fdm_path: String, pub idm_path: String, + /// The user's own managers (D-050), reached on `http://127.0.0.1:/`; chosen as `custom:`. + pub custom_managers: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(default)] +pub struct CustomManager { + pub name: String, + pub port: u16, + pub enabled: bool, +} + +impl Default for CustomManager { + fn default() -> Self { + Self { name: String::new(), port: 0, enabled: true } + } } impl Default for Downloads { @@ -303,6 +319,7 @@ impl Default for Downloads { jd_port: 9666, fdm_path: String::new(), idm_path: String::new(), + custom_managers: Vec::new(), } } } diff --git a/src/ui/menus.rs b/src/ui/menus.rs index d77a51a..ed6fea5 100644 --- a/src/ui/menus.rs +++ b/src/ui/menus.rs @@ -727,10 +727,10 @@ fn downloads(ui: &mut Ui, f: &mut Frame) { }); // Where new downloads go. let mut settings = f.shared.settings.borrow_mut(); - let enabled: Vec = settings.downloads.managers.clone(); + let enabled = crate::net::dlm::enabled(&settings.downloads); if !enabled.is_empty() { let mut keys = vec![("builtin".to_owned(), "Nacre")]; - keys.extend(enabled.iter().filter_map(|key| crate::net::dlm::by_key(key).map(|m| (key.clone(), m.short)))); + keys.extend(enabled.iter().map(|(key, _, short)| (key.clone(), short.as_str()))); let mut index = keys.iter().position(|(k, _)| *k == settings.downloads.manager).unwrap_or(0); let options: Vec<(usize, &str)> = keys.iter().enumerate().map(|(i, (_, label))| (i, *label)).collect(); line(ui, "Download with", |ui| { diff --git a/src/ui/pages/mod.rs b/src/ui/pages/mod.rs index 98876bc..ca88758 100644 --- a/src/ui/pages/mod.rs +++ b/src/ui/pages/mod.rs @@ -31,6 +31,8 @@ pub struct PageState { /// The shortcut being recorded was drawn this frame. pub capture_shown: bool, pub new_engine: (String, String), + /// Name and port typed for a custom download manager. + pub new_manager: (String, String), pub new_list_url: String, pub keep_active_input: String, pub new_profile: String, diff --git a/src/ui/pages/settings.rs b/src/ui/pages/settings.rs index 29257d6..2a36fe7 100644 --- a/src/ui/pages/settings.rs +++ b/src/ui/pages/settings.rs @@ -951,7 +951,7 @@ fn downloads(ui: &mut Ui, f: &mut Frame, s: &mut Settings) { } switch_row(ui, "Ask where to save each file", "", &mut s.downloads.ask); switch_row(ui, "Show downloads when they start", "", &mut s.downloads.auto_open); - let using = if s.downloads.manager == "builtin" { "Nacre".to_owned() } else { crate::net::dlm::by_key(&s.downloads.manager).map(|m| m.name.to_owned()).unwrap_or_default() }; + let using = if s.downloads.manager == "builtin" { "Nacre".to_owned() } else { crate::net::dlm::label(&s.downloads.manager, &s.downloads, false).unwrap_or_default() }; if icon_link_row(ui, icons::DOWNLOAD, "Download managers", &format!("New downloads go to {using}")) { open(f, "managers"); } @@ -963,8 +963,9 @@ fn managers(ui: &mut Ui, f: &mut Frame, s: &mut Settings) { section(ui, "Where downloads go"); card(ui, |ui| { wide_row(ui, "New downloads go to", "Turn a manager on below to choose it here", |ui| { + let enabled = crate::net::dlm::enabled(&s.downloads); let mut options = vec![("builtin".to_owned(), "Nacre")]; - options.extend(crate::net::dlm::available().filter(|m| s.downloads.managers.iter().any(|k| k == m.key)).map(|m| (m.key.to_owned(), m.name))); + options.extend(enabled.iter().map(|(key, name, _)| (key.clone(), name.as_str()))); choice_chips(ui, &mut s.downloads.manager, &options); }); }); @@ -1013,6 +1014,56 @@ fn managers(ui: &mut Ui, f: &mut Frame, s: &mut Settings) { }); ui.add_space(theme::GAP_S); } + // The user's own managers (D-050): a name and a local port, sent D-022's JSON (DESIGN.md "Custom download manager"). + let mut remove = None; + for (i, c) in s.downloads.custom_managers.iter_mut().enumerate() { + let key = crate::net::dlm::custom_key(c.port); + card(ui, |ui| { + let status = match statuses.get(&key) { + Some(Ok(where_)) => format!("Found · {where_}"), + Some(Err(why)) => format!("{why} · port {}", c.port), + None => "Checking…".into(), + }; + row(ui, &c.name, &format!("Your own manager on http://127.0.0.1:{}/ · {status}", c.port), |ui| { + // Right to left: the switch lines up with the other managers' switches. + switch(ui, &mut c.enabled); + if icon_button(ui, icons::DELETE, "Remove this download manager").clicked() { + remove = Some(i); + } + }); + }); + ui.add_space(theme::GAP_S); + } + if let Some(i) = remove { + let gone = s.downloads.custom_managers.remove(i); + if s.downloads.manager == crate::net::dlm::custom_key(gone.port) { + s.downloads.manager = "builtin".into(); + } + } + if s.downloads.manager.starts_with("custom:") && !crate::net::dlm::is_on(&s.downloads.manager, &s.downloads) { + s.downloads.manager = "builtin".into(); + } + card(ui, |ui| { + let (name, port) = &f.ui.pages.new_manager; + let parsed = crate::net::dlm::parse_custom(name, port, &s.downloads); + let typed = !name.trim().is_empty() || !port.trim().is_empty(); + let desc = match &parsed { + Err(why) if typed => why.clone(), + _ => "Any program that takes a JSON POST on a local port; see the contract in Nacre's docs".to_owned(), + }; + wide_row(ui, "Add your own", &desc, |ui| { + text_field(ui, &mut f.ui.pages.new_manager.0, "Name", 160.0); + text_field(ui, &mut f.ui.pages.new_manager.1, "Port", 90.0); + if ui.add_enabled_ui(parsed.is_ok(), |ui| button(ui, ButtonKind::Tonal, Some(icons::ADD), "Add")).inner.clicked() + && let Ok(manager) = parsed + { + s.downloads.custom_managers.push(manager); + f.ui.pages.new_manager = Default::default(); + f.send(Command::PingManagers); + } + }); + }); + ui.add_space(theme::GAP_S); ui.horizontal(|ui| { ui.add_space(theme::GAP_S); if button(ui, ButtonKind::Outlined, Some(icons::REFRESH), "Check again").clicked() { diff --git a/tests/smoke/net-downloads.txt b/tests/smoke/net-downloads.txt index 9e15acb..8474d75 100644 --- a/tests/smoke/net-downloads.txt +++ b/tests/smoke/net-downloads.txt @@ -1,11 +1,12 @@ # Network pass (S007): downloads. A link by its file type and one by its Content-Disposition header land in the # "Save to" folder; a slow 4 MiB file pauses and resumes with a Range request; another is cancelled; the external # download managers get the link (aria2, AB Download Manager and JDownloader stubs in tests/smoke/net/server.py, a -# dummy FDM program, tests/smoke/net/fake-fdm.sh) and Nacre downloads it itself when the manager isn't there. +# dummy FDM program, tests/smoke/net/fake-fdm.sh) and Nacre downloads it itself when the manager isn't there; the +# user's own manager by port (S065, D-050: POST / on 8767 with D-022's JSON) takes one and falls back when it's down. # Offline. Never Tor or proxies. Start the server first: # python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/net-downloads.txt # Afterwards: /home/saved/ has file.zip, report.txt, their (1) copies, named.zip (), made.txt (blob:), -# file (2).zip (manager fallback), big.bin (4194304 bytes, byte i = i % 251) and no .part; +# file (2).zip (manager fallback), file (3).zip (custom manager fallback), big.bin (4194304 bytes, byte i = i % 251) and no .part; # /home/fdm-args.txt has the FDM link. wait 3 set /downloads/dir "@HOME@/saved" @@ -124,5 +125,29 @@ cmd download http://127.0.0.1:8766/file.zip?to=fallback wait 6 status fallback expect /downloads/0/state "Done" +# The user's own manager (S065): a name and a port, chosen as custom:, gets D-022's JSON on POST /. +set /downloads/custom_managers [{"name":"Test manager","port":8767,"enabled":true},{"name":"Down manager","port":9,"enabled":true}] +set /downloads/manager "custom:8767" +cmd download http://127.0.0.1:8766/file.zip?to=custom +wait 2 +status custom +expect /downloads/0/state "HandedOff" +expect /downloads/0/manager "Test manager" +js fetch("http://127.0.0.1:8766/log").then(r => r.json()).then(l => { window.netlog2 = l; }) +waitfor 5 window.netlog2 !== undefined +js JSON.stringify(window.netlog2.dlm.filter(c => c.manager === "custom")) +assert window.netlog2.dlm.some(c => c.manager === "custom" && c.port === 8767 && c.type === "application/json" && c.body.url.endsWith("to=custom") && c.body.filename === "file.zip" && c.body.referrer === "http://127.0.0.1:8766/" && c.body.headers.Referer === c.body.referrer && "cookies" in c.body && c.body.user_agent.length > 0 && c.body.headers["User-Agent"] === c.body.user_agent && c.body.size === null && c.body.mime === null) +# Down: Nacre downloads it itself. +set /downloads/manager "custom:9" +cmd download http://127.0.0.1:8766/file.zip?to=custom-fallback +wait 6 +status custom-fallback +expect /downloads/0/state "Done" +expect /downloads/0/name "file (3).zip" +# The settings page lists both with their status; the add row checks the port. +cmd ping_managers +page nacre://settings/managers +wait 3 +shot managers-custom status done quit diff --git a/tests/smoke/net/server.py b/tests/smoke/net/server.py index af55160..9f34509 100644 --- a/tests/smoke/net/server.py +++ b/tests/smoke/net/server.py @@ -19,6 +19,8 @@ certificate for *.nacre.test. Port 8767 speaks plain HTTP only (an HTTPS upgrade /attachment small file with Content-Disposition: attachment (a download by its headers); /report the same file at a path that gives no hint /add, /jsonrpc, /flashgot stubs for AB Download Manager, aria2 and JDownloader 2 + POST / a custom download manager (S065, D-050: the user's own, by port; GET / is its status ping): + the JSON body, Content-Type and port go to /log "dlm" as manager "custom" /setcookie?name=N[&domain=D][&ss=lax|none] sets cookie N=1 (Path=/, SameSite=None; Secure, so https only, or the ss= variant; Domain=D if given); /cookies shows the Cookie header in the title; /pixel is a 1x1 GIF; /tp?tag=T is a page with a cross-site iframe and picture (https://cdn.other.test:8766) and a @@ -262,6 +264,9 @@ class Handler(BaseHTTPRequestHandler): if path in ("/flashgot", "/flash/add"): record("dlm", {"manager": "jdownloader", "path": path, "form": parse_qs(body)}) return self.reply(b"success\r\n", "text/plain") + if path == "/": + record("dlm", {"manager": "custom", "port": self.server.server_address[1], "type": self.headers.get("Content-Type"), "body": json.loads(body)}) + return self.reply(b"OK", "text/plain") self.reply(b"not found", "text/plain", status=404) def big(self):