Dezio/src/hosted.rs

102 lines
3.8 KiB
Rust

//! Files too big for Discord, kept on the bot's own web server for a few hours so people can download them or
//! watch/listen in the browser: `data/hosted/<token>/<name>` is served at `/f/<token>/<name>` (the token is a random
//! 64-bit number, so a link only works for whoever was given it). Old files are deleted by [`start_cleanup`].
use crate::paths;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
/// How long a hosted file is kept.
pub const TTL: Duration = Duration::from_secs(6 * 60 * 60);
/// Everything hosted together never takes more than this much disk; the oldest go first.
const MAX_TOTAL: u64 = 3 * 1024 * 1024 * 1024;
/// The biggest single file we will host.
pub const MAX_FILE: u64 = 1024 * 1024 * 1024;
pub fn dir() -> PathBuf {
let d = paths::data(&["hosted"]);
let _ = std::fs::create_dir_all(&d);
d
}
/// The address people open (the dashboard's public address).
pub fn base_url() -> String {
std::env::var("DASHBOARD_URL").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| "http://192.168.1.71:8080".into()).trim_end_matches('/').to_string()
}
/// Copy `src` into the hosted folder as `name` and give back its public link.
pub fn store(src: &Path, name: &str) -> std::io::Result<String> {
let name = crate::ui::file_name(name);
let token = format!("{:016x}", rand::random::<u64>());
let folder = dir().join(&token);
std::fs::create_dir_all(&folder)?;
std::fs::copy(src, folder.join(&name))?;
prune();
Ok(format!("{}/f/{token}/{name}", base_url()))
}
fn folder_size(p: &Path) -> u64 {
std::fs::read_dir(p).map(|rd| rd.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum()).unwrap_or(0)
}
/// Delete expired folders, then the oldest ones while over the disk budget.
pub fn prune() {
let Ok(rd) = std::fs::read_dir(dir()) else { return };
let mut keep: Vec<(SystemTime, u64, PathBuf)> = Vec::new();
for e in rd.flatten() {
let path = e.path();
let Ok(meta) = e.metadata() else { continue };
let made = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
if made.elapsed().unwrap_or_default() > TTL {
let _ = std::fs::remove_dir_all(&path);
} else {
keep.push((made, folder_size(&path), path));
}
}
keep.sort_by_key(|k| k.0);
let mut total: u64 = keep.iter().map(|k| k.1).sum();
for (_, size, path) in keep {
if total <= MAX_TOTAL {
break;
}
let _ = std::fs::remove_dir_all(path);
total = total.saturating_sub(size);
}
}
/// Clean up now and every ten minutes.
pub fn start_cleanup() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
tokio::spawn(async {
loop {
prune();
tokio::time::sleep(Duration::from_secs(600)).await;
}
});
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_stored_file_gets_a_link_and_old_ones_expire() {
let tmp = std::env::temp_dir().join(format!("dezio-host-{}", std::process::id()));
std::fs::create_dir_all(&tmp).unwrap();
let src = tmp.join("a.bin");
std::fs::write(&src, b"hello").unwrap();
let url = store(&src, "My Video (1).mp4").unwrap();
assert!(url.contains("/f/") && url.ends_with("My_Video__1.mp4"), "{url}");
let token = url.rsplit('/').nth(1).unwrap();
let stored = dir().join(token);
assert!(stored.exists());
// age it past the time limit
let old = SystemTime::now() - TTL - Duration::from_secs(60);
let f = std::fs::File::open(&stored).unwrap();
f.set_modified(old).unwrap();
prune();
assert!(!stored.exists(), "expired files are removed");
let _ = std::fs::remove_dir_all(tmp);
}
}