//! Raw-filesystem media store. Uploads are streamed to `
/tmp`, hashed with blake3 as
//! they arrive, then renamed to `/files/.`. Files are served by name, so a
//! file's name is its content and a copy with the same bytes is stored once.
pub mod webm;
use std::collections::HashSet;
use std::fmt::Display;
use std::io;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use bytes::Bytes;
use tokio::io::AsyncWriteExt;
/// Largest upload taken, and largest recording take, in bytes.
pub const MAX_BYTES: u64 = 4 << 30;
/// Stores media files under one directory. Recording takes live under `rec`, see [`Media::joined_take`].
#[derive(Debug)]
pub struct Media {
dir: PathBuf,
/// Serialises joins, so two of one take never write the same file.
joins: tokio::sync::Mutex<()>,
}
/// Why an upload was not stored.
#[derive(Debug)]
pub enum StoreError {
/// The body is bigger than [`MAX_BYTES`].
TooLarge,
/// Reading the body or writing the file failed.
Failed(anyhow::Error),
}
impl Media {
/// Opens the store at `$NOTE_MEDIA`, or `media` when that is unset, creating its folders.
pub fn open() -> io::Result {
let dir = PathBuf::from(std::env::var("NOTE_MEDIA").unwrap_or_else(|_| "media".to_owned()));
std::fs::create_dir_all(dir.join("files"))?;
std::fs::create_dir_all(dir.join("tmp"))?;
std::fs::create_dir_all(dir.join("rec"))?;
Ok(Self { dir, joins: tokio::sync::Mutex::new(()) })
}
/// Creates a new take of `note` and answers its id. Its folder is `rec/`.
pub async fn new_take(&self, note: &str) -> io::Result {
let id = session_id(note);
tokio::fs::create_dir(self.take_dir(&id)).await?;
Ok(id)
}
/// The folder of take `id`, which holds its parts.
pub fn take_dir(&self, id: &str) -> PathBuf {
self.dir.join("rec").join(id)
}
/// The ids of every take on disk.
pub async fn takes(&self) -> io::Result> {
let mut ids = Vec::new();
let mut entries = tokio::fs::read_dir(self.dir.join("rec")).await?;
while let Some(entry) = entries.next_entry().await? {
if let Ok(id) = entry.file_name().into_string()
&& valid_session(&id)
{
ids.push(id);
}
}
Ok(ids)
}
/// Joins the closed parts of take `id` into `joined.weba`, unless `joined.key` already
/// records the same parts. A part in `attached` is still being written and is left out.
/// Answers the joined file and its join key, or `None` when no closed part has audio.
/// The join is written to a temporary name and renamed, the key after the file, so a crash
/// between the two only means the next request joins again.
pub async fn joined_take(&self, id: &str, attached: &HashSet) -> anyhow::Result> {
let _lock = self.joins.lock().await;
let dir = self.take_dir(id);
let closed: Vec<(u32, u64)> = parts_in(&dir)?.into_iter().filter(|(n, _)| !attached.contains(n)).collect();
if closed.is_empty() {
return Ok(None);
}
let key = join_key(&closed);
let joined = dir.join("joined.weba");
if tokio::fs::read_to_string(dir.join("joined.key")).await.is_ok_and(|stored| stored == key) && joined.is_file() {
return Ok(Some((joined, key)));
}
let parts: Vec = closed.iter().map(|(n, _)| part_file(&dir, *n)).collect();
let tmp = dir.join(format!("joined-{}.tmp", uuid::Uuid::now_v7()));
let out = tmp.clone();
if let Err(err) = tokio::task::spawn_blocking(move || webm::join(&parts, &out)).await? {
let _ = tokio::fs::remove_file(&tmp).await;
eprintln!("joining take {id} failed: {err:#}");
return Ok(None);
}
tokio::fs::rename(&tmp, &joined).await?;
let key_tmp = dir.join(format!("joined-{}.tmp", uuid::Uuid::now_v7()));
tokio::fs::write(&key_tmp, &key).await?;
tokio::fs::rename(&key_tmp, dir.join("joined.key")).await?;
Ok(Some((joined, key)))
}
/// Stores the body under its blake3 hash and `ext` (from [`ext_of`]). Answers with the
/// stored file name, `.`. The temporary file is removed on any error.
pub async fn store(&self, ext: &str, mut body: B) -> Result
where
B: http_body::Body + Unpin,
B::Error: Display,
{
let tmp = self.dir.join("tmp").join(uuid::Uuid::now_v7().to_string());
let hash = match write_hashed(&tmp, &mut body).await {
Ok(hash) => hash,
Err(err) => {
let _ = tokio::fs::remove_file(&tmp).await;
return Err(err);
}
};
let name = format!("{hash}.{ext}");
// Renaming over an identical file leaves the same bytes under the same name.
if let Err(err) = tokio::fs::rename(&tmp, self.path(&name)).await {
let _ = tokio::fs::remove_file(&tmp).await;
return Err(failed(err));
}
Ok(name)
}
/// Where the file `name` lives. Check it with [`valid_name`] before serving.
pub fn path(&self, name: &str) -> PathBuf {
self.dir.join("files").join(name)
}
/// The names of the stored files.
pub async fn list(&self) -> io::Result> {
let mut names = Vec::new();
let mut entries = tokio::fs::read_dir(self.dir.join("files")).await?;
while let Some(entry) = entries.next_entry().await? {
if let Ok(name) = entry.file_name().into_string()
&& valid_name(&name)
{
names.push(name);
}
}
Ok(names)
}
}
/// Streams `body` into the file at `tmp`, returning the blake3 hash of the bytes written.
async fn write_hashed(tmp: &Path, body: &mut B) -> Result
where
B: http_body::Body + Unpin,
B::Error: Display,
{
let mut file = tokio::fs::File::create(tmp).await.map_err(failed)?;
let mut hasher = blake3::Hasher::new();
let mut len: u64 = 0;
while let Some(frame) = std::future::poll_fn(|cx| http_body::Body::poll_frame(Pin::new(&mut *body), cx)).await {
let frame = frame.map_err(|err| StoreError::Failed(anyhow::anyhow!("{err}")))?;
let Ok(chunk) = frame.into_data() else { continue };
len += chunk.len() as u64;
if len > MAX_BYTES {
return Err(StoreError::TooLarge);
}
hasher.update(&chunk);
file.write_all(&chunk).await.map_err(failed)?;
}
file.flush().await.map_err(failed)?;
Ok(hasher.finalize().to_hex().to_string())
}
fn failed(err: io::Error) -> StoreError {
StoreError::Failed(err.into())
}
/// A new take id: `..weba`. The uuid sorts by creation time.
pub fn session_id(note: &str) -> String {
format!("{note}.{}.weba", uuid::Uuid::now_v7())
}
/// Whether `id` is a take id from [`session_id`]: a note of 1 to 64 ASCII letters, digits or
/// `-`, a uuid-shaped part of 1 to 36 hex digits or `-`, and the `weba` extension. Dots are the
/// only separators, so a path with `/` or `..` is refused.
pub fn valid_session(id: &str) -> bool {
let mut parts = id.split('.');
let (Some(note), Some(uuid), Some(ext), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
return false;
};
(1..=64).contains(¬e.len())
&& note.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
&& (1..=36).contains(&uuid.len())
&& uuid.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-')
&& ext == "weba"
}
/// The file of part `n` of a take folder: `.weba`, the raw MediaRecorder stream from 0.
pub fn part_file(dir: &Path, n: u32) -> PathBuf {
dir.join(format!("{n}.weba"))
}
/// The parts of a take folder as `(number, bytes)`, in part order. Only `.weba` files are parts,
/// so the joined file and temporary files are skipped.
pub fn parts_in(dir: &Path) -> io::Result> {
let mut parts = Vec::new();
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let Some(n) = entry.file_name().to_str().and_then(part_number) else { continue };
parts.push((n, entry.metadata()?.len()));
}
parts.sort_unstable();
Ok(parts)
}
/// The bytes of all parts of a take folder.
pub fn take_bytes(dir: &Path) -> io::Result {
Ok(parts_in(dir)?.iter().map(|(_, len)| len).sum())
}
/// The part number of a file name `.weba`.
fn part_number(name: &str) -> Option {
let digits = name.strip_suffix(".weba")?;
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
digits.parse().ok()
}
/// The join key of a take's closed parts: each part as `:`, comma separated. A join
/// is current while the key of the parts on disk equals the key it was joined under.
pub fn join_key(parts: &[(u32, u64)]) -> String {
parts.iter().map(|(n, len)| format!("{n}:{len}")).collect::>().join(",")
}
/// The lowercase extension of a file name, or `bin` when there is none that is 1 to 10
/// ASCII letters or digits.
pub fn ext_of(name: &str) -> String {
let ext = Path::new(name)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
if is_ext(&ext) { ext } else { "bin".to_owned() }
}
/// Whether `ext` is 1 to 10 lowercase ASCII letters or digits.
fn is_ext(ext: &str) -> bool {
(1..=10).contains(&ext.len()) && ext.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
}
/// The content type served inline for `ext`. `None` for every other type, which is served
/// as a download. SVG and HTML are never inline: they can run script.
pub fn content_type(ext: &str) -> Option<&'static str> {
Some(match ext {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"avif" => "image/avif",
"bmp" => "image/bmp",
"mp3" => "audio/mpeg",
"m4a" => "audio/mp4",
"wav" => "audio/wav",
"flac" => "audio/flac",
"aac" => "audio/aac",
"ogg" | "oga" | "opus" => "audio/ogg",
"weba" => "audio/webm",
"mp4" | "m4v" => "video/mp4",
"webm" => "video/webm",
"mov" => "video/quicktime",
"ogv" => "video/ogg",
"pdf" => "application/pdf",
_ => return None,
})
}
/// Whether `name` is exactly a 64-digit lowercase hex blake3 hash, a dot and a valid
/// extension. Anything else, such as a path with `/` or `..`, is refused.
pub fn valid_name(name: &str) -> bool {
let Some((hash, ext)) = name.split_once('.') else {
return false;
};
hash.len() == 64
&& hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
&& is_ext(ext)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_and_extensions() {
assert_eq!(ext_of("Photo.JPG"), "jpg");
assert_eq!(ext_of("notes"), "bin");
assert_eq!(ext_of("bad.e x"), "bin");
assert_eq!(ext_of("long.abcdefghijk"), "bin");
let hash = "a".repeat(64);
assert!(valid_name(&format!("{hash}.png")));
assert!(!valid_name(&format!("{hash}.PNG")));
assert!(!valid_name(&format!("../{hash}.png")));
assert!(!valid_name(&format!("{}.png", "A".repeat(64))));
assert!(!valid_name(&format!("{}.png", "a".repeat(63))));
}
#[test]
fn session_ids() {
let id = session_id("my-note");
assert!(valid_session(&id));
assert!(!valid_session("my-note.abc.webm"));
assert!(!valid_session("my-note.abc.weba.weba"));
assert!(!valid_session("../x.abc.weba"));
assert!(!valid_session("a/b.abc.weba"));
assert!(!valid_session("note.abc.WEBA"));
assert!(!valid_session(&format!("{}.abc.weba", "n".repeat(65))));
}
#[test]
fn join_keys() {
assert_eq!(join_key(&[(0, 10), (2, 5)]), "0:10,2:5");
assert_eq!(join_key(&[]), "");
}
}