| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | pub mod webm; |
| 6 | |
| 7 | use std::collections::HashSet; |
| 8 | use std::fmt::Display; |
| 9 | use std::io; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::pin::Pin; |
| 12 | |
| 13 | use bytes::Bytes; |
| 14 | use tokio::io::AsyncWriteExt; |
| 15 | |
| 16 | |
| 17 | pub const MAX_BYTES: u64 = 4 << 30; |
| 18 | |
| 19 | |
| 20 | #[derive(Debug)] |
| 21 | pub struct Media { |
| 22 | dir: PathBuf, |
| 23 | |
| 24 | joins: tokio::sync::Mutex<()>, |
| 25 | } |
| 26 | |
| 27 | |
| 28 | #[derive(Debug)] |
| 29 | pub enum StoreError { |
| 30 | |
| 31 | TooLarge, |
| 32 | |
| 33 | Failed(anyhow::Error), |
| 34 | } |
| 35 | |
| 36 | impl Media { |
| 37 | |
| 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 | |
| 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 | |
| 54 | pub fn take_dir(&self, id: &str) -> PathBuf { |
| 55 | self.dir.join("rec").join(id) |
| 56 | } |
| 57 | |
| 58 | |
| 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 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 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 | |
| 105 | |
| 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 | |
| 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 | |
| 129 | pub fn path(&self, name: &str) -> PathBuf { |
| 130 | self.dir.join("files").join(name) |
| 131 | } |
| 132 | |
| 133 | |
| 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 | |
| 149 | async fn write_hashed<B>(tmp: &Path, body: &mut B) -> Result<String, StoreError> |
| 150 | where |
| 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 | |
| 171 | fn failed(err: io::Error) -> StoreError { |
| 172 | StoreError::Failed(err.into()) |
| 173 | } |
| 174 | |
| 175 | |
| 176 | pub fn session_id(note: &str) -> String { |
| 177 | format!("{note}.{}.weba", uuid::Uuid::now_v7()) |
| 178 | } |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | pub 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(¬e.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 | |
| 196 | pub fn part_file(dir: &Path, n: u32) -> PathBuf { |
| 197 | dir.join(format!("{n}.weba")) |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | pub 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 | |
| 214 | pub fn take_bytes(dir: &Path) -> io::Result<u64> { |
| 215 | Ok(parts_in(dir)?.iter().map(|(_, len)| len).sum()) |
| 216 | } |
| 217 | |
| 218 | |
| 219 | fn 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 | |
| 228 | |
| 229 | pub fn join_key(parts: &[(u32, u64)]) -> String { |
| 230 | parts.iter().map(|(n, len)| format!("{n}:{len}")).collect::<Vec<_>>().join(",") |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | pub 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 | |
| 245 | fn 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 | |
| 250 | |
| 251 | pub 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 | |
| 276 | |
| 277 | pub 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)] |
| 287 | mod 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 | } |