misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
feat(debrid): add TorBox for file-host links and torrents (#566)
Not_Noob26f5b00f8943
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 12a07554..892822f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see- Links you add by hand go with the User-Agent of your default browser, at the version you have installed (Chrome, Edge, Brave, Opera, Vivaldi, Firefox or Safari, on Windows, Linux and macOS), instead of the Internet Explorer 11 one MDM sent until now, which some sites no longer let through. MDM looks the browser up once as it starts. **Options → Downloads** shows it with **Automatic** ticked; untick it to type your own, and a User-Agent you had set stays yours. When MDM doesn't recognise your default browser, it sends a current Chrome's; when a site turns a browser's User-Agent away, it asks once more with its former one, as for downloads from the browser (part of [#668](https://github.com/anefzaoui/misterdownloadmanager/issues/668)).- Linux and macOS: a gallery-dl installed by the system (a package manager, Homebrew, pip) is found and used when MDM has none of its own, as yt-dlp is; **Helpers** can switch to MDM's own copy where MDM has one (Windows and Linux x86-64) ([#571](https://github.com/anefzaoui/misterdownloadmanager/issues/571)).- Videos a site sends in pieces (HLS and DASH streams, as many sites other than YouTube do) download several pieces at once, as many as **Options → Connection** gives a file (8 by default): against a test server that slows each connection, 4 at once took under a third of the time, 8 under a fifth. With a speed limit on, they still come one at a time, so the limit holds; a video in one file, as most of YouTube's are, is unchanged. The command line's `video-get` and `playlist-get` take `-c` for it ([#531](https://github.com/anefzaoui/misterdownloadmanager/issues/531)).+- **TorBox** debrid accounts (experimental), in **Options → Accounts**, signed in in the browser or with your API key: file-host links, torrents and magnet links through your account ([#391](https://github.com/anefzaoui/misterdownloadmanager/issues/391)).- Linux and macOS: a yt-dlp installed by the system (a package manager, Homebrew) is found and used when MDM has none of its own; **Helpers** can still switch to MDM's own copy, kept up to date ([#452](https://github.com/anefzaoui/misterdownloadmanager/issues/452)).### Changeddiff --git a/Cargo.lock b/Cargo.lockindex 76129acf..52c3a799 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4537,6 +4537,7 @@ name = "mdm-debrid"version = "0.5.2"dependencies = ["bytes",+ "chrono","futures","mdm-engine","mdm-labserver",diff --git a/README.md b/README.mdindex 05f1beb9..dc9a460c 100644--- a/README.md+++ b/README.md@@ -284,7 +284,7 @@ right-to-left window.the sound alone), **image galleries** with gallery-dl, and **torrents and magnet links**(sequential order, RSS feeds, sharing limits).- **Many links at once**: the Link grabber sorts them into packages and extracts the archives- (zip, 7z, rar) when they're in. Debrid accounts (Real-Debrid, AllDebrid, Premiumize; experimental) download+ (zip, 7z, rar) when they're in. Debrid accounts (Real-Debrid, AllDebrid, Premiumize, TorBox; experimental) downloadfile-host links through your own account.- **Downloads overnight** with queues and a scheduler that can wake the computer, then shuts itdown if you like.diff --git a/ROADMAP.md b/ROADMAP.mdindex a9f26046..771bb74e 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -320,6 +320,8 @@ Everything below ships together, in version 0.5.0.([#44](https://github.com/anefzaoui/misterdownloadmanager/issues/44))- ✅ Debrid accounts: torrents and magnet links through the service, their files downloaded overHTTP, no peer connections ([#44](https://github.com/anefzaoui/misterdownloadmanager/issues/44))+- ✅ Debrid accounts (experimental): TorBox, for file-host links and torrents+ ([#391](https://github.com/anefzaoui/misterdownloadmanager/issues/391))- ✅ Sign-ins in the system's keychain: Windows Credential Manager, the Secret Service keyring onLinux, the macOS keychain; for debrid accounts, Sites Logins and the proxy([#44](https://github.com/anefzaoui/misterdownloadmanager/issues/44))diff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 8f1b8fa9..99533e76 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -2736,10 +2736,35 @@ impl App {self.selection.after_removal(&before, &after);}+ /// Download `id` went through a debrid account and ended (done, or taken off the list): the+ /// service forgets its link (TorBox's list of web downloads, #391). A paused one keeps it,+ /// to go on with.+ fn release_link(&self, id: u64) {+ let Some(i) = self.items.iter().find(|i| i.id == id) else {+ return;+ };+ if !self.settings.debrid_on+ || i.direct+ || i.remote.is_some()+ || i.torrent.is_some()+ || i.video.is_some()+ || i.gallery.is_some()+ {+ return;+ }+ let (debrid, url) = (self.debrid.clone(), i.url.clone());+ self.rt.spawn(async move {+ if let Err(e) = debrid.release(&url).await {+ tracing::warn!("debrid: the link stays in the service's list: {e:?}");+ }+ });+ }+/// Take a download off the list (not while it runs); with `files`, its file goes from disk/// too: a finished file, or the data so far (a torrent's files when its session runs).fn remove_download(&mut self, id: u64, files: bool) {if self.item(id).is_some_and(|i| i.live.is_none()) {+ self.release_link(id);if let Some(spec) = self.item(id).and_then(|i| i.torrent.clone()) {self.torrent_host.forget(&self.rt, &spec.hash, files);} else if files@@ -5605,6 +5630,7 @@ impl App {}}for id in &finished {+ self.release_link(*id);self.failures.remove(id);// Its archive, when it is to be extracted and its last volume is in (#37).self.extracts.finished(*id, &self.items, &self.settings);diff --git a/crates/app/src/model.rs b/crates/app/src/model.rsindex 757f157a..4ff3f5d7 100644--- a/crates/app/src/model.rs+++ b/crates/app/src/model.rs@@ -525,6 +525,7 @@ fn tool_snapshot(p: mdm_tools::video::Progress, url: &Url) -> mdm_engine::Snapsh.collect(),// yt-dlp's and gallery-dl's connections are theirs: not seen here (#140).server: None,+ at_service: None,}}@@ -886,16 +887,18 @@ impl Item {}/// The Status column: `13.38%`, `Complete`, `Error`, or blank.- /// A torrent at its debrid service (#44), before its files come: "45% at Real-Debrid" (the- /// percentage first: the list's Status column is narrow).+ /// A torrent at its debrid service (#44), before its files come, or a file-host link whose file+ /// the service fetches first (TorBox): "45% at Real-Debrid" (the percentage first: the list's+ /// Status column is narrow).pub fn at_service(&self) -> Option<String> {- let Some(Live {- dl: Job::Remote(r), ..- }) = &self.live- else {- return None;+ let (service, progress) = match &self.live {+ Some(Live {+ dl: Job::Remote(r), ..+ }) => r.at_service().map(|(s, p)| (s.to_owned(), p))?,+ Some(_) => self.snap.as_ref()?.at_service.clone()?,+ None => return None,};- let (service, progress) = r.at_service()?;+ let service = service.as_str();Some(crate::i18n::fmt(// i18n: a torrent's status while the user's debrid service downloads it, before MDM gets its files; {service} the service ("Real-Debrid"), {percent} how far it is ("45%")crate::i18n::t("{percent} at {service}"),diff --git a/crates/app/src/options.rs b/crates/app/src/options.rsindex abfdda10..1045fbee 100644--- a/crates/app/src/options.rs+++ b/crates/app/src/options.rs@@ -3366,7 +3366,10 @@ impl OptionsDialog {"opt-account",// i18n: window title: adding a debrid service account (Real-Debrid…)"Add an account",- [420.0, 300.0],+ [+ 420.0,+ 300.0 + crate::dialogs::grow_extra(ctx, "opt-account"),+ ],false,LIGHT_BG(),|ui, o| account_dialog(ui, o, &mut e),@@ -3804,13 +3807,24 @@ fn dns_dialog(ui: &mut Ui, o: Pos2, e: &mut DnsEdit) -> Outcome<()> {}/// Accounts → Add...: the service, a token typed in, and the sign-in on its thread (#44).-#[derive(Default)]struct AccountEdit {service: mdm_debrid::ServiceKind,token: String,signin: crate::debrid::SignIn,}+/// It starts on the first service Options lists (not `ServiceKind`'s default, Real-Debrid,+/// which saved accounts fall back to).+impl Default for AccountEdit {+ fn default() -> Self {+ AccountEdit {+ service: mdm_debrid::ServiceKind::ALL[0],+ token: String::new(),+ signin: Default::default(),+ }+ }+}+/// Accounts → Add...: sign in by code in the browser (Real-Debrid's device flow, AllDebrid's PIN),/// or paste the API token (Premiumize: its API key only); the account is checked before it is kept.fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settings::DebridAccount> {@@ -3819,6 +3833,8 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingslet ctx = ui.ctx().clone();let state = e.signin.get();let busy = matches!(state, S::Starting | S::Waiting { .. } | S::Checking);+ // What the sign-in text took beyond its three lines: everything under it moves down.+ let extra = crate::dialogs::grow_extra(&ctx, "opt-account");// i18n: Options → Add an account: label before the choice of debrid servicetext(&p,@@ -3870,15 +3886,17 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingsif let S::Waiting { code, page, until } = &state {// The code, large, to type at the service's page.let code_font = egui::FontId::monospace(crate::theme::metrics().font_code);+ let code_w = winui::text_width_font(&p, code_font.clone(), code);+ // At the leading edge: mirrored in a right-to-left interface, as the buttons are.p.text(- o + vec2(14.0, 78.0),+ winui::at(o + vec2(14.0, 78.0), code_w),egui::Align2::LEFT_TOP,code,- code_font.clone(),+ code_font,LIGHT_TEXT(),);// The buttons as wide as their labels in this language (#192), short of the code.- let code_end = 14.0 + winui::text_width_font(&p, code_font, code);+ let code_end = 14.0 + code_w;let [copy_at, open_at] = winui::button_row(&p,&[("Copy code", 200.0, 90.0), ("Open the page", 296.0, 110.0)],@@ -3915,7 +3933,7 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingslet left = until.saturating_duration_since(std::time::Instant::now()).as_secs();- winui::paragraph(+ let lines = winui::paragraph(&p,o.x + 14.0,o.y + 120.0,@@ -3933,7 +3951,11 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingso.x + 406.0,14.0,);+ // Three lines fit above the token's label; a longer page or language grows the dialog.+ crate::dialogs::grow_px(&ctx, "opt-account", lines.saturating_sub(3) as f32 * 14.0);ctx.request_repaint_after(std::time::Duration::from_secs(1));+ } else {+ crate::dialogs::grow_px(&ctx, "opt-account", 0.0);}let label = if by_code {// i18n: Options → Add an account: label before the field for the service's API token (the other way to sign in)@@ -3942,20 +3964,20 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settings// i18n: Options → Add an account: label before the field for the service's API key (Premiumize: the only way to sign in; the key is on the service's Account page)crate::i18n::t("Paste your API key (from the service's Account page):")};- text(&p, o.x + 14.0, o.y + 178.0, label, LIGHT_TEXT());+ text(&p, o.x + 14.0, o.y + 178.0 + extra, label, LIGHT_TEXT());// As wide as its label in this language (#192); the box ends 6 px before it.let (use_x, use_w) =winui::buttons_to_right(&p, 406.0, 0.0, &[("Use the token", 106.0)], 200.0)[0];winui::password_light(ui,- r(o, 14.0, 186.0, use_x - 6.0 - 14.0, 21.0),+ r(o, 14.0, 186.0 + extra, use_x - 6.0 - 14.0, 21.0),&mut e.token,!busy,);// i18n: button: sign in with the token typed inif winui::button_light(ui,- r(o, use_x, 186.0, use_w, 21.0),+ r(o, use_x, 186.0 + extra, use_w, 21.0),"Use the token",kind(!busy && !e.token.trim().is_empty()),false,@@ -3970,7 +3992,7 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingsr(o,14.0,- 212.0,+ 212.0 + extra,winui::button_fit_width(&p, "Find my token", 160.0, 392.0),21.0,),@@ -4004,7 +4026,7 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingslet (rect, cut) = winui::label_into(&p,o.x + 14.0,- o.y + 252.0,+ o.y + 252.0 + extra,&line,color,o.x + 406.0,@@ -4014,7 +4036,7 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingswinui::full_on_hover(ui, rect, "opt-account-state", &line);}let done = matches!(state, S::Done { .. });- match ok_cancel(ui, o, 252.0, 266.0, done) {+ match ok_cancel(ui, o, 252.0, 266.0 + extra, done) {Outcome::Done(()) => match state {S::Done {user,diff --git a/crates/app/src/torrents.rs b/crates/app/src/torrents.rsindex ff284fed..793d2f7e 100644--- a/crates/app/src/torrents.rs+++ b/crates/app/src/torrents.rs@@ -890,6 +890,7 @@ impl Run {events: Vec::new(),// A torrent has peers, not one server (#140).server: None,+ at_service: None,};if *self.stopped.lock().unwrap() {s.state = State::Cancelled;diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rsindex 0717e7f9..7b5a98de 100644--- a/crates/cli/src/lib.rs+++ b/crates/cli/src/lib.rs@@ -1314,7 +1314,7 @@ mod tests {fn unlock<'a>(&'a self,_: &'a url::Url,- _: &'a (dyn Fn(String) + Send + Sync),+ _: &'a (dyn Fn(String, Option<f32>) + Send + Sync),_: &'a tokio_util::sync::CancellationToken,) -> std::pin::Pin<Box<diff --git a/crates/debrid/Cargo.toml b/crates/debrid/Cargo.tomlindex 6fb73bb9..33a409a6 100644--- a/crates/debrid/Cargo.toml+++ b/crates/debrid/Cargo.toml@@ -10,6 +10,7 @@ publish.workspace = true[dependencies]bytes.workspace = true+chrono.workspace = truefutures.workspace = truemdm-engine.workspace = truereqwest.workspace = truediff --git a/crates/debrid/src/lib.rs b/crates/debrid/src/lib.rsindex 4ac091bd..d9fe435b 100644--- a/crates/debrid/src/lib.rs+++ b/crates/debrid/src/lib.rs@@ -8,12 +8,14 @@//! (`mdm_engine::Options::unlocker`). Secrets (tokens) are kept by the app, in the system's//! keychain; here they are only in memory, and never written to a log.//!-//! The services: Real-Debrid (`realdebrid`), AllDebrid (`alldebrid`) and Premiumize-//! (`premiumize`), each from its own public API documentation, on one interface (`ServiceKind`).+//! The services: Real-Debrid (`realdebrid`), AllDebrid (`alldebrid`), Premiumize (`premiumize`)+//! and TorBox (`torbox`), each from its own public API documentation, on one interface+//! (`ServiceKind`).pub mod alldebrid;pub mod premiumize;pub mod realdebrid;+pub mod torbox;pub mod torrents;use std::collections::HashMap;@@ -33,11 +35,14 @@ pub enum ServiceKind {RealDebrid,AllDebrid,Premiumize,+ TorBox,}impl ServiceKind {- /// Every service, in the order Options lists them.- pub const ALL: [ServiceKind; 3] = [+ /// Every service, in the order Options lists them: the most asked for first. Add an account+ /// starts on the first.+ pub const ALL: [ServiceKind; 4] = [+ ServiceKind::TorBox,ServiceKind::RealDebrid,ServiceKind::AllDebrid,ServiceKind::Premiumize,@@ -49,6 +54,7 @@ impl ServiceKind {ServiceKind::RealDebrid => "Real-Debrid",ServiceKind::AllDebrid => "AllDebrid",ServiceKind::Premiumize => "Premiumize",+ ServiceKind::TorBox => "TorBox",}}@@ -58,22 +64,28 @@ impl ServiceKind {ServiceKind::RealDebrid => "https://real-debrid.com/apitoken",ServiceKind::AllDebrid => "https://alldebrid.com/apikeys",ServiceKind::Premiumize => "https://www.premiumize.me/account",+ ServiceKind::TorBox => "https://torbox.app/settings",}}- /// Whether it signs in by code in the browser (Real-Debrid's device flow, AllDebrid's PIN).- /// Premiumize's needs a client registered by MDM's maintainer: its API key is pasted.+ /// Whether it signs in by code in the browser (Real-Debrid's device flow, AllDebrid's PIN,+ /// TorBox's device code). Premiumize's needs a client registered by MDM's maintainer: its API+ /// key is pasted.pub fn signs_in_by_code(self) -> bool {!matches!(self, ServiceKind::Premiumize)}/// The requests a minute MDM allows itself (each service's published limit, halved or more:- /// Real-Debrid 250 a minute, AllDebrid 600; Premiumize publishes none).+ /// Real-Debrid 250 a minute, AllDebrid 600; Premiumize publishes none). TorBox: 300 a minute+ /// for each endpoint, per API key, and 60 new web downloads (or uncached torrents) an hour+ /// (https://support.torbox.app/en/articles/13726368-api-rate-limits); a refused request+ /// pauses it as any "too many requests" does.fn per_minute(self) -> usize {match self {ServiceKind::RealDebrid => 120,ServiceKind::AllDebrid => 300,ServiceKind::Premiumize => 60,+ ServiceKind::TorBox => 120,}}}@@ -84,6 +96,7 @@ pub struct Services {pub rd: realdebrid::Endpoints,pub ad: Url,pub pm: Url,+ pub tb: Url,}impl Default for Services {@@ -92,6 +105,7 @@ impl Default for Services {rd: realdebrid::Endpoints::default(),ad: Url::parse(alldebrid::BASE).expect("constant"),pm: Url::parse(premiumize::BASE).expect("constant"),+ tb: Url::parse(torbox::BASE).expect("constant"),}}}@@ -103,6 +117,7 @@ impl Services {rd: realdebrid::Endpoints::at(base),ad: base.join("ad/").expect("relative"),pm: base.join("pm/api/").expect("relative"),+ tb: base.join("tb/v1/api/").expect("relative"),}}}@@ -266,6 +281,14 @@ impl Http {Err(f)}+ fn post_json(&self, url: &Url, body: &serde_json::Value) -> reqwest::RequestBuilder {+ self.client+ .post(url.clone())+ .header(reqwest::header::USER_AGENT, USER_AGENT)+ .header(reqwest::header::CONTENT_TYPE, "application/json")+ .body(body.to_string())+ }+fn post_form(&self, url: &Url, form: &[(&str, &str)]) -> reqwest::RequestBuilder {let body = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(form)@@ -387,7 +410,7 @@ impl Session {async fn unlock(&self,link: &Url,- note: &(dyn Fn(String) + Send + Sync),+ note: &(dyn Fn(String, Option<f32>) + Send + Sync),cancel: &CancellationToken,) -> Result<Option<Unlocked>, Fault> {let not_a_file = || {@@ -421,10 +444,13 @@ impl Session {if Instant::now() >= until {return Err(Fault::Service(ServiceFault::ServiceDown));}- note(format!(- "AllDebrid is preparing the link (about {} s)",- d.time_left.max(0)- ));+ note(+ format!(+ "AllDebrid is preparing the link (about {} s)",+ d.time_left.max(0)+ ),+ None,+ );let wait = Duration::from_secs((d.time_left.max(0) as u64 / 4).max(5));tokio::select! {_ = tokio::time::sleep(wait) => {}@@ -462,6 +488,64 @@ impl Session {max_connections: None,}))}+ ServiceKind::TorBox => {+ use torbox::Kind;+ let key = self.token(false).await?;+ let id = match torbox::create(&self.http, &key, Kind::Web, "link", link.as_str())+ .await+ {+ Ok(id) => id,+ Err(Fault::Unsupported) => return Ok(None),+ Err(e) => return Err(e),+ };+ // TorBox fetches the file to its servers first (at once when it has it already):+ // asked every 5 s, up to an hour, said in the event log, stopped with the download.+ let until = Instant::now() + Duration::from_secs(3600);+ let mut said = String::new();+ let item = loop {+ let i = torbox::item(&self.http, &key, Kind::Web, id).await?;+ match torbox::state(&i) {+ None => break i,+ Some(torrents::Status::Failed(f)) => return Err(Fault::Service(f)),+ Some(torrents::Status::Working { progress, what }) => {+ let line = format!(+ "TorBox is fetching the file: {what}, {}%",+ (progress.unwrap_or(0.0) * 100.0) as u32 / 10 * 10+ );+ if line != said {+ note(line.clone(), progress);+ said = line;+ }+ }+ Some(torrents::Status::Ready { .. }) => unreachable!("state() never says"),+ }+ if Instant::now() >= until {+ return Err(Fault::Service(ServiceFault::ServiceDown));+ }+ tokio::select! {+ _ = tokio::time::sleep(Duration::from_secs(5)) => {}+ _ = cancel.cancelled() => {+ return Err(Fault::Service(ServiceFault::Other("cancelled".into())));+ }+ }+ };+ // One file per host link; several are a folder (as Premiumize: not a file).+ let [file] = item.files.as_slice() else {+ return Err(not_a_file());+ };+ let url = torbox::link(&self.http, &key, Kind::Web, id, file.id).await?;+ let name = if file.short_name.trim().is_empty() {+ file.name.rsplit('/').next().unwrap_or("").to_owned()+ } else {+ file.short_name.clone()+ };+ Ok(Some(Unlocked {+ url,+ file_name: Some(name).filter(|n| !n.trim().is_empty()),+ size: (file.size > 0).then_some(file.size),+ max_connections: None,+ }))+ }ServiceKind::RealDebrid => {let u = match self.with_token(@@ -582,6 +666,7 @@ impl Debrid {Ok(t) => premiumize::domains(&s.http, &t).await,Err(e) => Err(e),},+ ServiceKind::TorBox => torbox::domains(&s.http).await,};match list {Ok(list) => {@@ -632,6 +717,19 @@ impl Debrid {Some(Arc::new(AccountUnlocker { session }))}+ /// A download of `url` through an account ended (done, or taken off MDM's list): on TorBox,+ /// its web downloads leave the account's list, as a torrent does once downloaded. The other+ /// services keep no list of unlocked links.+ pub async fn release(&self, url: &Url) -> Result<(), Fault> {+ let Some((id, ServiceKind::TorBox)) = self.account_for(url) else {+ return Ok(());+ };+ let Some(s) = self.session(id) else {+ return Ok(());+ };+ torbox::release(&s.http, &s.token(false).await?, url).await+ }+/// Ask the service about account `id` (Options, after signing in).pub async fn account_info(&self, id: u64) -> Result<AccountInfo, Fault> {let s = self@@ -681,6 +779,22 @@ async fn account_info(s: &Session) -> Result<AccountInfo, Fault> {},})}+ ServiceKind::TorBox => {+ let u = torbox::user(&s.http, &s.token(false).await?).await?;+ let left = u+ .premium_expires_at+ .as_deref()+ .and_then(torbox::unix_of)+ .map(|t| t - now_unix())+ .filter(|l| *l > 0);+ Ok(AccountInfo {+ // Plan 0 is the free one.+ premium: u.plan > 0 && left.is_some(),+ premium_left: left.map(|l| Duration::from_secs(l as u64)),+ // TorBox gives no user name: the account's email stands for it.+ user: u.email,+ })+ }}}@@ -736,7 +850,7 @@ impl mdm_engine::Unlocker for AccountUnlocker {fn unlock<'a>(&'a self,url: &'a Url,- note: &'a (dyn Fn(String) + Send + Sync),+ note: &'a (dyn Fn(String, Option<f32>) + Send + Sync),cancel: &'a CancellationToken,) -> BoxFuture<'a, Result<Option<Unlocked>, ServiceFault>> {Box::pin(async move {@@ -748,8 +862,8 @@ impl mdm_engine::Unlocker for AccountUnlocker {}}-/// Sign-in by code: Real-Debrid's device flow, AllDebrid's PIN. The code to show and the page to-/// type it at, then a poll until the user allowed MDM there.+/// Sign-in by code: Real-Debrid's device flow, AllDebrid's PIN, TorBox's device code. The code to+/// show and the page to type it at, then a poll until the user allowed MDM there.pub mod signin {use super::*;@@ -770,6 +884,7 @@ pub mod signin {enum Inner {Rd(realdebrid::DeviceCode),Ad(alldebrid::Pin),+ Tb(torbox::DeviceCode),}/// Step 1: a code from `service` (one that signs in by code).@@ -798,6 +913,24 @@ pub mod signin {inner: Inner::Ad(p),})}+ ServiceKind::TorBox => {+ let c = torbox::device_start(http).await?;+ let left = c+ .expires_at+ .as_deref()+ .and_then(torbox::unix_of)+ .map(|t| t - now_unix())+ .filter(|l| *l > 0);+ own_page(service, &c.verification_url)?;+ Ok(Code {+ shown: c.code.clone(),+ page: c.verification_url.clone(),+ // The docs: ask every `interval` seconds; 5 or more, as the others.+ interval: c.interval.max(5),+ expires_in: left.map_or(600, |l| l as u64),+ inner: Inner::Tb(c),+ })+ }ServiceKind::Premiumize => Err(Fault::Service(ServiceFault::Other("Premiumize signs in with its API key".into(),))),@@ -812,6 +945,7 @@ pub mod signin {ServiceKind::RealDebrid => "real-debrid.com",ServiceKind::AllDebrid => "alldebrid.com",ServiceKind::Premiumize => "premiumize.me",+ ServiceKind::TorBox => "torbox.app",};let ok = url::Url::parse(page).is_ok_and(|u| {u.scheme() == "https"@@ -846,6 +980,9 @@ pub mod signin {Inner::Ad(p) => Ok(alldebrid::pin_check(http, p).await?.map(|token| Credential::Token { token })),+ Inner::Tb(c) => Ok(torbox::device_token(http, &c.device_code)+ .await?+ .map(|token| Credential::Token { token })),}}@@ -875,6 +1012,15 @@ pub mod signin {assert!(own_page(rd, bad).is_err(), "{bad}");}assert!(own_page(ad, "https://real-debrid.com/device").is_err());+ let tb = ServiceKind::TorBox;+ assert!(+ own_page(+ tb,+ "https://torbox.app/oauth/device?app=MisterDownloadManager"+ )+ .is_ok()+ );+ assert!(own_page(tb, "https://real-debrid.com/device").is_err());}}}diff --git a/crates/debrid/src/torbox.rs b/crates/debrid/src/torbox.rsnew file mode 100644index 00000000..6859462c--- /dev/null+++ b/crates/debrid/src/torbox.rs@@ -0,0 +1,470 @@+//! TorBox's API, as documented at <https://api-docs.torbox.app/> and+//! <https://api.torbox.app/openapi.json> (read 2026-11-10). Only what MDM uses: the account, the+//! hosters list, and two kinds of its downloads (web downloads for file-host links, and+//! torrents), which go the same way: created, fetched on TorBox's servers (`mylist` until+//! finished), then each file's link asked (`requestdl`).+//!+//! - Every call carries `Authorization: Bearer <API key>`, except `requestdl`, whose documented+//! sign-in is the `token` query parameter: MDM never logs or shows that address, and asks it+//! with `redirect=false` so the API key never reaches the download's own address.+//! - Every answer is `{"success", "error", "detail", "data"}`; `error` is a code+//! (`BAD_TOKEN`, `UNSUPPORTED_SITE`...). Note `ITEM_NOT_FOUND` comes with `success: true`.+//! - Sign-in by code (`user/auth/device/start`, then `user/auth/device/token` until allowed): the+//! user types the code at TorBox's page (its short address is `tor.box/link`), and MDM gets the+//! account's API key. Or the key is pasted from the account's settings page.++use serde::Deserialize;+use serde_json::Value;+use url::Url;++use crate::torrents::{RemoteFile, Status};+use crate::{Fault, Http, ServiceKind};++/// Where TorBox answers (tests: the lab server's `/tb/v1/api/`).+pub const BASE: &str = "https://api.torbox.app/v1/api/";++/// TorBox's kinds of downloads MDM uses: the same calls under their own path and id names.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Kind {+ Web,+ Torrent,+}++impl Kind {+ fn path(self) -> &'static str {+ match self {+ Kind::Web => "webdl",+ Kind::Torrent => "torrents",+ }+ }+ fn create(self) -> &'static str {+ match self {+ Kind::Web => "webdl/createwebdownload",+ Kind::Torrent => "torrents/createtorrent",+ }+ }+ /// The created download's id in `create`'s answer.+ fn created_id(self) -> &'static str {+ match self {+ Kind::Web => "webdownload_id",+ Kind::Torrent => "torrent_id",+ }+ }+ /// The id's name for `control…` (JSON) and for `requestdl` (query).+ fn control(self) -> (&'static str, &'static str) {+ match self {+ Kind::Web => ("webdl/controlwebdownload", "webdl_id"),+ Kind::Torrent => ("torrents/controltorrent", "torrent_id"),+ }+ }+ fn request_id(self) -> &'static str {+ match self {+ Kind::Web => "web_id",+ Kind::Torrent => "torrent_id",+ }+ }+}++#[derive(Debug, Deserialize)]+struct Envelope {+ #[serde(default)]+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ detail: String,+ #[serde(default)]+ data: Value,+}++/// What an error code means for MDM (the codes the documentation's examples show).+pub(crate) fn fault_of(code: &str, detail: &str) -> Fault {+ use mdm_engine::ServiceFault as F;+ Fault::Service(match code {+ "NO_AUTH" | "BAD_TOKEN" | "AUTH_ERROR" => F::SignIn,+ "UNSUPPORTED_SITE" => return Fault::Unsupported,+ "TEMPORARILY_DISABLED" => F::HostDown,+ "PLAN_RESTRICTED_FEATURE" => F::NotPremium,+ "ACTIVE_LIMIT" => F::TooManyActive,+ "MONTHLY_LIMIT" | "COOLDOWN_LIMIT" | "DOWNLOAD_TOO_LARGE" => F::LimitReached,+ "ITEM_NOT_FOUND" | "LINK_OFFLINE" | "INVALID_LINK" => F::FileUnavailable,+ "BOZO_TORRENT" | "INVALID_HASH" => F::TorrentUnavailable,+ "DATABASE_ERROR" | "UNKNOWN_ERROR" | "DOWNLOAD_SERVER_ERROR" => F::ServiceDown,+ _ if !detail.is_empty() => F::Other(detail.to_owned()),+ _ => F::Other(code.to_owned()),+ })+}++/// An answer's `data`, or its error.+fn read(status: u16, body: &[u8], retry: Option<u64>) -> Result<Value, Fault> {+ use mdm_engine::ServiceFault as F;+ if status == 429 {+ return Err(Fault::Service(F::TooManyRequests(+ retry.map(std::time::Duration::from_secs),+ )));+ }+ let Ok(e) = serde_json::from_slice::<Envelope>(body) else {+ return Err(Fault::Service(if status >= 500 {+ F::ServiceDown+ } else {+ F::Other("an answer MDM can't read".into())+ }));+ };+ match e.error.filter(|c| !c.is_empty()) {+ Some(code) => Err(fault_of(&code, &e.detail)),+ None if !e.success => Err(Fault::Service(F::Other(e.detail))),+ None => Ok(e.data),+ }+}++fn data<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, Fault> {+ serde_json::from_value(v).map_err(|_| {+ Fault::Service(mdm_engine::ServiceFault::Other(+ "an answer MDM can't read".into(),+ ))+ })+}++async fn call(http: &Http, req: reqwest::RequestBuilder) -> Result<Value, Fault> {+ let (status, body, retry) = http.send(ServiceKind::TorBox, req).await?;+ read(status, &body, retry)+}++fn url(http: &Http, path: &str) -> Url {+ http.services.tb.join(path).expect("relative")+}++/// `GET user/me`.+#[derive(Debug, Deserialize)]+pub(crate) struct User {+ #[serde(default)]+ pub email: String,+ /// 0 is the free plan.+ #[serde(default)]+ pub plan: i64,+ /// RFC 3339.+ pub premium_expires_at: Option<String>,+}++pub(crate) async fn user(http: &Http, key: &str) -> Result<User, Fault> {+ data(call(http, http.get(&url(http, "user/me")).bearer_auth(key)).await?)+}++/// `GET user/auth/device/start?app=` (no sign-in): the code to show and where.+#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]+pub struct DeviceCode {+ pub device_code: String,+ /// What the user types (6 digits).+ pub code: String,+ /// The page that shows the app's name (on torbox.app; `tor.box/link`, TorBox's short+ /// address for it, is another domain and isn't opened).+ #[serde(default)]+ pub verification_url: String,+ #[serde(default)]+ pub interval: u64,+ /// RFC 3339 (the docs: 10 minutes).+ pub expires_at: Option<String>,+}++pub(crate) async fn device_start(http: &Http) -> Result<DeviceCode, Fault> {+ let mut u = url(http, "user/auth/device/start");+ // Letters and digits only, as the docs ask: shown on TorBox's page.+ u.query_pairs_mut()+ .append_pair("app", "MisterDownloadManager");+ data(call(http, http.get(&u)).await?)+}++/// `POST user/auth/device/token`: the API key once the user allowed MDM, None while not yet+/// (`DEVICE_CODE_NOT_USED`).+pub(crate) async fn device_token(http: &Http, device_code: &str) -> Result<Option<String>, Fault> {+ #[derive(Deserialize)]+ struct Token {+ access_token: String,+ }+ let req = http.post_json(+ &url(http, "user/auth/device/token"),+ &serde_json::json!({ "device_code": device_code }),+ );+ let (status, body, retry) = http.send(ServiceKind::TorBox, req).await?;+ let code = serde_json::from_slice::<Envelope>(&body)+ .ok()+ .and_then(|e| e.error);+ match code.as_deref() {+ Some("DEVICE_CODE_NOT_USED") => Ok(None),+ Some("ITEM_NOT_FOUND") => Err(Fault::Service(mdm_engine::ServiceFault::Other(+ "the code expired: sign in again".into(),+ ))),+ _ => data::<Token>(read(status, &body, retry)?).map(|t| Some(t.access_token)),+ }+}++/// Seconds since 1970 of an RFC 3339 time, as TorBox writes them.+pub(crate) fn unix_of(t: &str) -> Option<i64> {+ chrono::DateTime::parse_from_rfc3339(t)+ .ok()+ .map(|d| d.timestamp())+}++#[derive(Debug, Deserialize)]+struct Hoster {+ #[serde(default)]+ domains: Vec<String>,+}++/// `GET webdl/hosters` (public): every domain of every host and site TorBox takes, those it+/// marks down for now included (their links then fail with TorBox's reason, as with the others).+pub(crate) async fn domains(http: &Http) -> Result<Vec<String>, Fault> {+ let hosters: Vec<Hoster> = data(call(http, http.get(&url(http, "webdl/hosters"))).await?)?;+ Ok(hosters.into_iter().flat_map(|h| h.domains).collect())+}++/// `POST <kind>/create…` with `field` (`link`, `magnet`): its id at TorBox.+pub(crate) async fn create(+ http: &Http,+ key: &str,+ kind: Kind,+ field: &str,+ value: &str,+) -> Result<u64, Fault> {+ let d = call(+ http,+ http.post_form(&url(http, kind.create()), &[(field, value)])+ .bearer_auth(key),+ )+ .await?;+ d.get(kind.created_id())+ .and_then(Value::as_u64)+ .ok_or(Fault::Service(mdm_engine::ServiceFault::ServiceDown))+}++/// A `mylist` entry: the same for both kinds.+#[derive(Debug, Deserialize)]+pub(crate) struct Item {+ #[serde(default)]+ pub id: u64,+ #[serde(default)]+ pub name: String,+ /// The link it was made from (a web download's file-host link).+ #[serde(default)]+ pub original_url: String,+ #[serde(default)]+ pub download_state: String,+ /// 0 to 1.+ #[serde(default)]+ pub progress: f64,+ #[serde(default)]+ pub download_finished: bool,+ #[serde(default)]+ pub download_present: bool,+ #[serde(default)]+ pub error: Option<String>,+ #[serde(default)]+ pub files: Vec<File>,+}++#[derive(Debug, Deserialize)]+pub(crate) struct File {+ pub id: u64,+ /// Its path in the download, `/`-separated.+ #[serde(default)]+ pub name: String,+ #[serde(default)]+ pub short_name: String,+ #[serde(default)]+ pub size: u64,+}++/// `GET <kind>/mylist?id=` (fresh, not TorBox's cached list).+pub(crate) async fn item(http: &Http, key: &str, kind: Kind, id: u64) -> Result<Item, Fault> {+ let mut u = url(http, &format!("{}/mylist", kind.path()));+ u.query_pairs_mut()+ .append_pair("id", &id.to_string())+ .append_pair("bypass_cache", "true");+ let d = call(http, http.get(&u).bearer_auth(key)).await?;+ // One item for an id; a list of one when TorBox answers with its list form.+ match d {+ Value::Array(mut a) if !a.is_empty() => data(a.swap_remove(0)),+ Value::Object(_) => data(d),+ _ => Err(Fault::Service(mdm_engine::ServiceFault::FileUnavailable)),+ }+}++/// A download of `link` ended (done, or taken off MDM's list): its web downloads leave the+/// account's TorBox list, as a torrent does once downloaded. Found by the link they were made+/// from, so those made before a restart, or by a refreshed link, go too.+pub(crate) async fn release(http: &Http, key: &str, link: &Url) -> Result<(), Fault> {+ // shortcut: only the first 1000 entries (TorBox's default limit), page through them if+ // accounts hold more.+ let mut u = url(http, "webdl/mylist");+ u.query_pairs_mut().append_pair("bypass_cache", "true");+ let list: Vec<Item> = match call(http, http.get(&u).bearer_auth(key)).await {+ Ok(d) => data(d)?,+ // An empty list: nothing to remove.+ Err(Fault::Service(mdm_engine::ServiceFault::FileUnavailable)) => return Ok(()),+ Err(e) => return Err(e),+ };+ for i in list {+ if Url::parse(&i.original_url).is_ok_and(|o| o == *link) {+ delete(http, key, Kind::Web, i.id).await?;+ }+ }+ Ok(())+}++/// How TorBox is doing with `i`: still at it, failed, or finished (its files, not yet linked).+pub(crate) fn state(i: &Item) -> Option<Status> {+ let what = i.download_state.to_lowercase();+ if let Some(e) = i.error.as_deref().filter(|e| !e.trim().is_empty()) {+ return Some(Status::Failed(mdm_engine::ServiceFault::Other(+ e.to_owned(),+ )));+ }+ if what.contains("fail") || what == "error" {+ return Some(Status::Failed(mdm_engine::ServiceFault::Other(+ i.download_state.clone(),+ )));+ }+ if i.download_finished && i.download_present {+ return None;+ }+ Some(Status::Working {+ progress: Some(i.progress.clamp(0.0, 1.0) as f32),+ what: if what.is_empty() {+ "queued".into()+ } else {+ what+ },+ })+}++/// `GET <kind>/requestdl`: a file's direct link (good for 3 hours to start).+pub(crate) async fn link(+ http: &Http,+ key: &str,+ kind: Kind,+ id: u64,+ file: u64,+) -> Result<Url, Fault> {+ let mut u = url(http, &format!("{}/requestdl", kind.path()));+ u.query_pairs_mut()+ .append_pair("token", key)+ .append_pair(kind.request_id(), &id.to_string())+ .append_pair("file_id", &file.to_string())+ .append_pair("redirect", "false");+ let d = call(http, http.get(&u)).await?;+ d.as_str().and_then(|l| Url::parse(l).ok()).ok_or_else(|| {+ Fault::Service(mdm_engine::ServiceFault::Other(+ "the service gave a link MDM can't read".into(),+ ))+ })+}++/// A finished download's files, each with its direct link.+pub(crate) async fn files(+ http: &Http,+ key: &str,+ kind: Kind,+ id: u64,+ i: &Item,+) -> Result<Vec<RemoteFile>, Fault> {+ let mut out = Vec::with_capacity(i.files.len());+ for f in &i.files {+ out.push(RemoteFile {+ path: f.name.clone(),+ size: f.size,+ link: link(http, key, kind, id, f.id).await?.into(),+ });+ }+ Ok(out)+}++/// `POST <kind>/control…` `delete`: gone from the account's list.+pub(crate) async fn delete(http: &Http, key: &str, kind: Kind, id: u64) -> Result<(), Fault> {+ let (path, name) = kind.control();+ call(+ http,+ http.post_json(+ &url(http, path),+ &serde_json::json!({ name: id, "operation": "delete" }),+ )+ .bearer_auth(key),+ )+ .await+ .map(|_| ())+}++/// A torrent's id as the app keeps it (`Order::transfer`): its number.+pub(crate) fn torrent_id(t: &str) -> Result<u64, Fault> {+ t.parse().map_err(|_| {+ Fault::Service(mdm_engine::ServiceFault::Other(+ "the service gave an id MDM can't use".into(),+ ))+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use mdm_engine::ServiceFault as F;++ #[test]+ fn the_documented_answers_read() {+ let ok = br#"{"success":true,"error":null,"detail":"ok","data":{"hash":"h","webdownload_id":42,"auth_id":"a"}}"#;+ assert_eq!(read(200, ok, None).unwrap()["webdownload_id"], 42);+ let bad = br#"{"success":false,"error":"BAD_TOKEN","detail":"Your token is invalid","data":null}"#;+ assert_eq!(read(403, bad, None).unwrap_err(), Fault::Service(F::SignIn));+ let un =+ br#"{"success":false,"error":"UNSUPPORTED_SITE","detail":"not supported","data":null}"#;+ assert_eq!(read(400, un, None).unwrap_err(), Fault::Unsupported);+ // Documented with success: true, still an error.+ let none =+ br#"{"success":true,"error":"ITEM_NOT_FOUND","detail":"No web downloads","data":null}"#;+ assert_eq!(+ read(404, none, None).unwrap_err(),+ Fault::Service(F::FileUnavailable)+ );+ assert_eq!(+ fault_of("NEW_CODE", "Its words"),+ Fault::Service(F::Other("Its words".into()))+ );+ let h: Vec<Hoster> = serde_json::from_str(+ r#"[{"id":1,"name":"Rapidgator","domains":["rapidgator.net","rg.to"],"status":false,"type":"hoster"}]"#,+ )+ .unwrap();+ assert_eq!(h[0].domains, ["rapidgator.net", "rg.to"]);+ assert_eq!(unix_of("2051-02-18T04:08:43Z"), Some(2560306123));+ }++ #[test]+ fn list_states_mean_what_they_say() {+ let i = |state: &str, done: bool, error: Option<&str>| Item {+ id: 1,+ name: "x".into(),+ original_url: String::new(),+ download_state: state.into(),+ progress: 0.25,+ download_finished: done,+ download_present: done,+ error: error.map(Into::into),+ files: vec![],+ };+ assert_eq!(+ state(&i("downloading", false, None)),+ Some(Status::Working {+ progress: Some(0.25),+ what: "downloading".into()+ })+ );+ assert_eq!(state(&i("completed", true, None)), None);+ assert!(matches!(+ state(&i("failed (link dead)", false, None)),+ Some(Status::Failed(_))+ ));+ assert!(matches!(+ state(&i("downloading", false, Some("Host error"))),+ Some(Status::Failed(F::Other(_)))+ ));+ assert_eq!(torrent_id("12").unwrap(), 12);+ assert!(torrent_id("x/../1").is_err());+ }+}diff --git a/crates/debrid/src/torrents.rs b/crates/debrid/src/torrents.rsindex 2f30f798..9a63bc08 100644--- a/crates/debrid/src/torrents.rs+++ b/crates/debrid/src/torrents.rs@@ -13,6 +13,8 @@//! - Premiumize: `transfer/create` (`src`), `transfer/list`, `folder/list` (walked) or//! `item/details` for a single file, `transfer/delete`; its files' links are direct links to//! the user's own cloud.+//! - TorBox: `torrents/createtorrent` (`magnet`), `torrents/mylist?id=`, `torrents/requestdl` for+//! each file (a direct link), `torrents/controltorrent` (`delete`).use std::path::{Component, Path, PathBuf};use std::sync::{Arc, Mutex};@@ -24,7 +26,7 @@ use serde::Deserialize;use tokio_util::sync::CancellationToken;use url::Url;-use crate::{Debrid, Fault, ServiceKind, Session, alldebrid, premiumize, realdebrid};+use crate::{Debrid, Fault, ServiceKind, Session, alldebrid, premiumize, realdebrid, torbox};/// How the service is doing with a torrent.#[derive(Clone, Debug, PartialEq)]@@ -70,6 +72,12 @@ impl Session {ServiceKind::Premiumize => {premiumize::create(&self.http, &self.token(false).await?, magnet).await}+ ServiceKind::TorBox => {+ let key = self.token(false).await?;+ let id = torbox::create(&self.http, &key, torbox::Kind::Torrent, "magnet", magnet)+ .await?;+ Ok(id.to_string())+ }}}@@ -87,6 +95,18 @@ impl Session {ServiceKind::Premiumize => {premiumize::transfer_status(&self.http, &self.token(false).await?, id).await}+ ServiceKind::TorBox => {+ let (kind, n) = (torbox::Kind::Torrent, torbox::torrent_id(id)?);+ let key = self.token(false).await?;+ let i = torbox::item(&self.http, &key, kind, n).await?;+ match torbox::state(&i) {+ Some(s) => Ok(s),+ None => Ok(Status::Ready {+ files: torbox::files(&self.http, &key, kind, n, &i).await?,+ name: i.name,+ }),+ }+ }}}@@ -104,6 +124,16 @@ impl Session {ServiceKind::Premiumize => {premiumize::transfer_delete(&self.http, &self.token(false).await?, id).await}+ ServiceKind::TorBox => {+ let n = torbox::torrent_id(id)?;+ torbox::delete(+ &self.http,+ &self.token(false).await?,+ torbox::Kind::Torrent,+ n,+ )+ .await+ }}}}@@ -118,7 +148,7 @@ impl Debrid {.map(|s| (s.account.id, s.account.service))}- fn session(&self, id: u64) -> Option<Arc<Session>> {+ pub(crate) fn session(&self, id: u64) -> Option<Arc<Session>> {self.sessions.read().unwrap()@@ -301,9 +331,9 @@ impl RemoteTorrent {let total: u64 = files.iter().map(|f| f.size).sum();self.shared.lock().unwrap().total = (total > 0).then_some(total);// Real-Debrid's and AllDebrid's links are their hoster links: unlocked through the- // account, as any. Premiumize's are direct.+ // account, as any. Premiumize's and TorBox's are direct.let unlocker = match s.account.service {- ServiceKind::Premiumize => None,+ ServiceKind::Premiumize | ServiceKind::TorBox => None,_ => Some(Arc::new(crate::AccountUnlocker { session: s.clone() })as Arc<dyn mdm_engine::Unlocker>),};@@ -318,6 +348,11 @@ impl RemoteTorrent {};let within = |path: &str| {let t = path.trim_start_matches(['/', '\\']);+ // The one file by its name, whatever folder the service keeps it in (TorBox's+ // `<torrent>/<file>`).+ if files.len() == 1 {+ return t.rsplit(['/', '\\']).next().unwrap_or(t).to_owned();+ }match t.split_once(['/', '\\']) {Some((first, rest)) if files.len() > 1 && first.trim() == name.trim() => {rest.to_owned()@@ -468,6 +503,8 @@ impl RemoteTorrent {(State::Probing, Some(_)) => State::Downloading,(s, _) => s,};+ // A file whose link the service prepares (AllDebrid's delayed links).+ let at_service = cur.as_ref().and_then(|c| c.at_service.clone());let (connections, server, running) = match cur {Some(c) => (c.connections,@@ -516,6 +553,7 @@ impl RemoteTorrent {}),events,server,+ at_service,}}}diff --git a/crates/debrid/tests/alldebrid_real.rs b/crates/debrid/tests/alldebrid_real.rsindex ca1b5d3e..4c65ed11 100644--- a/crates/debrid/tests/alldebrid_real.rs+++ b/crates/debrid/tests/alldebrid_real.rs@@ -52,7 +52,7 @@ async fn the_real_service_answers_the_demo_key() {let got = u.unlock(&link,- &|n| eprintln!("note: {n}"),+ &|n, _| eprintln!("note: {n}"),&CancellationToken::new(),).await;diff --git a/crates/debrid/tests/services.rs b/crates/debrid/tests/services.rsindex 88bda101..caa60e55 100644--- a/crates/debrid/tests/services.rs+++ b/crates/debrid/tests/services.rs@@ -205,6 +205,114 @@ async fn premiumize_links_come_through_the_account() {assert!(signin::start(&http, ServiceKind::Premiumize).await.is_err());}+#[tokio::test]+async fn torbox_links_come_through_the_account_once_it_has_the_file() {+ let (lab, http) = lab().await;+ let key = |t: &str| Credential::Token { token: t.into() };+ let info = check(&http, ServiceKind::TorBox, key("good"))+ .await+ .unwrap();+ assert_eq!(+ (info.user.as_str(), info.premium),+ ("[email protected]", true)+ );+ assert!(info.premium_left.is_some());+ let free = check(&http, ServiceKind::TorBox, key("free"))+ .await+ .unwrap();+ assert!(!free.premium);+ assert!(matches!(+ check(&http, ServiceKind::TorBox, key("bad")).await,+ Err(mdm_debrid::Fault::Service(ServiceFault::SignIn))+ ));+ // Or by its device code: the code shown, TorBox's page, then the key once allowed there.+ let code = signin::start(&http, ServiceKind::TorBox).await.unwrap();+ assert_eq!(code.shown, "123456");+ assert!(code.page.contains("torbox.app"), "{}", code.page);+ let credential = loop {+ if let Some(c) = signin::poll(&http, &code).await.unwrap() {+ break c;+ }+ };+ let info = check(&http, ServiceKind::TorBox, credential).await.unwrap();+ assert!(info.premium);++ let d = account(&http, ServiceKind::TorBox, "good").await;+ // Its hosters list: the fake's two domains, nothing else.+ assert!(+ d.account_for(&"http://hoster2.test/x".parse().unwrap())+ .is_some()+ );+ assert!(+ d.account_for(&"http://elsewhere.test/x".parse().unwrap())+ .is_none()+ );+ // Fetched at TorBox first (two polls), the download saying how far TorBox is meanwhile (the+ // list's "50% at TorBox"), then its direct link; the key never in an address the engine+ // downloads.+ let url: Url = "http://hoster.test/file/2M/b.bin".parse().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let dl = Download::start(+ Request {+ url: url.clone(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ Options {+ unlocker: d.unlocker_for(&url),+ ..Options::default()+ },+ );+ let mut seen = None;+ for _ in 0..300 {+ seen = seen.or(dl.snapshot().at_service);+ tokio::time::sleep(Duration::from_millis(50)).await;+ if dl.snapshot().state == mdm_engine::download::State::Done {+ break;+ }+ }+ assert_eq!(seen, Some(("TorBox".to_owned(), Some(0.5))));+ assert_eq!(dl.snapshot().at_service, None, "cleared once the link came");+ let p = dl.wait().await.unwrap().path;+ assert!(same(&p, "/file/2M/b.bin"));+ // Done: the web download leaves the account's TorBox list (found by its link); again, a+ // no-op. Only this test makes web downloads in this binary.+ let held = || async {+ let body = reqwest::get(lab.url("/_debrid/torrents"))+ .await+ .unwrap()+ .bytes()+ .await+ .unwrap();+ serde_json::from_slice::<Vec<String>>(&body).unwrap()+ };+ let before = held().await;+ d.release(&url).await.unwrap();+ let after = held().await;+ assert!(after.len() < before.len(), "{before:?} → {after:?}");+ d.release(&url).await.unwrap();+ assert_eq!(held().await, after);+ let log = lab.log();+ assert!(+ log.iter()+ .filter(|e| e.path.starts_with("/gen/"))+ .all(|e| e.authorization.is_none()+ && !e.query.as_deref().unwrap_or("").contains("token"))+ );+ let (svc, f) = fault(+ download(&d, "http://hoster.test/file/1M/g.bin?gone=1")+ .await+ .unwrap_err(),+ );+ assert_eq!((svc.as_str(), f), ("TorBox", ServiceFault::FileUnavailable));+ let (_, f) = fault(+ download(&d, "http://hoster.test/file/1M/d.bin?down=1")+ .await+ .unwrap_err(),+ );+ assert_eq!(f, ServiceFault::HostDown);+}+#[tokio::test]async fn accounts_are_asked_in_their_order() {let (_lab, http) = lab().await;diff --git a/crates/debrid/tests/torrents.rs b/crates/debrid/tests/torrents.rsindex 20de9c68..f4b5e3f1 100644--- a/crates/debrid/tests/torrents.rs+++ b/crates/debrid/tests/torrents.rs@@ -118,6 +118,21 @@ async fn a_magnet_through_each_service_comes_down_as_files() {}}+#[tokio::test]+async fn a_torrent_of_one_file_goes_into_the_folder_itself() {+ // The service keeps it as `Lab Show/video.mkv`: it lands as `video.mkv`, no folder made.+ for service in ServiceKind::ALL {+ let (_lab, d) = setup(service).await;+ let dir = tempfile::tempdir().unwrap();+ let (_t, s) = run(&d, "one00001", dir.path()).await;+ assert_eq!(s.state, State::Done, "{service:?}: {:?}", s.error);+ let file = dir.path().join("video.mkv");+ assert!(same(&file, "2M", "video.mkv"), "{service:?}");+ assert_eq!(s.file.as_deref(), Some(file.as_path()), "{service:?}");+ assert!(!dir.path().join("Lab Show").exists(), "{service:?}");+ }+}+#[tokio::test]async fn a_torrent_the_service_cant_get_fails_with_its_reason() {for service in ServiceKind::ALL {diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rsindex 01722078..1e9e47f8 100644--- a/crates/engine/src/download.rs+++ b/crates/engine/src/download.rs@@ -752,6 +752,9 @@ pub struct Snapshot {/// What happened, oldest first (the last `EVENTS`): the download's event log. Never/// cookies or credentials.pub events: Vec<Event>,+ /// While a service account prepares the file's link (#44): the service, and how far it is+ /// (0 to 1) when it says. The list shows it instead of "Connecting...".+ pub at_service: Option<(String, Option<f32>)>,/// Where its server is, as its connections saw it (#140).pub server: Option<crate::Server>,}@@ -939,22 +942,36 @@ async fn unlock_origin(if opts.post.is_some() || !matches!(url.scheme(), "http" | "https") {return Ok(None);}- let note = |s: String| {+ unlock_noted(u, url, shared, cancel).await.map_err(|fault| {+ Error::Refused(Refusal::Service {+ service: u.name().to_owned(),+ fault,+ })+ })+}++/// `u`'s link for `url`, its waits told in the event log and the list's status ("40% at+/// TorBox") meanwhile, and the link it gave noted (never the link itself).+async fn unlock_noted(+ u: &Arc<dyn crate::unlock::Unlocker>,+ url: &Url,+ shared: Option<&Shared>,+ cancel: &CancellationToken,+) -> Result<Option<crate::unlock::Unlocked>, crate::unlock::ServiceFault> {+ let note = |s: String, progress: Option<f32>| {if let Some(sh) = shared {sh.event(s);+ sh.view.lock().unwrap().at_service = Some((u.name().to_owned(), progress));}};- match u.unlock(url, ¬e, cancel).await {- Ok(Some(x)) => {- note(crate::unlock::note_unlocked(u.name(), &x));- Ok(Some(x))+ let out = u.unlock(url, ¬e, cancel).await;+ if let Some(sh) = shared {+ sh.view.lock().unwrap().at_service = None;+ if let Ok(Some(x)) = &out {+ sh.event(crate::unlock::note_unlocked(u.name(), x));}- Ok(None) => Ok(None),- Err(fault) => Err(Error::Refused(Refusal::Service {- service: u.name().to_owned(),- fault,- })),}+ out}#[derive(Clone, Debug, PartialEq, Eq)]@@ -1035,6 +1052,7 @@ impl Download {failure: None,events: Vec::new(),server: None,+ at_service: None,}),seen: Default::default(),planner: Mutex::new(None),@@ -1315,6 +1333,7 @@ impl Ctx {self.size,&self.cancel,self.opts.unlocker.as_ref(),+ &self.shared,).await.filter(|(u, _)| *u != self.target.lock().unwrap().url) else {@@ -2021,6 +2040,7 @@ async fn run_resume(saved.size,&cancel,opts.unlocker.as_ref(),+ &shared,).await} else {@@ -2146,11 +2166,15 @@ async fn refresh_final_url(size: u64,cancel: &CancellationToken,unlocker: Option<&Arc<dyn crate::unlock::Unlocker>>,+ shared: &Shared,) -> Option<(Url, HeaderMap)> {// Through a service account (#44): the service gives today's direct link (the host's link// itself leads to its web page); the host's cookies and logins stay with the host.let unlocked = match unlocker.filter(|_| post.is_none()) {- Some(u) => u.unlock(origin, &|_| {}, cancel).await.ok().flatten(),+ Some(u) => unlock_noted(u, origin, Some(shared), cancel)+ .await+ .ok()+ .flatten(),None => None,};let (target, mut asked) = match &unlocked {diff --git a/crates/engine/src/unlock.rs b/crates/engine/src/unlock.rsindex ab4b9788..8cb7a4f6 100644--- a/crates/engine/src/unlock.rs+++ b/crates/engine/src/unlock.rs@@ -20,11 +20,12 @@ pub trait Unlocker: Send + Sync + std::fmt::Debug {fn name(&self) -> &str;/// Today's direct address for `url`. `Ok(None)`: not for this service after all (it doesn't- /// support the host): the engine downloads `url` itself. `note` reports waits to the event log.+ /// support the host): the engine downloads `url` itself. `note` reports waits to the event log,+ /// with how far the service is (0 to 1) when it says: the list shows it while the link waits.fn unlock<'a>(&'a self,url: &'a Url,- note: &'a (dyn Fn(String) + Send + Sync),+ note: &'a (dyn Fn(String, Option<f32>) + Send + Sync),cancel: &'a CancellationToken,) -> BoxFuture<'a, Result<Option<Unlocked>, ServiceFault>>;}diff --git a/crates/engine/tests/unlock.rs b/crates/engine/tests/unlock.rsindex 2c0d6776..439c5368 100644--- a/crates/engine/tests/unlock.rs+++ b/crates/engine/tests/unlock.rs@@ -50,12 +50,12 @@ impl Unlocker for Fake {fn unlock<'a>(&'a self,_url: &'a Url,- note: &'a (dyn Fn(String) + Send + Sync),+ note: &'a (dyn Fn(String, Option<f32>) + Send + Sync),_cancel: &'a CancellationToken,) -> BoxFuture<'a, Result<Option<Unlocked>, ServiceFault>> {Box::pin(async move {self.calls.fetch_add(1, Ordering::SeqCst);- note("Fake-Debrid is preparing the link".into());+ note("Fake-Debrid is preparing the link".into(), None);match self.answer.lock().unwrap().clone().expect("an answer") {Answer::Declined => Ok(None),Answer::Refused(f) => Err(f),@@ -179,12 +179,33 @@ async fn an_expired_direct_link_is_unlocked_again_and_the_download_completes() {max_connections: 2,..options(u.clone())};- let out = Download::start(request(dir.path(), false), opts)+ let dl = Download::start(request(dir.path(), false), opts);+ // The service's note, each time it is asked: the first link, and the refreshed one too+ // (the event log keeps the last 50 events, so they are gathered as they come).+ let mut notes = std::collections::BTreeSet::new();+ loop {+ let s = dl.snapshot();+ notes.extend(+ s.events+ .iter()+ .filter(|e| e.text == "Fake-Debrid is preparing the link")+ .map(|e| e.seq),+ );+ if matches!(+ s.state,+ mdm_engine::download::State::Done | mdm_engine::download::State::Failed+ ) {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ }+ let out = dl.wait().await.expect("unlocked again when the link expired");let data = std::fs::read(&out.path).unwrap();assert!(same(&data, 45), "content after the link changed");+ assert!(notes.len() >= 2, "the refresh is noted too: {notes:?}");assert!(u.calls.load(Ordering::SeqCst) >= 2,"{}",diff --git a/crates/labserver/src/debrid.rs b/crates/labserver/src/debrid.rsindex e283a749..172583b7 100644--- a/crates/labserver/src/debrid.rs+++ b/crates/labserver/src/debrid.rs@@ -252,7 +252,10 @@ fn bearer(headers: &HeaderMap) -> Option<bool> {/// The fake host's direct link on this lab for `link` (its size, name, address), or why not:/// "unsupported", "gone", "down".-fn direct_for(headers: &HeaderMap, link: &url::Url) -> Result<(u64, String, String), &'static str> {+pub(crate) fn direct_for(+ headers: &HeaderMap,+ link: &url::Url,+) -> Result<(u64, String, String), &'static str> {if link.host_str() != Some(HOSTER) {return Err("unsupported");}diff --git a/crates/labserver/src/debrid_torrents.rs b/crates/labserver/src/debrid_torrents.rsindex 1a92a4bc..90a77dba 100644--- a/crates/labserver/src/debrid_torrents.rs+++ b/crates/labserver/src/debrid_torrents.rs@@ -1,13 +1,13 @@-//! Fake torrents at the three fake services (#44): a magnet link sent to the account is "fetched"+//! Fake torrents at the fake services (#44): a magnet link sent to the account is "fetched"//! over a few polls, then its files are there, each a link the service hands back. Answers as each//! service's public API documentation shows them (paths, JSON shapes, status words and codes);//! nothing is copied from the services.//!//! - The torrent's name is the magnet's `dn` (else "torrent"). It holds two files://! `<name>/video.mkv` (2 MB) and `<name>/extras/notes.txt` (64 KB).-//! - Its info hash (`xt=urn:btih:…`) says how it goes: `dead…` dies at the service; `bad…` gives-//! a file whose path climbs out of the folder (`../../escape.bin`); anything else is ready-//! after two status polls.+//! - Its info hash (`xt=urn:btih:…`) says how it goes: `dead…` dies at the service; `one…` holds+//! only `<name>/video.mkv`; `bad…` gives a file whose path climbs out of the folder+//! (`../../escape.bin`); anything else is ready after two status polls.//! - Real-Debrid's and AllDebrid's file links are the fake host's (`http://hoster.test/file/…`),//! unrestricted as any link; Premiumize's are the lab's own direct links (`/gen/…`).//! - `GET /_debrid/torrents` lists what the accounts still hold (a test checks the cleanup).@@ -44,6 +44,10 @@ fn files(t: &Torrent) -> Vec<(String, &'static str, u64)> {(format!("{}/video.mkv", t.name), "2M", 2 << 20),(format!("{}/extras/notes.txt", t.name), "64K", 64 << 10),];+ if t.hash.starts_with("one") {+ // A torrent of one file, kept in a folder of its name (as TorBox keeps them).+ v.truncate(1);+ }if t.hash.starts_with("bad") {v.push(("../../escape.bin".to_owned(), "1K", 1 << 10));}@@ -90,7 +94,7 @@ fn add(service: &'static str, text: &str) -> Option<(String, String, String)> {*n += 1;match service {"rd" => format!("RDT{}", *n),- "ad" => n.to_string(),+ "ad" | "tb" => n.to_string(),_ => format!("pmt{}", *n),}};@@ -136,7 +140,15 @@ fn token_ok(headers: &HeaderMap) -> bool {/// `GET /_debrid/torrents`: the ids the fake accounts still hold.pub async fn held() -> Response {- let ids: Vec<String> = with(|m| m.keys().cloned().collect());+ let mut ids: Vec<String> = with(|m| m.keys().cloned().collect());+ // TorBox's web downloads too.+ ids.extend(+ TB_WEB+ .lock()+ .unwrap()+ .iter()+ .flat_map(|m| m.keys().map(u64::to_string)),+ );axum::Json(json!(ids)).into_response()}@@ -436,3 +448,295 @@ pub async fn pm_delete(headers: HeaderMap, body: Bytes) -> Response {None => pm_error("not_found"),}}++// ---- TorBox, as https://api-docs.torbox.app/ documents it ------------------------------------+//+// `{"success","error","detail","data"}`, the error a code. Tokens `good` (premium) and `free`+// (Bearer; `requestdl` takes `?token=`). Web downloads of the fake host's links and torrents (the+// store above, service "tb"), each ready after two `mylist` polls; every file's link is the lab's own direct one.++/// A web download: (its polls so far, the file's size, name and direct link, the link it was+/// made from).+type Web = (u32, u64, String, String, String);+static TB_WEB: Mutex<Option<HashMap<u64, Web>>> = Mutex::new(None);++fn tb_ok(data: Value) -> Response {+ axum::Json(json!({"success": true, "error": null, "detail": "lab", "data": data}))+ .into_response()+}++fn tb_error(status: StatusCode, code: &str) -> Response {+ (+ status,+ axum::Json(+ json!({"success": false, "error": code, "detail": format!("lab: {code}"), "data": null}),+ ),+ )+ .into_response()+}++/// As the documentation shows it: `ITEM_NOT_FOUND` with `success: true`.+fn tb_not_found() -> Response {+ (+ StatusCode::NOT_FOUND,+ axum::Json(+ json!({"success": true, "error": "ITEM_NOT_FOUND", "detail": "lab", "data": null}),+ ),+ )+ .into_response()+}++fn tb_token(t: &str) -> Option<bool> {+ match t {+ t if t == "good" || t.starts_with("good-") => Some(true),+ "free" => Some(false),+ _ => None,+ }+}++fn tb_premium(headers: &HeaderMap) -> Option<bool> {+ tb_token(+ headers+ .get(header::AUTHORIZATION)?+ .to_str()+ .ok()?+ .strip_prefix("Bearer ")?,+ )+}++fn tb_bad_token() -> Response {+ tb_error(StatusCode::FORBIDDEN, "BAD_TOKEN")+}++fn tb_next() -> u64 {+ let mut n = NEXT.lock().unwrap();+ *n += 1;+ *n+}++/// `GET /tb/v1/api/user/me`.+pub async fn tb_user(headers: HeaderMap) -> Response {+ let Some(premium) = tb_premium(&headers) else {+ return tb_bad_token();+ };+ let until = if premium {+ "2099-01-01T00:00:00Z"+ } else {+ "2020-01-01T00:00:00Z"+ };+ tb_ok(+ json!({"id": 1, "email": "[email protected]", "plan": if premium { 2 } else { 0 },+ "is_subscribed": premium, "premium_expires_at": until}),+ )+}++static TB_DEVICE: Mutex<Option<HashMap<String, u32>>> = Mutex::new(None);++/// `GET /tb/v1/api/user/auth/device/start?app=` (public).+pub async fn tb_device_start() -> Response {+ let device = format!("tbdev{}", tb_next());+ TB_DEVICE+ .lock()+ .unwrap()+ .get_or_insert_with(HashMap::new)+ .insert(device.clone(), 0);+ tb_ok(+ json!({"device_code": device, "interval": 0, "expires_at": "2099-01-01T00:00:00Z",+ "verification_url": "https://torbox.app/oauth/device?app=MisterDownloadManager",+ "friendly_verification_url": "https://tor.box/link", "code": "123456"}),+ )+}++/// `POST /tb/v1/api/user/auth/device/token`, JSON `device_code`: allowed on the third poll,+/// then a premium token (`good-device`).+pub async fn tb_device_token(body: Bytes) -> Response {+ let v: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);+ let device = v["device_code"].as_str().unwrap_or_default().to_owned();+ let mut all = TB_DEVICE.lock().unwrap();+ let Some(polls) = all.get_or_insert_with(HashMap::new).get_mut(&device) else {+ return tb_error(StatusCode::BAD_REQUEST, "ITEM_NOT_FOUND");+ };+ *polls += 1;+ if *polls < 3 {+ return tb_error(StatusCode::BAD_REQUEST, "DEVICE_CODE_NOT_USED");+ }+ tb_ok(json!({"access_token": "good-device", "token_type": "Bearer"}))+}++/// `GET /tb/v1/api/webdl/hosters` (public).+pub async fn tb_hosters() -> Response {+ tb_ok(+ json!([{"id": 1, "name": "Hostertest", "domains": [HOSTER, "hoster2.test"],+ "status": true, "type": "hoster"}]),+ )+}++/// `POST /tb/v1/api/webdl/createwebdownload` (`link`).+pub async fn tb_web_create(headers: HeaderMap, body: Bytes) -> Response {+ let Some(premium) = tb_premium(&headers) else {+ return tb_bad_token();+ };+ let Some(link) = field(&form(&body), "link").and_then(|l| url::Url::parse(&l).ok()) else {+ return tb_error(StatusCode::BAD_REQUEST, "INVALID_LINK");+ };+ let (size, name, direct) = match crate::debrid::direct_for(&headers, &link) {+ Ok(d) => d,+ Err("unsupported") => return tb_error(StatusCode::BAD_REQUEST, "UNSUPPORTED_SITE"),+ Err("down") => return tb_error(StatusCode::INTERNAL_SERVER_ERROR, "TEMPORARILY_DISABLED"),+ Err(_) => return tb_error(StatusCode::BAD_REQUEST, "LINK_OFFLINE"),+ };+ if !premium {+ return tb_error(StatusCode::FORBIDDEN, "PLAN_RESTRICTED_FEATURE");+ }+ let id = tb_next();+ TB_WEB+ .lock()+ .unwrap()+ .get_or_insert_with(HashMap::new)+ .insert(id, (0, size, name, direct, link.to_string()));+ tb_ok(json!({"hash": "h", "webdownload_id": id, "auth_id": "a"}))+}++/// One `mylist` entry: still at it for two polls, then finished with `files`.+fn tb_item(id: u64, name: &str, polls: u32, dead: bool, files: Vec<Value>) -> Value {+ let done = polls > 2 && !dead;+ let state = if dead {+ "failed"+ } else if done {+ "completed"+ } else {+ "downloading"+ };+ json!({"id": id, "name": name, "download_state": state,+ "progress": if done { 1.0 } else { 0.5 }, "download_finished": done,+ "download_present": done, "error": null, "files": if done { files } else { vec![] }})+}++/// `GET /tb/v1/api/{webdl,torrents}/mylist?id=`.+pub async fn tb_list(+ headers: HeaderMap,+ Path(kind): Path<String>,+ Query(q): Query<HashMap<String, String>>,+) -> Response {+ if tb_premium(&headers).is_none() {+ return tb_bad_token();+ }+ let id: u64 = q.get("id").and_then(|i| i.parse().ok()).unwrap_or(0);+ if kind == "webdl" {+ let mut all = TB_WEB.lock().unwrap();+ let all = all.get_or_insert_with(HashMap::new);+ // No id: the whole list, each with the link it was made from.+ if !q.contains_key("id") {+ if all.is_empty() {+ return tb_not_found();+ }+ let list: Vec<Value> = all+ .iter()+ .map(|(id, (polls, _, name, _, link))| {+ let mut v = tb_item(*id, name, *polls, false, vec![]);+ v["original_url"] = json!(link);+ v+ })+ .collect();+ return tb_ok(json!(list));+ }+ let Some((polls, size, name, _, _)) = all.get_mut(&id) else {+ return tb_not_found();+ };+ *polls += 1;+ let files = vec![json!({"id": 0, "name": name, "short_name": name, "size": size})];+ return tb_ok(tb_item(id, name, *polls, false, files));+ }+ let Some((polls, dead)) = poll(&id.to_string(), "tb") else {+ return tb_not_found();+ };+ let Some((name, list)) = with(|m| m.get(&id.to_string()).map(|t| (t.name.clone(), files(t))))+ else {+ return tb_not_found();+ };+ let files = list+ .iter()+ .enumerate()+ .map(|(i, (path, _, bytes))| {+ json!({"id": i, "name": path, "short_name": path.rsplit('/').next().unwrap_or(path),+ "size": bytes})+ })+ .collect();+ tb_ok(tb_item(id, &name, polls, dead, files))+}++/// `GET /tb/v1/api/{webdl,torrents}/requestdl?token=&<id>=&file_id=&redirect=false`.+pub async fn tb_requestdl(+ headers: HeaderMap,+ Path(kind): Path<String>,+ Query(q): Query<HashMap<String, String>>,+) -> Response {+ if q.get("token").and_then(|t| tb_token(t)).is_none() {+ return tb_bad_token();+ }+ if q.get("redirect").map(String::as_str) != Some("false") {+ // MDM always asks for the link itself: a redirect puts the key in the download's address.+ return tb_error(StatusCode::BAD_REQUEST, "INVALID_OPTION");+ }+ let file: usize = q.get("file_id").and_then(|i| i.parse().ok()).unwrap_or(0);+ let id_name = if kind == "webdl" {+ "web_id"+ } else {+ "torrent_id"+ };+ let id: u64 = q.get(id_name).and_then(|i| i.parse().ok()).unwrap_or(0);+ if kind == "webdl" {+ let all = TB_WEB.lock().unwrap();+ return match all.as_ref().and_then(|m| m.get(&id)) {+ Some((_, _, _, direct, _)) => tb_ok(json!(direct)),+ None => tb_not_found(),+ };+ }+ match with(|m| m.get(&id.to_string()).map(files)).and_then(|l| l.into_iter().nth(file)) {+ Some((path, size, _)) => tb_ok(json!(direct_link(&headers, &path, size))),+ None => tb_not_found(),+ }+}++/// `POST /tb/v1/api/torrents/createtorrent` (`magnet`).+pub async fn tb_torrent_create(headers: HeaderMap, body: Bytes) -> Response {+ if tb_premium(&headers).is_none() {+ return tb_bad_token();+ }+ match field(&form(&body), "magnet").and_then(|m| add("tb", &m)) {+ Some((id, _, hash)) => tb_ok(+ json!({"hash": hash, "torrent_id": id.parse::<u64>().unwrap_or(0), "auth_id": "a"}),+ ),+ None => tb_error(StatusCode::BAD_REQUEST, "BOZO_TORRENT"),+ }+}++/// `POST /tb/v1/api/{webdl/controlwebdownload,torrents/controltorrent}`, JSON+/// `{"<webdl_id|torrent_id>": id, "operation": "delete"}`.+pub async fn tb_control(headers: HeaderMap, body: Bytes) -> Response {+ if tb_premium(&headers).is_none() {+ return tb_bad_token();+ }+ let v: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);+ if v["operation"] != "delete" {+ return tb_error(StatusCode::BAD_REQUEST, "INVALID_OPTION");+ }+ let Some(id) = ["webdl_id", "torrent_id"]+ .iter()+ .find_map(|k| v[k].as_u64())+ else {+ return tb_error(StatusCode::BAD_REQUEST, "MISSING_REQUIRED_OPTION");+ };+ let torrent = with(|m| m.remove(&id.to_string())).is_some();+ let web = TB_WEB+ .lock()+ .unwrap()+ .as_mut()+ .and_then(|m| m.remove(&id))+ .is_some();+ if torrent || web {+ tb_ok(Value::Null)+ } else {+ tb_not_found()+ }+}diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rsindex 5d662f24..921f39fe 100644--- a/crates/labserver/src/server.rs+++ b/crates/labserver/src/server.rs@@ -431,6 +431,44 @@ impl LabServer {"/pm/api/transfer/delete",post(crate::debrid_torrents::pm_delete),)+ // A fake TorBox: web downloads and torrents (`debrid_torrents`).+ .route("/tb/v1/api/user/me", get(crate::debrid_torrents::tb_user))+ .route(+ "/tb/v1/api/user/auth/device/start",+ get(crate::debrid_torrents::tb_device_start),+ )+ .route(+ "/tb/v1/api/user/auth/device/token",+ post(crate::debrid_torrents::tb_device_token),+ )+ .route(+ "/tb/v1/api/webdl/hosters",+ get(crate::debrid_torrents::tb_hosters),+ )+ .route(+ "/tb/v1/api/webdl/createwebdownload",+ post(crate::debrid_torrents::tb_web_create),+ )+ .route(+ "/tb/v1/api/torrents/createtorrent",+ post(crate::debrid_torrents::tb_torrent_create),+ )+ .route(+ "/tb/v1/api/{kind}/mylist",+ get(crate::debrid_torrents::tb_list),+ )+ .route(+ "/tb/v1/api/{kind}/requestdl",+ get(crate::debrid_torrents::tb_requestdl),+ )+ .route(+ "/tb/v1/api/webdl/controlwebdownload",+ post(crate::debrid_torrents::tb_control),+ )+ .route(+ "/tb/v1/api/torrents/controltorrent",+ post(crate::debrid_torrents::tb_control),+ ).route("/_debrid/torrents", get(crate::debrid_torrents::held))// RSS feeds for the app's RSS tests (#39, `feeds`)..route("/rss/shows.xml", get(crate::feeds::shows))@@ -556,6 +594,8 @@ GET /redirect?to=URL[&ttl_ms=N][&uses=N][&code=3xx] 302 (or code) to URL (nota fake Real-Debrid (#44): tokens good (premium), free; links http://hoster.test/file/SIZE/NAME[?gone=1&down=1&chunks=N&ttl_ms=N&rate=SIZE]/ad/v4/{user,hosts/domains,link/unlock,link/delayed,pin/check}, /ad/v4.1/pin/get a fake AllDebrid: the same tokens and links, plus delayed=N/pm/api/{account/info,services/list,transfer/directdl} a fake Premiumize: the same tokens and links+/tb/v1/api/{user/me,user/auth/device/{start,token},webdl/hosters,webdl/createwebdownload,torrents/createtorrent,*/mylist,*/requestdl,*/control*}+ a fake TorBox: the same tokens and links (ready after 2 polls), and torrentsGET /hop?to=URL&how=meta|header[&wait=S][&cookie=N=V] a page that sends the browser on to URL (meta refresh or Refresh header)RSS made-up feeds for the RSS feeds window (#39); never real onesdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 6e24baf4..b011bb49 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -13,7 +13,7 @@ How Mister Download Manager's pieces fit together.| `crates/remote` | `mdm-remote` | The remote control (#141): the HTTPS server a paired phone or computer on the local network uses (its page, pairing codes, device tokens, the self-signed certificate); every request becomes an automation API command the app answers || `crates/nmhost` | `mdm-nmhost` | The browser's native messaging host: takes captured downloads from the extension and hands them to the app || `crates/ipc` | `mdm-ipc` | The single-instance channel (a token-protected local socket), the data folder, and the capture rules shared by the app and the host |-| `crates/debrid` | `mdm-debrid` | Debrid accounts (#44): the services' official APIs (Real-Debrid, AllDebrid, Premiumize) turn a file host's link into a direct one the engine downloads |+| `crates/debrid` | `mdm-debrid` | Debrid accounts (#44): the services' official APIs (Real-Debrid, AllDebrid, Premiumize, TorBox) turn a file host's link into a direct one the engine downloads || `crates/extract` | `mdm-extract` | Archive extraction (#37): zip, tar, gz and xz in process; 7z and RAR through an installed 7-Zip, run as its own program || `crates/geo` | `mdm-geo` | Where a download's server is (#140): an IP-to-country range table built from DB-IP's Lite data (`tools/geo/build.py`), looked up on this computer only, and the countries' flags || `crates/tools` | `mdm-tools` | Video pages through yt-dlp and ffmpeg, image galleries through gallery-dl (run as separate programs); while a network adapter is chosen, their connections go through a proxy of MDM's on 127.0.0.1 that binds them to it (`relay.rs`) |diff --git a/docs/README.md b/docs/README.mdindex 0b620f0c..9834860b 100644--- a/docs/README.md+++ b/docs/README.md@@ -34,7 +34,7 @@ These pages explain each part of the program. The tutorials walk through the thi- **[Image galleries](galleries.md)** — download a gallery's pictures (Wikimedia Commons, Flickr, DeviantArt and many more) with gallery-dl.- **[Torrents](torrents.md)** — magnet links and .torrent files, choosing files, and sharing.- **[Torrents and your security](torrent-security.md)** — what others can see, the network switches, blocklists, proxies.-- **[Debrid service accounts](debrid.md)** — Real-Debrid, AllDebrid and Premiumize: file-host links through your own account.+- **[Debrid service accounts](debrid.md)** — Real-Debrid, AllDebrid, Premiumize and TorBox: file-host links through your own account.## Settingsdiff --git a/docs/debrid.md b/docs/debrid.mdindex 2a6eb163..4baffb82 100644--- a/docs/debrid.md+++ b/docs/debrid.md@@ -1,12 +1,12 @@# Debrid service accounts-A debrid service, such as Real-Debrid, AllDebrid or Premiumize, is a paid account that downloads files from file hosts+A debrid service, such as Real-Debrid, AllDebrid, Premiumize or TorBox, is a paid account that downloads files from file hostson its own servers. It hands back a plain direct link, without the host's waits, speed capsand captchas. With your account in MDM, a link from a host your service supports is unlockedthrough the service, then downloaded by MDM like any file: all its connections, pause andresume.-MDM supports three services: **Real-Debrid**, **AllDebrid** and **Premiumize**.+MDM supports four services: **Real-Debrid**, **AllDebrid**, **Premiumize** and **TorBox**.> **Experimental:** built from each service's public API documentation, not yet confirmed with a> real paid account. AllDebrid's answers were also checked against its real API with the public@@ -19,9 +19,9 @@ MDM supports three services: **Real-Debrid**, **AllDebrid** and **Premiumize**.1. **Options → Accounts → Add...**2. Pick the service, then either:- - **Sign in in the browser** (Real-Debrid and AllDebrid): MDM shows a code and opens the- service's page. Type the code there (AllDebrid's page already has it) and allow MDM. The- dialog notices on its own.+ - **Sign in in the browser** (Real-Debrid, AllDebrid and TorBox): MDM shows a code and opens+ the service's page (TorBox's is also at `tor.box/link`). Type the code there (AllDebrid's+ page already has it) and allow MDM. The dialog notices on its own.- or paste your **API token** (**Find my token** opens the service's page that shows it),then **Use the token**. Premiumize signs in this way only: paste the API key from itsAccount page.@@ -71,9 +71,14 @@ the list:is down (MDM tries again later), the file is gone, and so on.- AllDebrid sometimes needs a while to prepare a link. MDM waits for it, up to 10 minutes,and the list says so.+- TorBox first downloads the file to its own servers (at once when it has it already). MDM+ waits for it, up to an hour, and the list says how far it is, such as **40% at TorBox**.+ Once the download is done, or taken off MDM's list, it leaves your account's list of web+ downloads on TorBox; a paused one keeps its place there, to go on with.- MDM asks each service well under its request limit: Real-Debrid at most 120 times a minute- (it allows 250), AllDebrid 300 (it allows 600), Premiumize 60 (it publishes no limit). When- a service says it's asked too often, MDM waits.+ (it allows 250), AllDebrid 300 (it allows 600), Premiumize 60 (it publishes no limit), TorBox+ 120 (it allows 300 a minute, and 60 new web downloads an hour). When a service says it's+ asked too often, MDM waits.## Download one link directly insteaddiff --git a/docs/options.md b/docs/options.mdindex cf94ac17..6e1a2a1a 100644--- a/docs/options.md+++ b/docs/options.md@@ -121,7 +121,7 @@ The passwords (these, the proxy's and the debrid accounts') are kept in the syst*Accounts: your debrid accounts.*-Your debrid service accounts (Real-Debrid, AllDebrid, Premiumize; experimental): **Add...** signs in by code in the browser or with your API token or key; a link from a host the service supports is then downloaded through it. The list's order is the order accounts are asked. See [Debrid service accounts](debrid.md).+Your debrid service accounts (Real-Debrid, AllDebrid, Premiumize, TorBox; experimental): **Add...** signs in by code in the browser or with your API token or key; a link from a host the service supports is then downloaded through it. The list's order is the order accounts are asked. See [Debrid service accounts](debrid.md).## Sounds