//! 傳送: a file, or a few words, from any device of the account to any other one — a computer //! to the phone, the phone to a computer, one computer to another. Nothing to do with a chat. //! //! The brain is the post office. The sender hands it the parcel in pieces (2 MB each, so a slow //! link and the account server's 35 s per request never matter); the brain keeps it in //! `drops/` and carries it on: //! - to a computer: pushed in pieces through 裝置連結's road (`/api/device/run`, tool //! `drop_put`), picked up where it stopped when the link breaks, tried again while the computer //! is off (for 7 days). It lands in that computer's 下載/AnyBot, with a notification; words go //! on its clipboard. //! - to the phone: it waits at the brain; the phone is told (a notification) and downloads it. //! - to the brain's own computer: moved into its 下載/AnyBot. //! //! A computer takes parcels only from its own brain (see `remote::device_run`). use base64::Engine; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::sync::{Condvar, Mutex, OnceLock}; /// The tool name a brain uses to push a piece to a computer. pub const PUT: &str = "drop_put"; /// The phone as a destination (every phone signed in to the account). pub const PHONE: &str = "phone"; /// One piece. pub const CHUNK: usize = 2 * 1024 * 1024; /// The largest file (estimated: the brain keeps a whole copy until it is delivered). pub const MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024; /// The most words in one go. pub const MAX_TEXT_CHARS: usize = 100_000; /// How long the brain keeps a parcel (delivered or not). const KEEP_MS: i64 = 7 * 24 * 3600 * 1000; /// After a try that didn't get through, how long before the next. const RETRY_MS: i64 = 15_000; /// How many arrived parcels a computer remembers. const RECEIVED_MAX: usize = 100; /// One thing on its way. `state`: uploading (the sender is still handing it over), waiting (for /// the destination to be on), sending, ready (the phone can download it), done, failed. #[derive(Clone, Serialize, Deserialize, Default, Debug, PartialEq)] pub struct Parcel { pub id: String, pub name: String, pub bytes: u64, /// Words instead of a file. #[serde(default, skip_serializing_if = "String::is_empty")] pub text: String, /// Who sent it, in words (a computer's name, 手機, a bot's name). pub from: String, #[serde(default)] pub from_id: String, pub to: String, pub to_name: String, pub at: i64, pub state: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub note: String, /// Bytes the brain has (while uploading), then bytes the destination has. #[serde(default)] pub sent: u64, #[serde(skip)] next_try: i64, } /// Something that arrived on this computer. #[derive(Clone, Serialize, Deserialize, Default, Debug, PartialEq)] pub struct Received { pub id: String, pub name: String, /// Where the file is now (empty for words). #[serde(default)] pub path: String, pub bytes: u64, #[serde(default, skip_serializing_if = "String::is_empty")] pub text: String, pub from: String, pub at: i64, } pub struct Office { dir: PathBuf, /// Where arrived files are put. land: PathBuf, parcels: Mutex>, received: Mutex>, /// Arrived since the window last looked (it copies words to the clipboard and rings). fresh: Mutex>, bell: (Mutex, Condvar), } /// How a try to a computer ended. enum Outcome { Done, Later(String), Failed(String), } fn now_ms() -> i64 { crate::model::now_ms() } /// A file name safe to put in a folder: no path, no control characters, not hidden, not endless. pub fn safe_name(name: &str) -> String { let last = name.rsplit(['/', '\\']).next().unwrap_or(""); let s: String = last.chars().filter(|c| !c.is_control() && *c != ':').collect(); let s = s.trim().trim_start_matches('.').trim(); let s: String = if s.chars().count() > 120 { // The ending says what the file is: keep it. let ext: String = Path::new(s).extension().map(|e| format!(".{}", e.to_string_lossy())).filter(|e| e.chars().count() <= 12).unwrap_or_default(); format!("{}{ext}", s.chars().take(120 - ext.chars().count()).collect::()) } else { s.to_string() }; if s.is_empty() { "檔案".into() } else { s } } fn good_id(id: &str) -> bool { !id.is_empty() && id.len() <= 32 && id.chars().all(|c| c.is_ascii_alphanumeric()) } /// A name nothing in `dir` has yet: `報告.pdf`, then `報告 (2).pdf`… fn free_name(dir: &Path, name: &str) -> PathBuf { let first = dir.join(name); if !first.exists() { return first; } let p = Path::new(name); let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string()); let ext = p.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); (2..10_000).map(|n| dir.join(format!("{stem} ({n}){ext}"))).find(|c| !c.exists()).unwrap_or(first) } fn write_whole(path: &Path, bytes: &[u8]) { let tmp = path.with_extension("tmp"); if std::fs::write(&tmp, bytes).is_ok() { let _ = std::fs::rename(&tmp, path); } } /// Words that mean "not now" (the computer is off, the link broke) rather than "no". fn only_for_now(e: &str) -> bool { ["離線", "斷線", "斷了", "連不到", "等太久", "沒有回應", "暫時"].iter().any(|w| e.contains(w)) } impl Office { pub fn at(dir: PathBuf, land: PathBuf) -> Office { let _ = std::fs::create_dir_all(&dir); let read = |f: &str| std::fs::read(dir.join(f)).ok(); let mut parcels: Vec = read("index.json").and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); // Whatever was half-way when AnyBot stopped: a half upload is gone with its sender; // a delivery starts again (the other side says how much it has). parcels.retain(|p| p.state != "uploading"); for p in parcels.iter_mut().filter(|p| p.state == "sending") { p.state = "waiting".into(); } let received = read("received.json").and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); Office { dir, land, parcels: Mutex::new(parcels), received: Mutex::new(received), fresh: Mutex::new(vec![]), bell: (Mutex::new(0), Condvar::new()) } } fn bin(&self, id: &str) -> PathBuf { self.dir.join(format!("{id}.bin")) } fn save(&self, v: &[Parcel]) { write_whole(&self.dir.join("index.json"), &serde_json::to_vec(v).unwrap_or_default()); } fn change(&self, f: impl FnOnce(&mut Vec) -> R) -> R { let mut g = self.parcels.lock().unwrap_or_else(|e| e.into_inner()); let r = f(&mut g); self.save(&g); r } fn set(&self, id: &str, f: impl FnOnce(&mut Parcel)) -> bool { self.change(|v| v.iter_mut().find(|p| p.id == id).map(f).is_some()) } pub fn ring(&self) { *self.bell.0.lock().unwrap_or_else(|e| e.into_inner()) += 1; self.bell.1.notify_all(); } // ---------- the sender's side (at the brain) ---------- /// A new parcel. Words are whole at once; a file follows in pieces (`chunk`, then `finish`). #[allow(clippy::too_many_arguments)] pub fn begin(&self, name: &str, bytes: u64, text: &str, to: &str, to_name: &str, from: &str, from_id: &str) -> Result { if to.is_empty() || to_name.is_empty() { return Err("請選要傳到哪一台".into()); } if to == from_id { return Err("這就是你現在用的這台,選另一台".into()); } let text = text.trim(); let id = crate::httpd::random_hex(8); let mut p = Parcel { id: id.clone(), from: from.to_string(), from_id: from_id.to_string(), to: to.to_string(), to_name: to_name.to_string(), at: now_ms(), ..Default::default() }; if !text.is_empty() { if text.chars().count() > MAX_TEXT_CHARS { return Err(format!("文字太長了(最多 {MAX_TEXT_CHARS} 個字),請存成檔案再傳")); } p.text = text.to_string(); p.name = text.lines().next().unwrap_or("").chars().take(40).collect(); p.bytes = text.len() as u64; p.state = "waiting".into(); } else { if bytes == 0 { return Err("檔案是空的".into()); } if bytes > MAX_BYTES { return Err(format!("「{}」太大了(最多 {})", safe_name(name), crate::attach::human(MAX_BYTES))); } std::fs::write(self.bin(&id), b"").map_err(|e| format!("大腦存不下這個檔案:{e}"))?; p.name = safe_name(name); p.bytes = bytes; p.state = "uploading".into(); } self.change(|v| v.push(p)); if !text.is_empty() { self.ring(); } Ok(id) } /// One piece of an upload, at byte `at`. Answers how many bytes the brain has now; a piece /// that isn't the next one changes nothing (the sender goes on from the answer). pub fn chunk(&self, id: &str, at: u64, data: &[u8]) -> Result { let p = self.get(id).filter(|p| p.state == "uploading").ok_or("這次傳送已經取消了")?; let path = self.bin(id); let have = std::fs::metadata(&path).map(|m| m.len()).map_err(|_| "這次傳送已經取消了".to_string())?; if at != have { return Ok(have); } if have + data.len() as u64 > p.bytes { return Err("傳來的比說好的大小還多".into()); } let mut f = std::fs::OpenOptions::new().append(true).open(&path).map_err(|e| e.to_string())?; f.write_all(data).map_err(|e| format!("大腦的磁碟寫不進去:{e}"))?; let have = have + data.len() as u64; self.set(id, |p| p.sent = have); Ok(have) } /// The upload is whole: it can go on to where it is going. pub fn finish(&self, id: &str) -> Result<(), String> { let p = self.get(id).filter(|p| p.state == "uploading").ok_or("這次傳送已經取消了")?; let have = std::fs::metadata(self.bin(id)).map(|m| m.len()).unwrap_or(0); if have != p.bytes { return Err(format!("還沒傳完({} / {})", crate::attach::human(have), crate::attach::human(p.bytes))); } self.set(id, |p| { p.state = "waiting".into(); p.sent = 0; }); self.ring(); Ok(()) } /// A file already on the brain's own disk (its own window, a bot's `send_to_device`). pub fn add_file(&self, path: &Path, to: &str, to_name: &str, from: &str, from_id: &str) -> Result { let meta = std::fs::metadata(path).map_err(|_| format!("找不到「{}」", path.display()))?; if meta.is_dir() { return Err(format!("「{}」是資料夾,請先壓縮成一個檔案", path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default())); } let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let id = self.begin(&name, meta.len(), "", to, to_name, from, from_id)?; if let Err(e) = std::fs::copy(path, self.bin(&id)) { self.remove(&id); return Err(format!("讀不到「{name}」:{e}")); } self.finish(&id).inspect_err(|_| self.remove(&id))?; Ok(id) } pub fn get(&self, id: &str) -> Option { self.parcels.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|p| p.id == id).cloned() } /// Everything of the last 7 days, the newest first. pub fn list(&self) -> Vec { self.prune(now_ms()); let mut v = self.parcels.lock().unwrap_or_else(|e| e.into_inner()).clone(); v.sort_by_key(|p| std::cmp::Reverse(p.at)); v } /// A piece of a parcel that waits for the phone. Reading its end marks it done. pub fn read(&self, id: &str, at: u64, len: u64) -> Result, String> { let p = self.get(id).filter(|p| p.to == PHONE && p.text.is_empty() && matches!(p.state.as_str(), "ready" | "done")).ok_or("這個檔案已經不在了(保留 7 天)")?; let mut f = std::fs::File::open(self.bin(id)).map_err(|_| "這個檔案已經不在了(保留 7 天)".to_string())?; let len = len.clamp(1, 8 * 1024 * 1024).min(p.bytes.saturating_sub(at)) as usize; let mut buf = vec![0u8; len]; f.seek(SeekFrom::Start(at)).and_then(|_| f.read_exact(&mut buf)).map_err(|e| e.to_string())?; if at + len as u64 >= p.bytes { self.set(id, |p| { p.state = "done".into(); p.sent = p.bytes; }); } Ok(buf) } pub fn remove(&self, id: &str) { self.change(|v| v.retain(|p| p.id != id)); let _ = std::fs::remove_file(self.bin(id)); } /// Try a failed one again. pub fn retry(&self, id: &str) { let has_file = self.bin(id).exists(); self.set(id, |p| { if p.state == "failed" && (has_file || !p.text.is_empty()) { p.state = "waiting".into(); p.note.clear(); p.next_try = 0; } }); self.ring(); } fn prune(&self, now: i64) { let old: Vec = self.parcels.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|p| now - p.at > KEEP_MS).map(|p| p.id.clone()).collect(); for id in old { self.remove(&id); } } // ---------- carrying them on (the brain's worker) ---------- /// One round: everything that waits is tried. `me`: this brain's own id. `carry` pushes one /// piece to a computer (host id, the tool's args, who it is from) and gives its answer; /// `tell_phone` says a parcel is ready for the phone. pub fn deliver(&self, me: &str, carry: &dyn Fn(&str, &str, &str) -> Result, tell_phone: &dyn Fn(&Parcel)) { let now = now_ms(); self.prune(now); let todo: Vec = self.parcels.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|p| p.state == "waiting" && p.next_try <= now).cloned().collect(); for p in todo { if p.to == PHONE { self.set(&p.id, |p| p.state = "ready".into()); tell_phone(&p); continue; } self.set(&p.id, |p| p.state = "sending".into()); let outcome = if p.to == me { let r = if p.text.is_empty() { self.land_file(&self.bin(&p.id), &p.name, &p.id, &p.from, p.bytes).map(|_| ()) } else { Ok(self.land_text(&p.text, &p.id, &p.from)) }; match r { Ok(()) => Outcome::Done, Err(e) => Outcome::Failed(e), } } else { self.carry_to(&p, carry) }; match outcome { Outcome::Done => { let _ = std::fs::remove_file(self.bin(&p.id)); self.set(&p.id, |p| { p.state = "done".into(); p.sent = p.bytes; p.note.clear(); }); } Outcome::Later(why) => { self.set(&p.id, |p| { p.state = "waiting".into(); p.note = why; p.next_try = now_ms() + RETRY_MS; }); } Outcome::Failed(why) => { self.set(&p.id, |p| { p.state = "failed".into(); p.note = why; }); } } } } fn carry_to(&self, p: &Parcel, carry: &dyn Fn(&str, &str, &str) -> Result) -> Outcome { let head = json!({"id": p.id, "name": p.name, "bytes": p.bytes, "from": p.from}); let ask = |extra: Value| -> Result { let mut a = head.clone(); for (k, v) in extra.as_object().into_iter().flatten() { a[k] = v.clone(); } carry(&p.to, &a.to_string(), &p.from).map_err(|e| { if e.contains("不能遠端使用") { Outcome::Later(format!("「{}」的 AnyBot 要先更新才收得到", p.to_name)) } else if only_for_now(&e) { Outcome::Later(e) } else { Outcome::Failed(e) } }) }; let refused = |v: &Value| Outcome::Failed(v["text"].as_str().filter(|t| !t.is_empty()).unwrap_or("那台電腦沒有收下").to_string()); if !p.text.is_empty() { return match ask(json!({"text": p.text})) { Ok(v) if v["done"] == true => Outcome::Done, Ok(v) => refused(&v), Err(o) => o, }; } // How much it already has (a link that broke half-way goes on from there). let mut at = match ask(json!({"probe": true})) { Ok(v) if v["done"] == true => return Outcome::Done, Ok(v) if v["ok"] == true => v["have"].as_u64().unwrap_or(0).min(p.bytes), Ok(v) => return refused(&v), Err(o) => return o, }; let Ok(mut f) = std::fs::File::open(self.bin(&p.id)) else { return Outcome::Failed("大腦上的檔案不見了,請重新傳一次".into()) }; let mut resyncs = 0; loop { // Taken back while on its way. if self.get(&p.id).is_none() { return Outcome::Failed("已取消".into()); } let n = (CHUNK as u64).min(p.bytes - at) as usize; let mut buf = vec![0u8; n]; if f.seek(SeekFrom::Start(at)).and_then(|_| f.read_exact(&mut buf)).is_err() { return Outcome::Failed("大腦上的檔案讀不出來,請重新傳一次".into()); } let v = match ask(json!({"at": at, "data": base64::engine::general_purpose::STANDARD.encode(&buf)})) { Ok(v) => v, Err(o) => return o, }; if v["done"] == true { return Outcome::Done; } match (v["ok"] == true, v["have"].as_u64()) { (true, Some(h)) if h > at && h < p.bytes => at = h, // It has a different amount than we thought: go on from what it has. (false, Some(h)) if resyncs < 3 && h < p.bytes => { resyncs += 1; at = h; } _ => return refused(&v), } self.set(&p.id, |p| p.sent = at); } } // ---------- the receiving side (any computer) ---------- /// A piece pushed by the brain (`drop_put`'s args). Answers `{ok, have, done, text}`. pub fn take(&self, v: &Value) -> Value { let id = v["id"].as_str().unwrap_or(""); if !good_id(id) { return json!({"ok": false, "text": "這次傳送的編號不對"}); } let from = v["from"].as_str().unwrap_or("").chars().take(60).collect::(); // Already here (the brain didn't hear the last "got it"). if self.received.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|r| r.id == id) { return json!({"ok": true, "done": true}); } if let Some(text) = v["text"].as_str().filter(|t| !t.is_empty()) { if text.chars().count() > MAX_TEXT_CHARS { return json!({"ok": false, "text": "文字太長了"}); } self.land_text(text, id, &from); return json!({"ok": true, "done": true}); } let bytes = v["bytes"].as_u64().unwrap_or(0); if bytes == 0 || bytes > MAX_BYTES { return json!({"ok": false, "text": "檔案大小不對"}); } let part = self.dir.join(format!("in-{id}.part")); let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0); if v["probe"] == true { // All here but never put in place (the folder couldn't be written last time). if have == bytes { return match self.land_file(&part, v["name"].as_str().unwrap_or(""), id, &from, bytes) { Ok(_) => json!({"ok": true, "done": true, "have": have}), Err(e) => json!({"ok": false, "text": e}), }; } if have > bytes { let _ = std::fs::remove_file(&part); return json!({"ok": true, "have": 0}); } return json!({"ok": true, "have": have}); } let at = v["at"].as_u64().unwrap_or(0); if at != have { return json!({"ok": false, "have": have, "text": "接不上,從已經收到的地方再傳"}); } let Some(data) = v["data"].as_str().and_then(|d| base64::engine::general_purpose::STANDARD.decode(d).ok()).filter(|d| !d.is_empty() && d.len() <= CHUNK * 2) else { return json!({"ok": false, "have": have, "text": "這一段的內容壞了"}); }; if have + data.len() as u64 > bytes { let _ = std::fs::remove_file(&part); return json!({"ok": false, "text": "傳來的比說好的大小還多"}); } let wrote = std::fs::OpenOptions::new().create(true).append(true).open(&part).and_then(|mut f| f.write_all(&data)); if let Err(e) = wrote { return json!({"ok": false, "text": format!("這台電腦存不下:{e}")}); } let have = have + data.len() as u64; if have < bytes { return json!({"ok": true, "have": have}); } match self.land_file(&part, v["name"].as_str().unwrap_or(""), id, &from, bytes) { Ok(_) => json!({"ok": true, "done": true, "have": have}), Err(e) => json!({"ok": false, "text": e}), } } /// A whole file, moved to where the person finds it. fn land_file(&self, src: &Path, name: &str, id: &str, from: &str, bytes: u64) -> Result { std::fs::create_dir_all(&self.land).map_err(|e| format!("建不了「{}」:{e}", self.land.display()))?; let dst = free_name(&self.land, &safe_name(name)); // Another disk than the data folder's: copy, then drop the original. if std::fs::rename(src, &dst).is_err() { std::fs::copy(src, &dst).map_err(|e| format!("放不進「{}」:{e}", self.land.display()))?; let _ = std::fs::remove_file(src); } let name = dst.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); self.arrived(Received { id: id.to_string(), name, path: dst.to_string_lossy().to_string(), bytes, text: String::new(), from: from.to_string(), at: now_ms() }); Ok(dst) } fn land_text(&self, text: &str, id: &str, from: &str) { let name: String = text.lines().next().unwrap_or("").chars().take(40).collect(); self.arrived(Received { id: id.to_string(), name, path: String::new(), bytes: text.len() as u64, text: text.to_string(), from: from.to_string(), at: now_ms() }); } fn arrived(&self, r: Received) { { let mut g = self.received.lock().unwrap_or_else(|e| e.into_inner()); g.insert(0, r.clone()); g.truncate(RECEIVED_MAX); write_whole(&self.dir.join("received.json"), &serde_json::to_vec(&*g).unwrap_or_default()); } let mut f = self.fresh.lock().unwrap_or_else(|e| e.into_inner()); f.push(r); // (Nobody looks on a computer without a window.) if f.len() > 50 { f.remove(0); } } /// What arrived on this computer, the newest first. pub fn received(&self) -> Vec { self.received.lock().unwrap_or_else(|e| e.into_inner()).clone() } /// Arrived since last asked. pub fn take_fresh(&self) -> Vec { std::mem::take(&mut *self.fresh.lock().unwrap_or_else(|e| e.into_inner())) } } // ---------- this AnyBot's own office ---------- fn downloads() -> PathBuf { dirs::download_dir().or_else(|| dirs::home_dir().map(|h| h.join("Downloads"))).unwrap_or_else(std::env::temp_dir).join("AnyBot") } pub fn office() -> &'static Office { static O: OnceLock = OnceLock::new(); O.get_or_init(|| { let dir = crate::model::State::path().parent().map(|p| p.join("drops")).unwrap_or_else(|| std::env::temp_dir().join("anybot-drops")); Office::at(dir, downloads()) }) } /// Start carrying (once), and look at the queue now. pub fn kick() { static STARTED: std::sync::Once = std::sync::Once::new(); STARTED.call_once(|| { std::thread::spawn(|| { let o = office(); let mut seen = 0; loop { let me = me_id(&crate::remote::hub().settings()); let before: Vec = o.received().into_iter().map(|r| r.id).collect(); o.deliver(&me, &|host, args, who| crate::remote::run_on_device(host, PUT, args, who), &|p| { let what = if p.text.is_empty() { format!("「{}」({})可以下載了", p.name, crate::attach::human(p.bytes)) } else { format!("一段文字:{}", p.name) }; crate::remote::notify(&format!("{} 傳來的", p.from), &what, 0); }); // What was for this brain's own computer landed without the device road. let new: Vec = o.received().into_iter().filter(|r| !before.contains(&r.id)).collect(); if !new.is_empty() { new.iter().for_each(tell_here); crate::remote::hub().repaint_now(); } let g = o.bell.0.lock().unwrap_or_else(|e| e.into_inner()); let (g, _) = o.bell.1.wait_timeout_while(g, std::time::Duration::from_secs(20), |n| *n == seen).unwrap_or_else(|e| e.into_inner()); seen = *g; } }); }); office().ring(); } /// A piece arriving on this computer from its brain: taken, and the person is told when it is whole. pub fn take_here(args: &str) -> Value { let o = office(); let v = o.take(&crate::tools::args_of(args)); if v["done"] == true { // (The window, when there is one, picks these up for the clipboard; the banner is for // a person who isn't looking at AnyBot.) if let Some(r) = o.fresh.lock().unwrap_or_else(|e| e.into_inner()).last() { tell_here(r); } crate::remote::hub().repaint_now(); } v } /// The notification on the computer something arrived on. pub fn tell_here(r: &Received) { let body = if r.text.is_empty() { format!("「{}」({})已放在 下載/AnyBot", r.name, crate::attach::human(r.bytes)) } else { format!("一段文字,已複製到剪貼簿:{}", r.name) }; crate::notify::banner(&format!("{} 傳來的", if r.from.is_empty() { "AnyBot" } else { &r.from }), &body); } /// This computer as a destination: its id in the account, or (with no account: only a phone on /// the same network reaches it) a word of its own. fn me_id(s: &crate::remote::Settings) -> String { if s.host_id.is_empty() { "this".into() } else { s.host_id.clone() } } /// Where a parcel can go, as the brain knows the account: its own computer, the computers that /// show it or lend it their hands, and the phone. (Asks the account server; cached 10 s.) pub fn targets() -> Vec { static CACHE: Mutex)>> = Mutex::new(None); if let Some((t, v)) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { if t.elapsed().as_secs() < 10 { return v.clone(); } } let s = crate::remote::hub().settings(); // No account: this computer and a phone signed in to it directly. if s.relay_url.is_empty() || s.host_id.is_empty() { return vec![json!({"id": me_id(&s), "name": s.host_name, "online": true, "kind": "brain"}), json!({"id": PHONE, "name": "手機", "online": true, "kind": "phone"})]; } let mut out = vec![]; for (id, name, online) in crate::remote::devices_online(&s) { if id == s.host_id { out.push(json!({"id": id, "name": name, "online": true, "kind": "brain"})); } else { let uses = crate::remote::peer_uses(&id); if uses == s.host_id || (uses.is_empty() && crate::remote::is_hands(&id)) { out.push(json!({"id": id, "name": name, "online": online, "kind": "computer"})); } } } if out.is_empty() { // The account server didn't answer: at least this computer and the phone. out.push(json!({"id": s.host_id, "name": s.host_name, "online": true, "kind": "brain"})); } out.push(json!({"id": PHONE, "name": "手機", "online": true, "kind": "phone"})); *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), out.clone())); out } /// A destination's name (by id), or None when the account has no such device. pub fn target_name(id: &str) -> Option { targets().iter().find(|t| t["id"] == id).and_then(|t| t["name"].as_str().map(String::from)) } /// A destination by what a person (or a bot) calls it: its name, or 手機 / phone. pub fn target_called(name: &str) -> Option<(String, String)> { let want = name.trim(); let phone = ["手機", "手机", "phone", "iphone", "android"].iter().any(|w| want.eq_ignore_ascii_case(w)); targets().iter().find(|t| if phone { t["id"] == PHONE } else { t["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(want)) || t["id"] == want }).and_then(|t| Some((t["id"].as_str()?.to_string(), t["name"].as_str()?.to_string()))) } /// The brain's answers to `/api/drop/` (the phone) and `/api/sync/drop/` (a screen). /// `from_id`: the computer asking, or PHONE; `from`: what to call it. pub fn api(what: &str, method: &str, query: &std::collections::HashMap, body: &[u8], from: &str, from_id: &str) -> Result { let o = office(); let q = |k: &str| query.get(k).cloned().unwrap_or_default(); let b = || serde_json::from_slice::(body).unwrap_or(Value::Null); match (method, what) { ("GET", "targets") => Ok(json!({"targets": targets(), "you": from_id})), ("GET", "list") => Ok(json!({"items": o.list(), "you": from_id})), ("POST", "new") => { let b = b(); let to = b["to"].as_str().unwrap_or(""); let to_name = target_name(to).ok_or("帳號裡找不到這台裝置(可能剛被移除)")?; let id = o.begin(b["name"].as_str().unwrap_or(""), b["bytes"].as_u64().unwrap_or(0), b["text"].as_str().unwrap_or(""), to, &to_name, from, from_id)?; kick(); Ok(json!({"id": id, "chunk": CHUNK})) } ("POST", "chunk") => o.chunk(&q("id"), q("at").parse().unwrap_or(0), body).map(|have| json!({"have": have})), ("POST", "done") => { o.finish(b()["id"].as_str().unwrap_or(""))?; kick(); Ok(json!({"ok": true})) } ("POST", "remove") => { o.remove(b()["id"].as_str().unwrap_or("")); Ok(json!({"ok": true})) } ("POST", "retry") => { o.retry(b()["id"].as_str().unwrap_or("")); kick(); Ok(json!({"ok": true})) } _ => Err("沒有這個動作".into()), } } // ---------- sending from this computer ---------- /// Ask this computer's post office: its brain's when it is a screen (`mirror`), else its own. pub fn ask(s: &crate::remote::Settings, mirror: bool, what: &str, method: &str, query: &[(&str, String)], body: &[u8]) -> Result { if mirror { return crate::remote::to_brain(s, method, &format!("/drop/{what}"), query, body, 60); } let q = query.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(); api(what, method, &q, body, &s.host_name, &me_id(s)) } /// Send a file from this computer. `sent` counts the bytes handed over (for a progress bar). pub fn send_file(s: &crate::remote::Settings, mirror: bool, path: &Path, to: &str, sent: &std::sync::atomic::AtomicU64) -> Result<(), String> { use std::sync::atomic::Ordering; let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let meta = std::fs::metadata(path).map_err(|_| format!("找不到「{name}」"))?; if meta.is_dir() { return Err(format!("「{name}」是資料夾,請先壓縮成一個檔案")); } if !mirror { let to_name = target_name(to).ok_or("帳號裡找不到這台裝置")?; office().add_file(path, to, &to_name, &s.host_name, &me_id(s))?; sent.store(meta.len(), Ordering::Relaxed); kick(); return Ok(()); } let id = ask(s, true, "new", "POST", &[], json!({"name": name, "bytes": meta.len(), "to": to}).to_string().as_bytes())?["id"].as_str().unwrap_or("").to_string(); let run = || -> Result<(), String> { let mut f = std::fs::File::open(path).map_err(|e| format!("讀不到「{name}」:{e}"))?; let mut at = 0u64; let mut stuck = 0; while at < meta.len() { let mut buf = vec![0u8; (CHUNK as u64).min(meta.len() - at) as usize]; f.seek(SeekFrom::Start(at)).and_then(|_| f.read_exact(&mut buf)).map_err(|e| format!("讀不到「{name}」:{e}"))?; match ask(s, true, "chunk", "POST", &[("id", id.clone()), ("at", at.to_string())], &buf) { Ok(v) => { let have = v["have"].as_u64().unwrap_or(at); stuck = if have > at { 0 } else { stuck + 1 }; at = have; } // A link that hiccups: a few more tries from where the brain says it is. Err(e) if only_for_now(&e) && stuck < 5 => { stuck += 1; std::thread::sleep(std::time::Duration::from_secs(2)); } Err(e) => return Err(e), } if stuck >= 6 { return Err("傳不過去:大腦一直沒有收下".into()); } sent.store(at, Ordering::Relaxed); } ask(s, true, "done", "POST", &[], json!({"id": id}).to_string().as_bytes()).map(|_| ()) }; run().inspect_err(|_| { let _ = ask(s, true, "remove", "POST", &[], json!({"id": id}).to_string().as_bytes()); }) } /// Send a few words from this computer. pub fn send_text(s: &crate::remote::Settings, mirror: bool, text: &str, to: &str) -> Result<(), String> { ask(s, mirror, "new", "POST", &[], json!({"text": text, "to": to}).to_string().as_bytes()).map(|_| ()) } #[cfg(test)] mod tests { use super::*; fn scratch(name: &str) -> (Office, PathBuf) { let root = std::env::temp_dir().join(format!("anybot-drops-{name}-{}", crate::httpd::random_hex(4))); let _ = std::fs::remove_dir_all(&root); (Office::at(root.join("data"), root.join("land")), root) } fn upload(o: &Office, name: &str, body: &[u8], to: &str, piece: usize) -> String { let id = o.begin(name, body.len() as u64, "", to, "那台", "筆電", "laptop").unwrap(); let mut at = 0; for c in body.chunks(piece) { at = o.chunk(&id, at, c).unwrap(); } o.finish(&id).unwrap(); id } /// The whole road: a screen uploads in pieces, the brain pushes to another computer, the /// link breaks half-way and goes on from where it was, and the file lands whole. #[test] fn a_file_goes_from_one_computer_to_another_through_a_bad_link() { let (brain, r1) = scratch("brain"); let (mini, r2) = scratch("mini"); let body: Vec = (0..(CHUNK * 2 + 12_345)).map(|i| (i % 251) as u8).collect(); let id = upload(&brain, "../../報告.pdf", &body, "mini", 700_000); // A piece that isn't the next one changes nothing. assert!(brain.chunk(&id, 0, b"x").is_err(), "an upload that is finished takes no more"); let calls = std::cell::Cell::new(0); let carry = |host: &str, args: &str, _who: &str| -> Result { assert_eq!(host, "mini"); calls.set(calls.get() + 1); // The third call never arrives. if calls.get() == 3 { return Err("目前離線".into()); } Ok(mini.take(&crate::tools::args_of(args))) }; brain.deliver("brain", &carry, &|_| panic!("not for the phone")); let p = brain.get(&id).unwrap(); assert_eq!((p.state.as_str(), p.note.as_str()), ("waiting", "目前離線"), "off for now: it waits, it didn't fail"); assert!(mini.received().is_empty()); // Not before its time. brain.deliver("brain", &carry, &|_| {}); assert_eq!(brain.get(&id).unwrap().state, "waiting"); brain.set(&id, |p| p.next_try = 0); brain.deliver("brain", &carry, &|_| {}); assert_eq!(brain.get(&id).unwrap().state, "done"); let got = mini.received(); assert_eq!(got.len(), 1); assert_eq!(got[0].name, "報告.pdf", "no path comes along with the name"); assert_eq!(std::fs::read(&got[0].path).unwrap(), body); assert!(Path::new(&got[0].path).starts_with(r2.join("land"))); assert!(!brain.bin(&id).exists(), "delivered: the brain keeps no copy"); // The second half was sent once (probe + 2 pieces, the second lost; probe again + 2 pieces). assert_eq!(calls.get(), 6); // The same parcel pushed again (a lost "got it") isn't a second file. assert_eq!(mini.take(&json!({"id": id, "name": "報告.pdf", "bytes": body.len(), "probe": true}))["done"], true); // A second file of the same name sits beside the first. let id2 = upload(&brain, "報告.pdf", b"another", "mini", 100); brain.deliver("brain", &carry, &|_| {}); assert_eq!(brain.get(&id2).unwrap().state, "done"); assert_eq!(mini.received()[0].name, "報告 (2).pdf"); assert_eq!(mini.take_fresh().len(), 2); let _ = std::fs::remove_dir_all(r1); let _ = std::fs::remove_dir_all(r2); } /// To the phone a parcel waits at the brain and is read in pieces; to the brain's own /// computer it is simply moved; words arrive as words. #[test] fn the_phone_downloads_and_the_brain_keeps_its_own() { let (brain, root) = scratch("phone"); let body = vec![7u8; 5000]; let id = upload(&brain, "照片.jpg", &body, PHONE, 2048); assert!(brain.read(&id, 0, 100).is_err(), "not before it is ready"); let told = std::cell::Cell::new(0); let nobody = |_: &str, _: &str, _: &str| -> Result { panic!("no computer involved") }; brain.deliver("brain", &nobody, &|_| told.set(told.get() + 1)); assert_eq!((brain.get(&id).unwrap().state.as_str(), told.get()), ("ready", 1)); let mut got = brain.read(&id, 0, 3000).unwrap(); assert_eq!(brain.get(&id).unwrap().state, "ready", "half read is not done"); got.extend(brain.read(&id, 3000, 3000).unwrap()); assert_eq!(got, body); assert_eq!(brain.get(&id).unwrap().state, "done"); assert!(brain.read(&id, 0, 10).is_ok(), "it can be downloaded again while it is kept"); // Told once, not at every round. brain.deliver("brain", &nobody, &|_| told.set(told.get() + 1)); assert_eq!(told.get(), 1); // From the phone to the brain's own computer. let id = brain.begin("筆記.txt", 3, "", "brain", "大腦", "手機", PHONE).unwrap(); brain.chunk(&id, 0, b"abc").unwrap(); assert!(brain.finish(&id).is_ok()); brain.deliver("brain", &nobody, &|_| {}); assert_eq!(brain.get(&id).unwrap().state, "done"); assert_eq!(std::fs::read(&brain.received()[0].path).unwrap(), b"abc"); // Words. let id = brain.begin("", 0, " https://example.com/很長的網址\n第二行 ", "brain", "大腦", "手機", PHONE).unwrap(); brain.deliver("brain", &nobody, &|_| {}); assert_eq!(brain.get(&id).unwrap().state, "done"); let r = &brain.received()[0]; assert_eq!((r.text.as_str(), r.name.as_str(), r.path.as_str()), ("https://example.com/很長的網址\n第二行", "https://example.com/很長的網址", "")); // What can't be sent says why. assert!(brain.begin("a", 1, "", "", "", "手機", PHONE).is_err()); assert!(brain.begin("a", 1, "", PHONE, "手機", "手機", PHONE).unwrap_err().contains("另一台")); assert!(brain.begin("a", 0, "", "brain", "大腦", "手機", PHONE).unwrap_err().contains("空的")); assert!(brain.begin("a", MAX_BYTES + 1, "", "brain", "大腦", "手機", PHONE).unwrap_err().contains("太大")); // An upload that stops short isn't finished, and more than promised is refused. let id = brain.begin("a.bin", 10, "", "brain", "大腦", "手機", PHONE).unwrap(); assert_eq!(brain.chunk(&id, 0, b"12345").unwrap(), 5); assert_eq!(brain.chunk(&id, 0, b"12345").unwrap(), 5, "the same piece twice is taken once"); assert!(brain.finish(&id).unwrap_err().contains("還沒傳完")); assert!(brain.chunk(&id, 5, b"1234567").is_err()); brain.remove(&id); assert!(brain.get(&id).is_none() && !brain.bin(&id).exists()); // Kept 7 days. let n = brain.list().len(); brain.prune(now_ms() + KEEP_MS + 1000); assert!(n > 0 && brain.list().is_empty()); let _ = std::fs::remove_dir_all(root); } /// A real send from a screen, through a running account server and brain (the road the /// window uses: `/api/sync/drop/…` in pieces): /// ANYBOT_DROP_STATE= ANYBOT_DROP_BRAIN= /// ANYBOT_DROP_TO= ANYBOT_DROP_FILE= cargo test live_send -- --ignored --nocapture #[test] #[ignore] fn live_send_from_a_screen() { let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("{k}")); let st: Value = serde_json::from_slice(&std::fs::read(env("ANYBOT_DROP_STATE")).unwrap()).unwrap(); let mut s: crate::remote::Settings = serde_json::from_value(st["remote"].clone()).unwrap(); s.brain_id = env("ANYBOT_DROP_BRAIN"); let to = env("ANYBOT_DROP_TO"); let t = ask(&s, true, "targets", "GET", &[], &[]).unwrap(); println!("targets: {}", t["targets"]); let sent = std::sync::atomic::AtomicU64::new(0); let file = PathBuf::from(env("ANYBOT_DROP_FILE")); let t0 = std::time::Instant::now(); send_file(&s, true, &file, &to, &sent).unwrap(); println!("handed over {} bytes in {:.2}s", sent.load(std::sync::atomic::Ordering::Relaxed), t0.elapsed().as_secs_f64()); send_text(&s, true, "從螢幕傳的一段字", &to).unwrap(); for _ in 0..80 { let l = ask(&s, true, "list", "GET", &[], &[]).unwrap(); let mine: Vec<&Value> = l["items"].as_array().unwrap().iter().filter(|p| p["from_id"] == s.host_id.as_str() && p["to"] == to.as_str()).take(2).collect(); if mine.len() == 2 && mine.iter().all(|p| matches!(p["state"].as_str(), Some("done" | "ready" | "failed"))) { for p in mine { println!("{} → {}: {} {}", p["name"], p["to_name"], p["state"], p["note"]); assert_ne!(p["state"], "failed"); } return; } std::thread::sleep(std::time::Duration::from_millis(250)); } panic!("not delivered in 20 s"); } /// What a computer refuses from a brain, and a refusal that is a "no" (not "later"). #[test] fn a_computer_takes_only_what_is_sound() { let (mini, root) = scratch("sound"); let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b); assert_eq!(mini.take(&json!({"id": "../x", "bytes": 3, "at": 0, "data": b64(b"abc")}))["ok"], false); assert_eq!(mini.take(&json!({"id": "a1", "bytes": 0, "at": 0, "data": b64(b"abc")}))["ok"], false); // More than promised: refused, and nothing is left behind. assert_eq!(mini.take(&json!({"id": "a2", "name": "x", "bytes": 2, "at": 0, "data": b64(b"abc")}))["ok"], false); assert_eq!(mini.take(&json!({"id": "a2", "bytes": 2, "probe": true}))["have"], 0); // A piece out of place says how much is here. assert_eq!(mini.take(&json!({"id": "a3", "name": ".ssh/../.zshrc", "bytes": 6, "at": 0, "data": b64(b"abc")}))["have"], 3); let v = mini.take(&json!({"id": "a3", "bytes": 6, "at": 0, "data": b64(b"abc")})); assert_eq!((v["ok"].as_bool(), v["have"].as_u64()), (Some(false), Some(3))); assert_eq!(mini.take(&json!({"id": "a3", "name": ".ssh/../.zshrc", "bytes": 6, "at": 3, "data": b64(b"def")}))["done"], true); let r = &mini.received()[0]; assert_eq!(r.name, "zshrc", "never a hidden file, never outside the folder"); assert!(Path::new(&r.path).starts_with(root.join("land"))); assert_eq!(safe_name("a/b\\c:d.txt"), "cd.txt"); assert_eq!(safe_name("..."), "檔案"); assert!(safe_name(&format!("{}.tar.gz", "長".repeat(300))).ends_with(".gz")); let (brain, r2) = scratch("refused"); let id = upload(&brain, "a.txt", b"hello", "mini", 10); brain.deliver("brain", &|_, _, _| Err("這台電腦只收它自己的大腦傳來的東西".into()), &|_| {}); assert_eq!(brain.get(&id).unwrap().state, "failed"); // Tried again when the person says so. brain.retry(&id); brain.deliver("brain", &|_, a, _| Ok(mini.take(&crate::tools::args_of(a))), &|_| {}); assert_eq!(brain.get(&id).unwrap().state, "done"); // An older AnyBot on the other side: said in words, and tried again later. let id = upload(&brain, "b.txt", b"hello", "mini", 10); brain.deliver("brain", &|_, _, _| Err("那台電腦:這個工具不能遠端使用".into()), &|_| {}); let p = brain.get(&id).unwrap(); assert!(p.state == "waiting" && p.note.contains("要先更新"), "{p:?}"); // Restarted in the middle: a half upload is gone, a delivery starts again. brain.begin("c.bin", 10, "", "mini", "那台", "筆電", "laptop").unwrap(); brain.set(&id, |p| p.state = "sending".into()); let again = Office::at(brain.dir.clone(), brain.land.clone()); let mut left: Vec<(String, String)> = again.list().into_iter().map(|p| (p.name, p.state)).collect(); left.sort(); assert_eq!(left, vec![("a.txt".to_string(), "done".to_string()), ("b.txt".to_string(), "waiting".to_string())]); let _ = std::fs::remove_dir_all(root); let _ = std::fs::remove_dir_all(r2); } }