//! `share.fetchLinks` — a share that is a download, decided here so no shell //! carries the rule. //! //! - A magnet, or a link to a `.torrent`, shared as the whole of the share's //! URL or text, is a download in every app: there is no page in it to read. //! - In an app whose kit holds `fetch` and not `page` (Cotton Downloads), every //! link is: the shared URL, or each link in shared text, and a shared //! `.torrent` file, which is sent to the object as its magnet (the Mac //! fetches from a link, and the file's bytes never leave the phone). //! //! Each becomes a row by the object's `fetch_add`. The answer is `{ fetch: //! [id] }`, empty when the share is no download and takes its other branches; //! in the app that takes every link, a share with none in it has no other //! branch, and the answer says so in the kit's words (`said`), so a shell //! never decides what an empty answer means there. //! A refusal (a phone not signed in, an object out of reach) is the act's own. use std::path::Path; use cotton_core::kit::AppKit; use cotton_core::rules::shell_lines::LineSet; use cotton_core::transforms::urls::{extract_urls, is_http_url}; use serde_json::{json, Value}; use sha1::{Digest, Sha1}; use crate::handle::CottonHandle; use crate::methods::{dispatch, MethodError}; /// Far larger than any torrent's metainfo; a bigger file is not one. const TORRENT_LARGEST: u64 = 16 * 1024 * 1024; fn is_magnet(link: &str) -> bool { link.get(..8).is_some_and(|head| head.eq_ignore_ascii_case("magnet:?")) } fn is_torrent_link(link: &str) -> bool { is_magnet(link) || (is_http_url(Some(link)) && url::Url::parse(link).is_ok_and(|parsed| parsed.path().to_ascii_lowercase().ends_with(".torrent"))) } /// Whether this app's shares are downloads: it keeps the queue, no reading /// pile and no conversations (Comms keeps the queue for its Downloads chat, /// and a share into Comms is a download only when it is sent there: `to`). pub fn takes_every_link(kit: Option<&AppKit>) -> bool { kit.is_some_and(|kit| kit.keeps_table("fetch") && !kit.keeps_table("page") && !kit.keeps_table("message")) } /// Whether this share was sent to Comms' Downloads chat (`to: "downloads"`), in an app that keeps the queue. fn to_downloads(kit: Option<&AppKit>, request: &Value) -> bool { request["to"] == "downloads" && kit.is_some_and(|kit| kit.keeps_table("fetch")) } /// The links of a share that are downloads, in the order it gave them. pub fn fetch_links(every_link: bool, url: Option<&str>, text: Option<&str>) -> Vec { let whole = |candidate: Option<&str>| candidate.map(str::trim).filter(|link| !link.is_empty() && !link.contains(char::is_whitespace)).map(str::to_string); if let Some(link) = [whole(url), whole(text)].into_iter().flatten().find(|link| is_torrent_link(link)) { return vec![link]; } if !every_link { return Vec::new(); } if let Some(link) = whole(url).filter(|link| is_http_url(Some(link)) || is_magnet(link)) { return vec![link]; } let mut links: Vec = Vec::new(); for word in text.unwrap_or_default().split_whitespace() { let found = if is_magnet(word) { vec![word.trim_end_matches([',', '.', ';', ')', '>']).to_string()] } else { extract_urls(Some(word)) }; for link in found { if !links.contains(&link) { links.push(link); } } } links } /// Where the bencoded value starting at `at` ends. By a depth count, never /// recursion: a file that nests a million lists is only a bad file. fn value_end(bytes: &[u8], at: usize) -> Option { let mut index = at; let mut depth = 0_usize; loop { match *bytes.get(index)? { b'e' if depth > 0 => { depth -= 1; index += 1; } b'l' | b'd' => { depth += 1; index += 1; } b'i' => index += bytes[index..].iter().position(|byte| *byte == b'e')? + 1, b'0'..=b'9' => index = string_at(bytes, index)?.1, _ => return None, } if depth == 0 { return Some(index); } } } /// The bencoded string at `at`: its bytes and where it ends. fn string_at(bytes: &[u8], at: usize) -> Option<(&[u8], usize)> { let colon = at + bytes.get(at..)?.iter().position(|byte| *byte == b':')?; let length: usize = std::str::from_utf8(&bytes[at..colon]).ok()?.parse().ok()?; let end = colon.checked_add(1)?.checked_add(length)?; Some((bytes.get(colon + 1..end)?, end)) } /// A dictionary's entries as `(key, value start, value end)`. fn entries(bytes: &[u8], at: usize) -> Option> { if *bytes.get(at)? != b'd' { return None; } let mut found = Vec::new(); let mut index = at + 1; while *bytes.get(index)? != b'e' { let (key, start) = string_at(bytes, index)?; let end = value_end(bytes, start)?; found.push((key, start, end)); index = end; } Some(found) } /// Every string in a list of lists (a torrent's trackers, tier by tier). fn strings_within(bytes: &[u8], start: usize, end: usize) -> Vec { let mut found = Vec::new(); let mut index = start; while index < end { if bytes[index].is_ascii_digit() { let Some((text, next)) = string_at(bytes, index) else { break }; found.push(String::from_utf8_lossy(text).into_owned()); index = next; } else { index += 1; } } found } fn escaped(text: &str) -> String { text.bytes().map(|byte| if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) { char::from(byte).to_string() } else { format!("%{byte:02X}") }).collect() } /// The magnet of a `.torrent`'s bytes: the SHA-1 of its `info` dictionary as /// the file wrote it, its name and its trackers. `None` when the bytes are no /// version-1 torrent (a version-2-only file carries no `pieces` to name it by). pub fn magnet_of(bytes: &[u8]) -> Option { let top = entries(bytes, 0)?; let (_, start, end) = *top.iter().find(|(key, ..)| *key == b"info")?; let info = entries(bytes, start)?; info.iter().find(|(key, ..)| *key == b"pieces")?; let mut magnet = format!("magnet:?xt=urn:btih:{}", hex::encode(Sha1::digest(&bytes[start..end]))); if let Some((_, name, _)) = info.iter().find(|(key, ..)| *key == b"name") { magnet += &format!("&dn={}", escaped(&String::from_utf8_lossy(string_at(bytes, *name)?.0))); } let mut trackers: Vec = Vec::new(); for (key, from, to) in &top { if *key == b"announce" || *key == b"announce-list" { for tracker in strings_within(bytes, *from, *to) { if !trackers.contains(&tracker) { magnet += &format!("&tr={}", escaped(&tracker)); trackers.push(tracker); } } } } Some(magnet) } fn torrent_magnet(path: &str) -> Result { let unreadable = || MethodError::new("refused", LineSet::shipped("capture").and_then(|lines| lines.say("share.torrent_unreadable", &[])).unwrap_or_default()); let small = std::fs::metadata(path).map_err(|_| unreadable())?.len() <= TORRENT_LARGEST; if !small { return Err(unreadable()); } magnet_of(&std::fs::read(path).map_err(|_| unreadable())?).ok_or_else(unreadable) } /// The sources a share becomes: its `.torrent`'s magnet, or its links. A file /// that is no `.torrent` is no download, whatever address came beside it. fn sources(every_link: bool, request: &Value) -> Result, MethodError> { if let Some(path) = request["file"].as_str().filter(|path| !path.is_empty()) { let name = request["fileName"].as_str().filter(|name| !name.is_empty()).unwrap_or(path); let torrent = Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case("torrent")); return if every_link && torrent { Ok(vec![torrent_magnet(path)?]) } else { Ok(Vec::new()) }; } Ok(fetch_links(every_link, request["url"].as_str(), request["text"].as_str())) } /// What an answer that queued nothing says: in the app that takes every link /// there is no other branch for it, so it is said; elsewhere nothing is. fn nothing_said(every_link: bool, found: &[String]) -> Option { (every_link && found.is_empty()).then(|| LineSet::shipped("capture").and_then(|lines| lines.say("share.no_link", &[])).unwrap_or_default()) } /// `share.fetchLinks { url?, text?, title?, file?, fileName?, to? }`; `to: "downloads"` is a share sent to Comms' Downloads chat, where every link is a download. pub fn fetch_links_method(handle: &CottonHandle, request: &Value) -> Result { let kit = AppKit::at(handle.client().layout().root()).map_err(|why| MethodError::new("unreadable", why))?; let downloads = to_downloads(kit.as_ref(), request); let every_link = downloads || takes_every_link(kit.as_ref()); let found = sources(every_link, request)?; if downloads { // Into the Downloads chat: the phone writes each row itself, sealed, as the chat's own writing box does. if found.is_empty() { return Ok(json!({ "fetch": [], "said": crate::phone::chat_app::downloads::not_a_link() })); } let made = crate::phone::chat_app::downloads::queue(&handle.client(), &found, request["title"].as_str())?; return Ok(json!({ "fetch": made["fetch"].clone() })); } if let Some(said) = nothing_said(every_link, &found) { return Ok(json!({ "fetch": [], "said": said })); } let title = request["title"].as_str().map(str::trim).filter(|title| !title.is_empty() && found.len() == 1 && *title != found[0]); let mut made = Vec::new(); for source in &found { let mut args = json!({ "source": source }); if let Some(title) = title { args["title"] = json!(title); } made.push(dispatch(handle, "object.act", &json!({ "act": "fetch_add", "args": args }))?["fetch"].clone()); } Ok(json!({ "fetch": made })) } #[cfg(test)] #[path = "share_fetch_tests.rs"] mod tests;