S065: custom download managers by name and port (D-050), D-022 JSON on 127.0.0.1:<port>, smoke case
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
8386b32064
commit
e258b5b120
7 changed files with 310 additions and 38 deletions
|
|
@ -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::<Vec<_>>() {
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
|
|
|||
145
src/net/dlm.rs
145
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:<port>/`; 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<String> {
|
||||
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<CustomManager, String> {
|
||||
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<String, serde_json::Value> {
|
||||
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<u8>, content_type: &str, timeout: Duration) -> Result<Vec<u8>, 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<String, String> {
|
|||
_ => 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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@
|
|||
//! blur leave the address field (as Escape does)
|
||||
//! hover <x> <y> [pip]|none move the pointer over the window (points; `pip`: the picture-in-picture window), or away
|
||||
//! do <action> a shortcut action by its settings key, e.g. `do new_tab`
|
||||
//! cmd <name> [arg] back, forward, reload, bookmark, install_app, pip, exitpip, free_memory,
|
||||
//! cmd <name> [arg] back, forward, reload, bookmark, install_app, pip, exitpip, free_memory, ping_managers,
|
||||
//! update_lists, check_updates, close_tab, select <n>, zoom <step>,
|
||||
//! find <text>, download <url>, pause_download|resume_download|cancel_download [id] (newest),
|
||||
//! import <n> (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),
|
||||
|
|
|
|||
|
|
@ -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:<port>`: where new downloads go.
|
||||
pub manager: String,
|
||||
/// Managers turned on in settings.
|
||||
pub managers: Vec<String>,
|
||||
|
|
@ -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:<port>/`; chosen as `custom:<port>`.
|
||||
pub custom_managers: Vec<CustomManager>,
|
||||
}
|
||||
|
||||
#[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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<String> = 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| {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
Loading…
Reference in a new issue