Cotton code
171 lines · 6.8 KB · RustRaw
//! What a meeting's audio IS: the containers a recording may arrive in, the//! content type each is stored as, and WHICH object a meeting's row names.//!//! ## Why the container is no longer assumed//!//! The cell-era import wrote every recording at `full.m4a` whatever it really//! was, and let the object's `contentType` carry the truth. That held while the//! only door was Voice Memos. It stopped holding the day the owner shared a//! WhatsApp voice note into Cotton: those are Opus in an Ogg container, and a//! `.m4a` key over Ogg bytes is a filename that lies to every reader that has//! only the key — the pipeline naming the vendor's input, a person saving a//! copy out of the app, the export manifest. So **the key's extension follows//! the source** ([`crate::media::keys::meeting_full_key_of`]) and this module//! is the one table that says which extensions there are.//!//! ## Which object, and why the manifest answers//!//! `cotton_meetings` has no column for its audio key — its audio is described//! by the `segments` manifest, which the recorder fills one entry per segment.//! An IMPORT is one object and therefore one entry, and that entry is where the//! real extension lives. A row with no manifest at all falls back to the//! well-known `full.m4a`, which is what every meeting written before this//! module existed carries.//!//! [`meeting_audio_object`] is that rule, once, because three readers ask it://! the server's pipeline (which object to transcribe), the phone's meeting//! reads (is this meeting's audio still on this device), and the tests that//! hold the two together.use cotton_store::file_identity::FileId;use serde_json::Value;use crate::media::keys::{meeting_full_key, MEETING_AUDIO_DEFAULT_EXT};pub use cotton_rules::media::MEETING_AUDIO_TYPES;/// `extension -> the content type an object with that extension is written/// with`.////// The CANONICAL type per container, which is what the object carries and what/// the vendor is told. The wider set above is what a caller may SAY; this is/// what gets written down.pub const MEETING_AUDIO_FORMATS: &[(&str, &str)] = &[    ("m4a", "audio/mp4"),    ("mp4", "audio/mp4"),    ("aac", "audio/aac"),    ("mp3", "audio/mpeg"),    ("wav", "audio/wav"),    ("opus", "audio/ogg"),    ("ogg", "audio/ogg"),    ("oga", "audio/ogg"),    ("flac", "audio/flac"),    ("amr", "audio/amr"),    ("caf", "audio/x-caf"),];/// Is this an extension a meeting's audio may be filed under?pub fn is_meeting_audio_ext(ext: &str) -> bool {    meeting_audio_mime_for_ext(ext).is_some()}/// The content type an object with this extension is written with.////// Case- and dot-insensitive, because the three callers get their extension/// from three different places: a filename the share sheet chose, a path the/// picker copied, and an object key this module built.pub fn meeting_audio_mime_for_ext(ext: &str) -> Option<&'static str> {    let ext = ext.trim().trim_start_matches('.').to_ascii_lowercase();    MEETING_AUDIO_FORMATS        .iter()        .find(|(candidate, _)| *candidate == ext)        .map(|(_, mime)| *mime)}/// Every extension a meeting's audio may be filed under, for a refusal that/// says what WOULD have been accepted.pub fn meeting_audio_extensions() -> Vec<&'static str> {    MEETING_AUDIO_FORMATS.iter().map(|(ext, _)| *ext).collect()}/// The content type for an object KEY — read off its extension.////// The pipeline's answer to "what am I handing the vendor". It used to be the/// constant `audio/m4a` for every recording, which was true only while every/// recording was an m4a.pub fn meeting_audio_mime_of_key(key: &str) -> &'static str {    let ext = key.rsplit('/').next().unwrap_or(key);    let ext = ext.rsplit_once('.').map(|(_, ext)| ext).unwrap_or_default();    meeting_audio_mime_for_ext(ext).unwrap_or_else(|| {        // The default container's own type, never an empty string: a vendor leg        // that sends a blank content type is a request nobody can debug, and        // every key written before this module existed IS an m4a.        meeting_audio_mime_for_ext(MEETING_AUDIO_DEFAULT_EXT).unwrap_or("audio/mp4")    })}/// Where a meeting's audio is, or why there is no single object to send.#[derive(Debug, Clone, PartialEq, Eq)]pub enum MeetingAudioObject {    /// The one object this meeting's audio lives in.    At(String),    /// More than one usable segment. Half a meeting presented as a whole one is    /// the failure the pipeline exists to make impossible, so the caller refuses    /// rather than transcribing the first piece.    ManyObjects,}/// The one object a meeting's audio lives in.////// Pure, and the purity is load-bearing: the server decides what to transcribe/// with it and the phone decides whether the bytes have left the device with/// it, and those two must never disagree about which key a meeting means.pub fn meeting_audio_object(    file_id: &FileId,    meeting_id: &str,    segments: &Value,) -> MeetingAudioObject {    let entries = segments.as_array().map(Vec::as_slice).unwrap_or_default();    let mut usable: Vec<String> = Vec::new();    for entry in entries {        let Some(record) = entry.as_object() else {            continue;        };        // A LOST segment has no bytes; it is a gap marker, not an input.        if record.get("lost") == Some(&Value::Bool(true)) {            continue;        }        let path = record            .get("path")            .and_then(Value::as_str)            .unwrap_or_default()            .trim();        if path.is_empty() {            continue;        }        usable.push(path.to_string());    }    if usable.len() > 1 {        return MeetingAudioObject::ManyObjects;    }    if let Some(path) = usable.pop() {        return MeetingAudioObject::At(path);    }    // No manifest at all: every meeting written before the manifest carried the    // import's own object is at the well-known key, in the default container.    MeetingAudioObject::At(meeting_full_key(file_id, meeting_id))}/// The manifest an import writes: ONE entry, naming the object the bytes went/// into.////// The cell-era import wrote an EMPTY manifest and relied on the well-known/// key, and the reason it could is that the key was a constant. It is not one/// any more — an Ogg voice note is at `full.opus` — so the entry is how the row/// says which object is its own, with no store schema change and no second/// column that could disagree with the manifest beside it.pub fn one_segment_manifest(key: &str, duration_ms: Option<i64>) -> Value {    serde_json::json!([{        "seq": 0,        "path": key,        "durationMs": duration_ms,        // Written by whatever uploads it; the ledger is the truth about that        // and this column is never read for it.        "uploadedAt": Value::Null,    }])}#[cfg(test)]#[path = "meeting_audio_tests.rs"]mod tests;