//! Bytes, for all three sources at once. //! //! One rule, and everything here follows from it: **no message ever waits on //! its bytes.** A file that is missing, too big, or of a type the server will //! not sign for is a counted SKIP — the row still lands, with its words and //! without its picture — because the alternative is refusing somebody's whole //! message history over an attachment they lost years ago. //! //! The sequence per file is the phone's, in the same order and for the same //! reasons: //! //! 1. measure it — a size the SOURCE claimed is a hint, never the judgement; //! 2. judge it against the message limits, the server's own ceiling and //! allowlist, so nothing is copied that the server would refuse to sign; //! 3. hash and copy it into this Mac's content-addressed media store; //! 4. mint the message media key — which is why the caller has to know the //! thread BEFORE the rows are written; //! 5. write the `_media` ledger row, `pending`, for the drain to pick up. //! //! Step 5 carries NO `after` trigger. The trigger a chat attachment normally //! gets wakes the server's copy worker so the other members of a group see the //! photo now — and an imported row is `origin: "imported"`, which the relay //! ignores by construction. Asking the server to consider mirroring tens of //! thousands of rows it will refuse to mirror is work nobody benefits from. use std::collections::BTreeMap; use cotton_core::import::envelope::{EnvelopeMedia, ImportBatch}; use cotton_core::import::media_plan::{content_type_for_extension, display_name_for, extension_of}; use cotton_core::media::keys::{ assert_key_in_workspace, media_limits, message_media_key, MediaKind, }; use cotton_core::media::voice_rendition::{ ogg_opus_duration_ms, is_ogg_opus, VOICE_RENDITION_CONTENT_TYPE, VOICE_RENDITION_EXT, }; use cotton_store::file_identity::FileId; use cotton_store::media_ledger::{enqueue_media, MediaEnqueueInput}; use cotton_store::Driver; use super::{count, MediaFile, Notes}; use crate::media::{file_size_of, put_media_file}; use crate::seams::Clock; use crate::Layout; /// What one attachment turned into — a key, or a written reason there is none. #[derive(Debug, Clone, PartialEq, Eq)] pub enum MediaOutcome { Stored { key: String, content_type: String, size_bytes: i64, name: String, }, Missing, Oversize, UnsupportedType, Failed { detail: String, }, } impl MediaOutcome { /// The counted reason this outcome is filed under. pub fn note_key(&self) -> &'static str { match self { MediaOutcome::Stored { .. } => "media:stored", MediaOutcome::Missing => "media:missing", MediaOutcome::Oversize => "media:oversize", MediaOutcome::UnsupportedType => "media:unsupportedType", MediaOutcome::Failed { .. } => "media:failed", } } } pub struct MediaLeg<'a> { pub layout: &'a Layout, /// The open file the key is made under. pub file: &'a FileId, /// The thread the rows will land in — the key carries it. pub thread_id: &'a str, pub clock: &'a dyn Clock, } /// What a file is, judged before a byte is copied: or why it never will be. struct Judged { size_bytes: u64, name: String, ext: String, content_type: String, } fn judge(file: &MediaFile) -> Result { let Some(size_bytes) = file_size_of(&file.path) else { return Err(MediaOutcome::Missing); }; let named = file .name .clone() .unwrap_or_else(|| file.path.to_string_lossy().to_string()); let name = display_name_for(&named); let ext = extension_of(&name); let guessed = file .content_type .clone() .or_else(|| content_type_for_extension(&ext).map(str::to_string)); let limits = media_limits(MediaKind::Message); // Judged HERE rather than at the server, on the server's own list: copying // 90 MB into the store and then learning the upload will never be signed is // the disk of a Mac spent on bytes that can go nowhere. let Some(content_type) = guessed.filter(|value| limits.content_types.contains(&value.as_str())) else { return Err(MediaOutcome::UnsupportedType); }; if size_bytes > limits.max_bytes { return Err(MediaOutcome::Oversize); } Ok(Judged { size_bytes, name, ext, content_type, }) } /// Store one file and ledger it, or say why not. /// /// Never fails for a reason that is about the FILE: a disk that refuses a read /// is a `Failed` outcome carrying the system's own sentence, so one unreadable /// attachment cannot take a batch of five hundred messages down with it. pub fn store_one_file(leg: &MediaLeg<'_>, db: &Driver, file: &MediaFile) -> MediaOutcome { store_one_file_keyed(leg, db, file, &|sha256, ext| message_media_key(leg.file, leg.thread_id, sha256, ext)) } /// [`store_one_file`] under a key the caller spells from the bytes' digest /// and extension — a WhatsApp profile picture is keyed to its person, not to /// a thread. pub fn store_one_file_keyed( leg: &MediaLeg<'_>, db: &Driver, file: &MediaFile, key_for: &dyn Fn(&str, &str) -> String, ) -> MediaOutcome { let Judged { name, ext, content_type, .. } = match judge(file) { Ok(judged) => judged, Err(outcome) => return outcome, }; let stored = match put_media_file(leg.layout, leg.file.as_str(), &file.path, &ext) { Ok(stored) => stored, Err(error) => { return MediaOutcome::Failed { detail: error.to_string(), } } }; let key = key_for(&stored.sha256, &ext); // The workspace prefix is the one thing a key MUST get right — it is what // keeps one person's bytes out of another's — so it is asserted rather than // assumed, exactly as every other writer of a key does. if let Err(error) = assert_key_in_workspace(Some(&key), leg.file) { return MediaOutcome::Failed { detail: error.to_string(), }; } if let Err(error) = enqueue_media( db, &MediaEnqueueInput { key: key.clone(), workspace_id: leg.file.as_str().to_string(), sha256: stored.sha256, content_type: content_type.clone(), size_bytes: stored.size_bytes as i64, local_path: Some(stored.path.to_string_lossy().to_string()), state: None, // No trigger: the relay ignores an imported row, so there is // nothing on the server to wake. after: None, after_row_id: None, now: leg.clock.now_iso(), tier: None, captured_here: false, }, ) { return MediaOutcome::Failed { detail: error.to_string(), }; } MediaOutcome::Stored { key, content_type, size_bytes: stored.size_bytes as i64, name, } } /// Store every file this batch references and hand back the batch to write. /// /// Returns a NEW batch rather than editing the one it was given: the source /// built that object, and a reader that mutates its caller's data is how a /// retry ends up writing something different from what it read. pub fn attach_media( leg: &MediaLeg<'_>, db: &Driver, batch: &ImportBatch, files: &[MediaFile], ) -> (ImportBatch, Notes) { attach_with(batch, files, |file| store_one_file(leg, db, file)) } /// Where a SERVING Mac keeps a picture: the object store it serves from, put /// by key. The bytes are already where every phone fetches them, so nothing /// is ledgered for upload. pub trait PutObject { /// Copy `source` into the store under `key`; a key already there is the /// same bytes (the key carries their digest), so it is left alone. fn put(&self, key: &str, source: &std::path::Path, content_type: &str) -> Result<(), String>; } /// Store one file straight into a served object store, or say why not. pub fn put_one_file( file_id: &FileId, thread_id: &str, store: &dyn PutObject, file: &MediaFile, ) -> MediaOutcome { put_one_file_keyed(file_id, store, file, &|sha256, ext| message_media_key(file_id, thread_id, sha256, ext)) } /// [`put_one_file`] under a key the caller spells from the bytes' digest and /// extension. pub fn put_one_file_keyed( file_id: &FileId, store: &dyn PutObject, file: &MediaFile, key_for: &dyn Fn(&str, &str) -> String, ) -> MediaOutcome { let judged = match judge(file) { Ok(judged) => judged, Err(outcome) => return outcome, }; let sha256 = match crate::media::sha256_file(&file.path) { Ok((sha256, _)) => sha256, Err(error) => { return MediaOutcome::Failed { detail: error.to_string(), } } }; let key = key_for(&sha256, &judged.ext); if let Err(error) = assert_key_in_workspace(Some(&key), file_id) { return MediaOutcome::Failed { detail: error.to_string(), }; } if let Err(detail) = store.put(&key, &file.path, &judged.content_type) { return MediaOutcome::Failed { detail }; } MediaOutcome::Stored { key, content_type: judged.content_type, size_bytes: judged.size_bytes as i64, name: judged.name, } } /// [`attach_media`] for a SERVING Mac: every file put straight into `store`. pub fn attach_media_served( file_id: &FileId, thread_id: &str, store: &dyn PutObject, batch: &ImportBatch, files: &[MediaFile], ) -> (ImportBatch, Notes) { attach_with(batch, files, |file| put_one_file(file_id, thread_id, store, file)) } fn attach_with( batch: &ImportBatch, files: &[MediaFile], store: impl FnMut(&MediaFile) -> MediaOutcome, ) -> (ImportBatch, Notes) { attach_with_transcoder(batch, files, store, &mut VoiceTranscodeJob::run) } fn attach_with_transcoder( batch: &ImportBatch, files: &[MediaFile], mut store: impl FnMut(&MediaFile) -> MediaOutcome, transcode: &mut dyn FnMut(&VoiceTranscodeJob) -> Result<(), String>, ) -> (ImportBatch, Notes) { let mut notes = Notes::new(); if files.is_empty() { return (batch.clone(), notes); } let mut by_external_id: BTreeMap> = BTreeMap::new(); for file in files { let outcome = store(file); count(&mut notes, outcome.note_key(), 1); let MediaOutcome::Stored { key, content_type, size_bytes, name, } = outcome else { continue; }; let voice = if is_ogg_opus(&content_type) { let voice = voice_rendition(file, &mut store, transcode); count(&mut notes, if voice.is_ok() { "voice:rendered" } else { "voice:notRendered" }, 1); voice.ok() } else { None }; // The length from the Ogg itself where no rendition was made (a phone, which has no transcoder): the // voice player counts down from it and the list line says it. let duration_ms = voice.as_ref().map(|voice| voice.duration_ms as f64).or_else(|| ogg_length(&content_type, file)); by_external_id .entry(file.external_id.clone()) .or_default() .push(EnvelopeMedia { key, content_type, name: Some(name), size_bytes: Some(size_bytes as f64), width: None, height: None, contact: None, duration_ms, playback_content_type: voice.as_ref().map(|_| VOICE_RENDITION_CONTENT_TYPE.to_string()), playback_key: voice.map(|voice| voice.key), file_key: None, kind: None, waveform: None, preview: None, }); } if by_external_id.is_empty() { return (batch.clone(), notes); } let mut next = batch.clone(); for message in &mut next.messages { let Some(attached) = by_external_id.get(&message.external_id) else { continue; }; message .media .get_or_insert_with(Vec::new) .extend(attached.iter().cloned()); } (next, notes) } /// An Ogg Opus file's length in ms, read from its last page; none for anything else or a file that will not read. fn ogg_length(content_type: &str, file: &MediaFile) -> Option { if !is_ogg_opus(content_type) { return None; } let bytes = std::fs::read(&file.path).ok()?; ogg_opus_duration_ms(&bytes).ok().filter(|ms| *ms > 0).map(|ms| ms as f64) } struct StoredVoice { key: String, duration_ms: i64, } /// Store a voice note's AAC m4a rendition beside its Ogg /// original, the same way the original was stored. The phone cannot play Ogg; /// a recording that cannot be transcoded keeps only its original. fn voice_rendition( file: &MediaFile, store: &mut impl FnMut(&MediaFile) -> MediaOutcome, transcode: &mut dyn FnMut(&VoiceTranscodeJob) -> Result<(), String>, ) -> Result { let bytes = std::fs::read(&file.path).map_err(|error| error.to_string())?; let duration_ms = ogg_opus_duration_ms(&bytes)?; let stem = file .path .file_stem() .map(|stem| stem.to_string_lossy().to_string()) .unwrap_or_else(|| "voice".to_string()); let temporary = tempfile::Builder::new() .prefix("cotton-voice-") .suffix(&format!(".{VOICE_RENDITION_EXT}")) .tempfile() .map_err(|error| error.to_string())?; transcode(&VoiceTranscodeJob { input: file.path.clone(), output: temporary.path().to_path_buf() })?; if std::fs::metadata(temporary.path()).map_err(|error| error.to_string())?.len() == 0 { return Err("voice_transcode_empty_output".into()); } let outcome = store(&MediaFile { external_id: file.external_id.clone(), path: temporary.path().to_path_buf(), name: Some(format!("{stem}.{VOICE_RENDITION_EXT}")), content_type: Some(VOICE_RENDITION_CONTENT_TYPE.to_string()), }); match outcome { MediaOutcome::Stored { key, .. } => Ok(StoredVoice { key, duration_ms, }), outcome => Err(outcome.note_key().to_string()), } } /// A serving-host engine job. Paths are arguments, never shell input, and the /// output is a private temporary file rather than a sibling of the original. struct VoiceTranscodeJob { input: std::path::PathBuf, output: std::path::PathBuf, } impl VoiceTranscodeJob { fn arguments(&self) -> Vec { let mut args: Vec = ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i"].into_iter().map(Into::into).collect(); args.push(self.input.as_os_str().to_owned()); args.extend(["-vn", "-c:a", "aac", "-b:a", "96k", "-movflags", "+faststart", "-f", "mp4"].into_iter().map(std::ffi::OsString::from)); args.push(self.output.as_os_str().to_owned()); args } fn run(&self) -> Result<(), String> { if !cfg!(target_os = "macos") { return Err("voice_transcode_requires_serving_mac".into()); } let executable = ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"] .into_iter().find(|path| std::path::Path::new(path).is_file()).unwrap_or("ffmpeg"); let mut child = std::process::Command::new(executable) .args(self.arguments()) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .spawn().map_err(|error| error.to_string())?; let started = std::time::Instant::now(); loop { match child.try_wait() { Ok(Some(status)) => return if status.success() { Ok(()) } else { Err("voice_transcode_failed".into()) }, Ok(None) if started.elapsed() < std::time::Duration::from_secs(120) => std::thread::sleep(std::time::Duration::from_millis(100)), result => { let _ = child.kill(); let _ = child.wait(); return Err(match result { Err(error) => error.to_string(), _ => "voice_transcode_timeout".into() }); } } } } } #[cfg(test)] #[path = "media_tests.rs"] mod tests;