forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

media.rs321 lines, 12.0 KiBHistoryRawDownload
1//! Raw-filesystem media store. Uploads are streamed to `<dir>/tmp`, hashed with blake3 as
2//! they arrive, then renamed to `<dir>/files/<hash>.<ext>`. Files are served by name, so a
3//! file's name is its content and a copy with the same bytes is stored once.
4
5pub mod webm;
6
7use std::collections::HashSet;
8use std::fmt::Display;
9use std::io;
10use std::path::{Path, PathBuf};
11use std::pin::Pin;
12
13use bytes::Bytes;
14use tokio::io::AsyncWriteExt;
15
16/// Largest upload taken, and largest recording take, in bytes.
17pub const MAX_BYTES: u64 = 4 << 30;
18
19/// Stores media files under one directory. Recording takes live under `rec`, see [`Media::joined_take`].
20#[derive(Debug)]
21pub struct Media {
22 dir: PathBuf,
23 /// Serialises joins, so two of one take never write the same file.
24 joins: tokio::sync::Mutex<()>,
25}
26
27/// Why an upload was not stored.
28#[derive(Debug)]
29pub enum StoreError {
30 /// The body is bigger than [`MAX_BYTES`].
31 TooLarge,
32 /// Reading the body or writing the file failed.
33 Failed(anyhow::Error),
34}
35
36impl Media {
37 /// Opens the store at `$NOTE_MEDIA`, or `media` when that is unset, creating its folders.
38 pub fn open() -> io::Result<Self> {
39 let dir = PathBuf::from(std::env::var("NOTE_MEDIA").unwrap_or_else(|_| "media".to_owned()));
40 std::fs::create_dir_all(dir.join("files"))?;
41 std::fs::create_dir_all(dir.join("tmp"))?;
42 std::fs::create_dir_all(dir.join("rec"))?;
43 Ok(Self { dir, joins: tokio::sync::Mutex::new(()) })
44 }
45
46 /// Creates a new take of `note` and answers its id. Its folder is `rec/<id>`.
47 pub async fn new_take(&self, note: &str) -> io::Result<String> {
48 let id = session_id(note);
49 tokio::fs::create_dir(self.take_dir(&id)).await?;
50 Ok(id)
51 }
52
53 /// The folder of take `id`, which holds its parts.
54 pub fn take_dir(&self, id: &str) -> PathBuf {
55 self.dir.join("rec").join(id)
56 }
57
58 /// The ids of every take on disk.
59 pub async fn takes(&self) -> io::Result<Vec<String>> {
60 let mut ids = Vec::new();
61 let mut entries = tokio::fs::read_dir(self.dir.join("rec")).await?;
62 while let Some(entry) = entries.next_entry().await? {
63 if let Ok(id) = entry.file_name().into_string()
64 && valid_session(&id)
65 {
66 ids.push(id);
67 }
68 }
69 Ok(ids)
70 }
71
72 /// Joins the closed parts of take `id` into `joined.weba`, unless `joined.key` already
73 /// records the same parts. A part in `attached` is still being written and is left out.
74 /// Answers the joined file and its join key, or `None` when no closed part has audio.
75 /// The join is written to a temporary name and renamed, the key after the file, so a crash
76 /// between the two only means the next request joins again.
77 pub async fn joined_take(&self, id: &str, attached: &HashSet<u32>) -> anyhow::Result<Option<(PathBuf, String)>> {
78 let _lock = self.joins.lock().await;
79 let dir = self.take_dir(id);
80 let closed: Vec<(u32, u64)> = parts_in(&dir)?.into_iter().filter(|(n, _)| !attached.contains(n)).collect();
81 if closed.is_empty() {
82 return Ok(None);
83 }
84 let key = join_key(&closed);
85 let joined = dir.join("joined.weba");
86 if tokio::fs::read_to_string(dir.join("joined.key")).await.is_ok_and(|stored| stored == key) && joined.is_file() {
87 return Ok(Some((joined, key)));
88 }
89 let parts: Vec<PathBuf> = closed.iter().map(|(n, _)| part_file(&dir, *n)).collect();
90 let tmp = dir.join(format!("joined-{}.tmp", uuid::Uuid::now_v7()));
91 let out = tmp.clone();
92 if let Err(err) = tokio::task::spawn_blocking(move || webm::join(&parts, &out)).await? {
93 let _ = tokio::fs::remove_file(&tmp).await;
94 eprintln!("joining take {id} failed: {err:#}");
95 return Ok(None);
96 }
97 tokio::fs::rename(&tmp, &joined).await?;
98 let key_tmp = dir.join(format!("joined-{}.tmp", uuid::Uuid::now_v7()));
99 tokio::fs::write(&key_tmp, &key).await?;
100 tokio::fs::rename(&key_tmp, dir.join("joined.key")).await?;
101 Ok(Some((joined, key)))
102 }
103
104 /// Stores the body under its blake3 hash and `ext` (from [`ext_of`]). Answers with the
105 /// stored file name, `<hash>.<ext>`. The temporary file is removed on any error.
106 pub async fn store<B>(&self, ext: &str, mut body: B) -> Result<String, StoreError>
107 where
108 B: http_body::Body<Data = Bytes> + Unpin,
109 B::Error: Display,
110 {
111 let tmp = self.dir.join("tmp").join(uuid::Uuid::now_v7().to_string());
112 let hash = match write_hashed(&tmp, &mut body).await {
113 Ok(hash) => hash,
114 Err(err) => {
115 let _ = tokio::fs::remove_file(&tmp).await;
116 return Err(err);
117 }
118 };
119 let name = format!("{hash}.{ext}");
120 // Renaming over an identical file leaves the same bytes under the same name.
121 if let Err(err) = tokio::fs::rename(&tmp, self.path(&name)).await {
122 let _ = tokio::fs::remove_file(&tmp).await;
123 return Err(failed(err));
124 }
125 Ok(name)
126 }
127
128 /// Where the file `name` lives. Check it with [`valid_name`] before serving.
129 pub fn path(&self, name: &str) -> PathBuf {
130 self.dir.join("files").join(name)
131 }
132
133 /// The names of the stored files.
134 pub async fn list(&self) -> io::Result<Vec<String>> {
135 let mut names = Vec::new();
136 let mut entries = tokio::fs::read_dir(self.dir.join("files")).await?;
137 while let Some(entry) = entries.next_entry().await? {
138 if let Ok(name) = entry.file_name().into_string()
139 && valid_name(&name)
140 {
141 names.push(name);
142 }
143 }
144 Ok(names)
145 }
146}
147
148/// Streams `body` into the file at `tmp`, returning the blake3 hash of the bytes written.
149async fn write_hashed<B>(tmp: &Path, body: &mut B) -> Result<String, StoreError>
150where
151 B: http_body::Body<Data = Bytes> + Unpin,
152 B::Error: Display,
153{
154 let mut file = tokio::fs::File::create(tmp).await.map_err(failed)?;
155 let mut hasher = blake3::Hasher::new();
156 let mut len: u64 = 0;
157 while let Some(frame) = std::future::poll_fn(|cx| http_body::Body::poll_frame(Pin::new(&mut *body), cx)).await {
158 let frame = frame.map_err(|err| StoreError::Failed(anyhow::anyhow!("{err}")))?;
159 let Ok(chunk) = frame.into_data() else { continue };
160 len += chunk.len() as u64;
161 if len > MAX_BYTES {
162 return Err(StoreError::TooLarge);
163 }
164 hasher.update(&chunk);
165 file.write_all(&chunk).await.map_err(failed)?;
166 }
167 file.flush().await.map_err(failed)?;
168 Ok(hasher.finalize().to_hex().to_string())
169}
170
171fn failed(err: io::Error) -> StoreError {
172 StoreError::Failed(err.into())
173}
174
175/// A new take id: `<note>.<uuid v7>.weba`. The uuid sorts by creation time.
176pub fn session_id(note: &str) -> String {
177 format!("{note}.{}.weba", uuid::Uuid::now_v7())
178}
179
180/// Whether `id` is a take id from [`session_id`]: a note of 1 to 64 ASCII letters, digits or
181/// `-`, a uuid-shaped part of 1 to 36 hex digits or `-`, and the `weba` extension. Dots are the
182/// only separators, so a path with `/` or `..` is refused.
183pub fn valid_session(id: &str) -> bool {
184 let mut parts = id.split('.');
185 let (Some(note), Some(uuid), Some(ext), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
186 return false;
187 };
188 (1..=64).contains(&note.len())
189 && note.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
190 && (1..=36).contains(&uuid.len())
191 && uuid.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-')
192 && ext == "weba"
193}
194
195/// The file of part `n` of a take folder: `<n>.weba`, the raw MediaRecorder stream from 0.
196pub fn part_file(dir: &Path, n: u32) -> PathBuf {
197 dir.join(format!("{n}.weba"))
198}
199
200/// The parts of a take folder as `(number, bytes)`, in part order. Only `<n>.weba` files are parts,
201/// so the joined file and temporary files are skipped.
202pub fn parts_in(dir: &Path) -> io::Result<Vec<(u32, u64)>> {
203 let mut parts = Vec::new();
204 for entry in std::fs::read_dir(dir)? {
205 let entry = entry?;
206 let Some(n) = entry.file_name().to_str().and_then(part_number) else { continue };
207 parts.push((n, entry.metadata()?.len()));
208 }
209 parts.sort_unstable();
210 Ok(parts)
211}
212
213/// The bytes of all parts of a take folder.
214pub fn take_bytes(dir: &Path) -> io::Result<u64> {
215 Ok(parts_in(dir)?.iter().map(|(_, len)| len).sum())
216}
217
218/// The part number of a file name `<n>.weba`.
219fn part_number(name: &str) -> Option<u32> {
220 let digits = name.strip_suffix(".weba")?;
221 if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
222 return None;
223 }
224 digits.parse().ok()
225}
226
227/// The join key of a take's closed parts: each part as `<n>:<bytes>`, comma separated. A join
228/// is current while the key of the parts on disk equals the key it was joined under.
229pub fn join_key(parts: &[(u32, u64)]) -> String {
230 parts.iter().map(|(n, len)| format!("{n}:{len}")).collect::<Vec<_>>().join(",")
231}
232
233/// The lowercase extension of a file name, or `bin` when there is none that is 1 to 10
234/// ASCII letters or digits.
235pub fn ext_of(name: &str) -> String {
236 let ext = Path::new(name)
237 .extension()
238 .and_then(|e| e.to_str())
239 .unwrap_or("")
240 .to_ascii_lowercase();
241 if is_ext(&ext) { ext } else { "bin".to_owned() }
242}
243
244/// Whether `ext` is 1 to 10 lowercase ASCII letters or digits.
245fn is_ext(ext: &str) -> bool {
246 (1..=10).contains(&ext.len()) && ext.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
247}
248
249/// The content type served inline for `ext`. `None` for every other type, which is served
250/// as a download. SVG and HTML are never inline: they can run script.
251pub fn content_type(ext: &str) -> Option<&'static str> {
252 Some(match ext {
253 "png" => "image/png",
254 "jpg" | "jpeg" => "image/jpeg",
255 "gif" => "image/gif",
256 "webp" => "image/webp",
257 "avif" => "image/avif",
258 "bmp" => "image/bmp",
259 "mp3" => "audio/mpeg",
260 "m4a" => "audio/mp4",
261 "wav" => "audio/wav",
262 "flac" => "audio/flac",
263 "aac" => "audio/aac",
264 "ogg" | "oga" | "opus" => "audio/ogg",
265 "weba" => "audio/webm",
266 "mp4" | "m4v" => "video/mp4",
267 "webm" => "video/webm",
268 "mov" => "video/quicktime",
269 "ogv" => "video/ogg",
270 "pdf" => "application/pdf",
271 _ => return None,
272 })
273}
274
275/// Whether `name` is exactly a 64-digit lowercase hex blake3 hash, a dot and a valid
276/// extension. Anything else, such as a path with `/` or `..`, is refused.
277pub fn valid_name(name: &str) -> bool {
278 let Some((hash, ext)) = name.split_once('.') else {
279 return false;
280 };
281 hash.len() == 64
282 && hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
283 && is_ext(ext)
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 #[test]
291 fn names_and_extensions() {
292 assert_eq!(ext_of("Photo.JPG"), "jpg");
293 assert_eq!(ext_of("notes"), "bin");
294 assert_eq!(ext_of("bad.e x"), "bin");
295 assert_eq!(ext_of("long.abcdefghijk"), "bin");
296 let hash = "a".repeat(64);
297 assert!(valid_name(&format!("{hash}.png")));
298 assert!(!valid_name(&format!("{hash}.PNG")));
299 assert!(!valid_name(&format!("../{hash}.png")));
300 assert!(!valid_name(&format!("{}.png", "A".repeat(64))));
301 assert!(!valid_name(&format!("{}.png", "a".repeat(63))));
302 }
303
304 #[test]
305 fn session_ids() {
306 let id = session_id("my-note");
307 assert!(valid_session(&id));
308 assert!(!valid_session("my-note.abc.webm"));
309 assert!(!valid_session("my-note.abc.weba.weba"));
310 assert!(!valid_session("../x.abc.weba"));
311 assert!(!valid_session("a/b.abc.weba"));
312 assert!(!valid_session("note.abc.WEBA"));
313 assert!(!valid_session(&format!("{}.abc.weba", "n".repeat(65))));
314 }
315
316 #[test]
317 fn join_keys() {
318 assert_eq!(join_key(&[(0, 10), (2, 5)]), "0:10,2:5");
319 assert_eq!(join_key(&[]), "");
320 }
321}