//! Media routes: POST /media stores a raw upload, and GET /media/{file} serves it back with //! HTTP Range support, so audio and video can seek. GET /media/rec/{session} serves a recording //! take, and GET /media/live takes the audio of a recording over a WebSocket. use std::io::SeekFrom; use std::path::Path; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use std::time::Duration; use bytes::Bytes; use http_body::Frame; use tokio::io::{AsyncRead, AsyncSeekExt, AsyncWriteExt, ReadBuf}; use tokio::sync::oneshot; use topcoat::{ Result, context::{Cx, app_context}, router::{ Body, Method, StatusCode, header, path_param, query_params, content::websocket::{Message, WebSocket, WebSocketUpgrade}, error::{content_too_large, not_found}, request::{headers, method}, response::Response, route, }, }; use crate::hub::{Attachment, Detach, Hub}; use crate::media::{MAX_BYTES, Media, StoreError, content_type, ext_of, part_file, take_bytes, valid_name, valid_session}; use crate::store::Store; /// Bytes read from disk per response frame. const CHUNK_SIZE: usize = 64 * 1024; /// Largest frame a recording socket takes: a chunk can grow large after a long retry. const MAX_FRAME: usize = 16 << 20; /// Silence after which a recording socket counts as disconnected. const FRAME_WAIT: Duration = Duration::from_secs(5); /// Cache-Control of a stored file, which never changes under its name. const IMMUTABLE: &str = "public, max-age=31536000, immutable"; /// The `name` parameter of an upload: the original file name. #[query_params(error = bad_request)] pub struct MediaQuery { /// The file's name as the user chose it. Only its extension is kept. pub name: Option, } /// The parameters of a recording socket. `part` is text so a bad one is refused on the socket. #[query_params(error = bad_request)] pub struct LiveQuery { /// A note to start a new take of. pub note: Option, /// A take to continue, or to reconnect to with `part`. pub session: Option, /// The part of `session` to reconnect to. pub part: Option, } path_param!(file); path_param!(session); /// POST /media?name=...: stores the raw request body and answers with its URL. #[route(POST "/media")] pub async fn upload_media(cx: &Cx, body: Body) -> Result { let media = app_context::>(cx); let name = query_params::(cx)?.name.clone().unwrap_or_default(); match media.store(&ext_of(&name), body).await { Ok(file) => Ok(format!("/media/{file}")), Err(StoreError::TooLarge) => Err(content_too_large().into()), Err(StoreError::Failed(err)) => Err(topcoat::Error::from_anyhow(err)), } } /// GET /media/{file}: a stored file, inline when its type is safe to show and a download /// otherwise. HEAD gets the headers alone. #[route(GET "/media/{file}")] pub async fn serve_media(cx: &Cx) -> Result { let media = app_context::>(cx); let name = path_param::(cx); if !valid_name(name) { return Err(not_found().into()); } let Some((_, ext)) = name.split_once('.') else { return Err(not_found().into()); }; file_response(cx, &media.path(name), ext, IMMUTABLE, None).await } /// GET /media/rec/{session}: a take, its closed parts joined into one WebM. Parts a socket is /// still writing are left out, and the answer is revalidated against the join key. #[route(GET "/media/rec/{session}")] pub async fn serve_take(cx: &Cx) -> Result { let media = app_context::>(cx); let hub = app_context::>(cx); let id = path_param::(cx); if !valid_session(id) { return take_missing(); } let joined = media .joined_take(id, &hub.attached(id)) .await .map_err(topcoat::Error::from_anyhow)?; let Some((path, key)) = joined else { return take_missing(); }; let etag = format!("\"{}\"", blake3::hash(key.as_bytes()).to_hex()); if not_modified(cx, &etag) { return Ok(Response::builder() .status(StatusCode::NOT_MODIFIED) .header(header::CACHE_CONTROL, "no-cache") .header(header::ETAG, etag) .body(Body::empty())?); } file_response(cx, &path, "weba", "no-cache", Some(&etag)).await } /// The 404 of a take with no audio to serve. Not cached, since audio may arrive. fn take_missing() -> Result { Ok(Response::builder() .status(StatusCode::NOT_FOUND) .header(header::CACHE_CONTROL, "no-store") .header("x-content-type-options", "nosniff") .header("content-security-policy", "sandbox; default-src 'none'") .body(Body::empty())?) } /// Whether the request's `If-None-Match` names `etag`. fn not_modified(cx: &Cx, etag: &str) -> bool { headers(cx) .get(header::IF_NONE_MATCH) .and_then(|v| v.to_str().ok()) .is_some_and(|list| list.split(',').map(str::trim).any(|tag| tag == etag || tag == "*")) } /// GET /media/live: the audio of a recording. `?note=` starts a take, `?session=` continues one /// with a new part, and `?session=&part=` reconnects to a part. The socket is upgraded first, so a /// refusal arrives as a `reject` frame and is not mistaken for the server being offline. #[route(GET "/media/live")] pub async fn recording_socket(cx: &Cx, upgrade: WebSocketUpgrade) -> Result { let store = app_context::>(cx).clone(); let hub = app_context::>(cx).clone(); let media = app_context::>(cx).clone(); let (note, session, part) = { let query = query_params::(cx)?; (query.note.clone(), query.session.clone(), query.part.clone()) }; upgrade .max_message_size(MAX_FRAME) .max_frame_size(MAX_FRAME) .on_upgrade(move |socket| async move { serve_recording(store, hub, media, note, session, part, socket).await; }) } /// Whether `note` is an id of a note that exists. async fn note_exists(store: &Store, note: &str) -> bool { super::is_note_id(note) && matches!(store.get_note(note).await, Ok(Some(_))) } /// The take and part a recording socket asks for, as `(note, session, part)`. `None` when the /// request is refused: a bad or missing id, an unknown note, or a bad part number. A new take is /// created here, with `part` None. async fn recording_target( store: &Store, media: &Media, note: Option, session: Option, part: Option, ) -> Option<(String, String, Option)> { if let Some(session) = session { if !valid_session(&session) { return None; } let note = session.split('.').next()?.to_owned(); if !note_exists(store, ¬e).await { return None; } let part = part.map(|p| p.parse::()).transpose().ok()?; return Some((note, session, part)); } let note = note?; if !note_exists(store, ¬e).await { return None; } let session = media.new_take(¬e).await.ok()?; Some((note, session, None)) } /// Drives one recording socket: attaches it to a part, then stores the chunks it sends. async fn serve_recording( store: Arc, hub: Arc, media: Arc, note: Option, session: Option, part: Option, mut socket: WebSocket, ) { let Some((note, session, part)) = recording_target(&store, &media, note, session, part).await else { return refuse(socket).await; }; let dir = media.take_dir(&session); let Attachment { part, token, mut stop } = match hub.attach(¬e, &session, part, &dir) { Ok(Some(attachment)) => attachment, _ => return refuse(socket).await, }; let (mut file, len) = match open_part(&part_file(&dir, part)).await { Ok(opened) => opened, Err(err) => { eprintln!("opening part {part} of take {session} failed: {err:#}"); hub.detach(¬e, &session, part, token, Detach::Lost); return refuse(socket).await; } }; if socket.send(Message::text(format!("ready {session} {part} {len}"))).await.is_err() { hub.detach(¬e, &session, part, token, Detach::Lost); return; } match receive_part(&mut socket, &mut file, &dir, len, &mut stop).await { Exit::Ended => { let _ = socket.send(Message::text("done")).await; hub.detach(¬e, &session, part, token, Detach::Ended); } Exit::Refused => { let _ = socket.send(Message::text("reject")).await; hub.detach(¬e, &session, part, token, Detach::Lost); } // A socket that was taken over no longer matches its token, so this detaches nothing. Exit::Lost | Exit::Taken => hub.detach(¬e, &session, part, token, Detach::Lost), } let _ = socket.close().await; } /// How a part's socket came to an end. enum Exit { /// The client sent `end`. Ended, /// The socket closed, broke, or went quiet for [`FRAME_WAIT`]. Lost, /// Another socket took the part over. Taken, /// A chunk could not be stored, or the take is full. Refused, } /// Refuses a recording socket: `reject`, then close. async fn refuse(mut socket: WebSocket) { let _ = socket.send(Message::text("reject")).await; let _ = socket.close().await; } /// Opens a part for writing, with its length. async fn open_part(path: &Path) -> std::io::Result<(tokio::fs::File, u64)> { let file = tokio::fs::OpenOptions::new().write(true).open(path).await?; let len = file.metadata().await?.len(); Ok((file, len)) } /// Stores the binary chunks of a part from `len` on, acking each one, until the client sends /// `end`, goes quiet, or another socket takes the part over. async fn receive_part( socket: &mut WebSocket, file: &mut tokio::fs::File, dir: &Path, mut len: u64, stop: &mut oneshot::Receiver<()>, ) -> Exit { loop { let message = tokio::select! { _ = &mut *stop => return Exit::Taken, message = tokio::time::timeout(FRAME_WAIT, socket.recv()) => message, }; let message = match message { Ok(Some(Ok(message))) => message, _ => return Exit::Lost, }; match message { Message::Binary(chunk) => { if write_chunk(file, dir, len, &chunk).await.is_err() { return Exit::Refused; } len += chunk.len() as u64; if socket.send(Message::text(format!("ack {len}"))).await.is_err() { return Exit::Lost; } } Message::Text(text) if text.as_str() == "end" => return Exit::Ended, Message::Close(_) => return Exit::Lost, _ => {} } } } /// Writes `chunk` at `len` and syncs it. A take that would pass [`MAX_BYTES`] is refused, and a /// failed write cuts the part back to `len`. async fn write_chunk(file: &mut tokio::fs::File, dir: &Path, len: u64, chunk: &[u8]) -> std::io::Result<()> { if take_bytes(dir)? + chunk.len() as u64 > MAX_BYTES { return Err(std::io::Error::other("the take is larger than the limit")); } let result = write_at(file, len, chunk).await; if result.is_err() { let _ = file.set_len(len).await; } result } async fn write_at(file: &mut tokio::fs::File, len: u64, chunk: &[u8]) -> std::io::Result<()> { file.seek(SeekFrom::Start(len)).await?; file.write_all(chunk).await?; file.sync_data().await } /// Answers a GET or HEAD for the file at `path`: the whole file, or the range the request asks /// for. `cache` is the Cache-Control value, and `etag` the ETag when there is one. async fn file_response(cx: &Cx, path: &Path, ext: &str, cache: &str, etag: Option<&str>) -> Result { let mut file = match tokio::fs::File::open(path).await { Ok(file) => file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Err(not_found().into()), Err(err) => return Err(topcoat::Error::from_anyhow(err.into())), }; let meta = file.metadata().await.map_err(|err| topcoat::Error::from_anyhow(err.into()))?; if !meta.is_file() { return Err(not_found().into()); } let len = meta.len(); let (status, start, count, content_range) = match headers(cx).get(header::RANGE).and_then(|v| v.to_str().ok()) { Some(range) => match span(range, len) { Span::Whole => (StatusCode::OK, 0, len, None), Span::Part(start, end) => ( StatusCode::PARTIAL_CONTENT, start, end - start + 1, Some(format!("bytes {start}-{end}/{len}")), ), Span::Unsatisfiable => (StatusCode::RANGE_NOT_SATISFIABLE, 0, 0, Some(format!("bytes */{len}"))), }, None => (StatusCode::OK, 0, len, None), }; let (mime, disposition) = match content_type(ext) { Some(mime) => (mime, "inline"), None => ("application/octet-stream", "attachment"), }; let mut builder = Response::builder() .status(status) .header(header::CONTENT_TYPE, mime) .header(header::CONTENT_LENGTH, count.to_string()) .header(header::CONTENT_DISPOSITION, disposition) .header(header::ACCEPT_RANGES, "bytes") .header(header::CACHE_CONTROL, cache) .header("x-content-type-options", "nosniff"); if let Some(etag) = etag { builder = builder.header(header::ETAG, etag); } // Browsers refuse to show a PDF in a sandbox, and a PDF cannot run script on this origin. if ext != "pdf" { builder = builder.header("content-security-policy", "sandbox; default-src 'none'"); } if let Some(range) = content_range { builder = builder.header(header::CONTENT_RANGE, range); } let body = if count == 0 || method(cx) == Method::HEAD { Body::empty() } else { file.seek(SeekFrom::Start(start)) .await .map_err(|err| topcoat::Error::from_anyhow(err.into()))?; Body::new(FileBody { file, remaining: count }) }; Ok(builder.body(body)?) } /// What a `Range` header asks for, against a file of some length. #[derive(Debug, PartialEq)] enum Span { /// No range the server honours: the whole file. Whole, /// The bytes `start..=end`. Part(u64, u64), /// No byte of the file is asked for. Unsatisfiable, } /// Reads one `bytes=a-b`, `bytes=a-` or `bytes=-n` range against a file of `len` bytes. /// Multiple ranges and malformed headers are ignored, and the whole file is served. fn span(value: &str, len: u64) -> Span { let Some((first, last)) = value.trim().strip_prefix("bytes=").and_then(|s| s.split_once('-')) else { return Span::Whole; }; let (first, last) = (first.trim(), last.trim()); if first.is_empty() { // The last `n` bytes. let Ok(n) = last.parse::() else { return Span::Whole }; if n == 0 || len == 0 { return Span::Unsatisfiable; } return Span::Part(len.saturating_sub(n), len - 1); } let Ok(start) = first.parse::() else { return Span::Whole }; if start >= len { return Span::Unsatisfiable; } let end = if last.is_empty() { len - 1 } else { match last.parse::() { Ok(end) if end >= start => end.min(len - 1), _ => return Span::Whole, } }; Span::Part(start, end) } /// Streams the next `remaining` bytes of an open file, a chunk at a time. struct FileBody { file: tokio::fs::File, remaining: u64, } impl http_body::Body for FileBody { type Data = Bytes; type Error = std::io::Error; fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>>> { let this = self.get_mut(); if this.remaining == 0 { return Poll::Ready(None); } let want = this.remaining.min(CHUNK_SIZE as u64) as usize; let mut chunk = vec![0u8; want]; let mut buf = ReadBuf::new(&mut chunk); match Pin::new(&mut this.file).poll_read(cx, &mut buf) { Poll::Pending => Poll::Pending, Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), Poll::Ready(Ok(())) => { let n = buf.filled().len(); if n == 0 { let err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "media file is shorter than its length"); return Poll::Ready(Some(Err(err))); } chunk.truncate(n); this.remaining -= n as u64; Poll::Ready(Some(Ok(Frame::data(Bytes::from(chunk))))) } } } }