Cotton code
290 lines · 11.1 KB · RustRaw
//! One message as a bubble and as a line: what it is, its attachments, its//! link card, its tick and its reactions. Pure: the row arrives parsed.use crate::messages::display::{message_line, DELETED_WORDS};use crate::messages::preview::{media_kind_of, PreviewSource};use crate::messages::{MessageMedia, MessageMeta};use crate::constants::MessageMediaKind as Kind;use super::lay::{length, size};use super::shapes::{BubbleKind, LinkCard, Mark, MediaPart, Reaction, Tick};/// A message as read.#[derive(Debug, Clone, Copy)]pub struct Row<'a> {    pub body: Option<&'a str>,    pub media: &'a [MessageMedia],    pub meta: Option<&'a MessageMeta>,    pub deleted_at: Option<&'a str>,}impl<'a> Row<'a> {    fn source(&self) -> PreviewSource<'a> {        PreviewSource { body: self.body, media: self.media, deleted_at: self.deleted_at, meta: self.meta }    }    pub fn deleted(&self) -> bool {        self.deleted_at.is_some_and(|d| !d.trim().is_empty())    }    /// A group event or an importer's aside: drawn centred, never a bubble.    pub fn event(&self) -> bool {        self.meta.and_then(|m| m.system.as_ref()).is_some_and(|s| s.is_truthy())    }}fn mark_of_kind(kind: Kind) -> Mark {    match kind {        Kind::Image => Mark::Photo,        Kind::Video => Mark::Video,        Kind::Audio => Mark::Audio,        Kind::Voice => Mark::Voice,        Kind::File => Mark::File,        Kind::Contact => Mark::Contact,    }}/// What the bubble is.pub fn kind_of(row: &Row<'_>) -> BubbleKind {    if row.deleted() {        return BubbleKind::Deleted;    }    if row.meta.and_then(|m| m.poll.as_ref()).is_some() {        return BubbleKind::Poll;    }    let kinds: Vec<Kind> = row.media.iter().map(media_kind_of).collect();    let visual = kinds.iter().filter(|k| matches!(k, Kind::Image | Kind::Video)).count();    if visual >= 2 && visual == kinds.len() {        return BubbleKind::Album;    }    match kinds.first() {        None => BubbleKind::Text,        Some(Kind::Image) => BubbleKind::Photo,        Some(Kind::Video) => BubbleKind::Video,        Some(Kind::Voice) => BubbleKind::Voice,        Some(Kind::Audio) => BubbleKind::Audio,        Some(Kind::File) => BubbleKind::File,        Some(Kind::Contact) => BubbleKind::Contact,    }}/// The small mark before a line (a list's last line, a reply's quote).pub fn mark_of(row: &Row<'_>) -> Option<Mark> {    match kind_of(row) {        BubbleKind::Text => None,        BubbleKind::Photo => Some(Mark::Photo),        BubbleKind::Album => Some(Mark::Album),        BubbleKind::Video => Some(Mark::Video),        BubbleKind::Voice => Some(Mark::Voice),        BubbleKind::Audio => Some(Mark::Audio),        BubbleKind::File => Some(Mark::File),        BubbleKind::Contact => Some(Mark::Contact),        BubbleKind::Location => Some(Mark::Location),        BubbleKind::Poll => Some(Mark::Poll),        BubbleKind::Deleted => Some(Mark::Deleted),    }}/// The line a list or a quote says for it: the one preview every surface writes.pub fn line_of(row: &Row<'_>) -> String {    message_line(&row.source())}/// The bubble's own words: the body as written; a deleted one says so./// A bubble of media alone carries none.pub fn text_of(row: &Row<'_>) -> Option<String> {    if row.deleted() {        return Some(DELETED_WORDS.to_string());    }    if row.event() {        return Some(line_of(row));    }    let body = row.body.map(crate::messages::js_trim).filter(|b| !b.is_empty())?;    // An importer's marker ("[attachment: PHOTO-….jpg]") stands for the file: beside the file drawn, it says nothing.    if crate::messages::display::marker_words(body).is_some() {        return row.media.is_empty().then(|| line_of(row));    }    if !row.media.is_empty() && names_a_file(body, row) {        return None;    }    Some(body.to_string())}/// Whether `body` is only the name of a file the message carries. An/// export's document line ("Screenshot ….png <attached: 00000011-Screenshot/// ….png>", "Plan.pdf • 3 pages <attached: …>") leaves the file's name where/// a caption stands; a file name is not a caption.pub fn names_a_file(body: &str, row: &Row<'_>) -> bool {    let said = plain_name(body);    if said.is_empty() {        return false;    }    let attached = row.meta.and_then(|m| m.attachment.as_ref()).and_then(|a| a.name.as_deref());    row.media.iter().filter_map(|m| m.name.as_deref()).chain(attached).any(|name| {        let name = plain_name(name);        // The export's staging number ("00000011-") is the file's, never the words'.        let unnumbered = name.find('-').filter(|&at| at > 0 && name[..at].bytes().all(|b| b.is_ascii_digit())).map(|at| &name[at + 1..]);        name == said || unnumbered == Some(said.as_str())    })}/// A file's name as compared: no direction marks, no page count, any case.fn plain_name(text: &str) -> String {    let plain: String = text.chars().filter(|c| !matches!(c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}')).collect();    let plain = plain.trim();    let plain = match plain.rsplit_once('\u{2022}') {        Some((name, pages)) if pages.trim().ends_with("page") || pages.trim().ends_with("pages") => name.trim(),        _ => plain,    };    plain.to_lowercase()}/// How many bars a voice message's player draws, whatever its length, so/// every player is one width (`assets/design/chat/voice-player.html`).pub const BARS: usize = 36;/// A loudest sample under this is silence: every bar then stands at its least.pub const SILENCE: f64 = 0.05;/// A voice message's [`BARS`] heights in 0..1 from its waveform (the/// recorder's peak loudness per slice, 0..1, up to 64 samples): with more/// samples than bars each bar is the highest sample in its share of them, so/// a loud word never disappears; with fewer (a very short note) each bar takes/// the sample under it, so the shape stretches to fill the width. Scaled to/// the note's own loudest sample, so a quiet speaker's note is no flatter than/// a loud one's; a note whose loudest is under [`SILENCE`] is all nought.pub fn bars(waveform: &[f64]) -> Vec<f64> {    let levels: Vec<f64> = waveform.iter().map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }).collect();    if levels.is_empty() {        return vec![0.0; BARS];    }    let gathered: Vec<f64> = if levels.len() >= BARS {        let step = levels.len() as f64 / BARS as f64;        (0..BARS)            .map(|i| {                let from = (i as f64 * step).floor() as usize;                let to = (((i + 1) as f64 * step).floor() as usize).max(from + 1).min(levels.len());                levels[from..to].iter().copied().fold(0.0, f64::max)            })            .collect()    } else {        (0..BARS).map(|i| levels[i * levels.len() / BARS]).collect()    };    let top = gathered.iter().copied().fold(0.0, f64::max);    if top < SILENCE {        return vec![0.0; BARS];    }    gathered.into_iter().map(|v| ((v / top) * 1000.0).round() / 1000.0).collect()}/// Each attachment as drawn; none on a deleted message.pub fn media_parts(row: &Row<'_>) -> Vec<MediaPart> {    if row.deleted() {        return Vec::new();    }    row.media        .iter()        .enumerate()        .map(|(index, entry)| {            let kind = mark_of_kind(media_kind_of(entry));            let timed = matches!(kind, Mark::Voice | Mark::Audio | Mark::Video);            MediaPart {                index: index as u32,                kind,                name: entry.name.clone(),                width: entry.width,                height: entry.height,                length: entry.duration_ms.filter(|ms| timed && *ms > 0.0).map(length),                size: entry.size_bytes.filter(|b| kind == Mark::File && *b > 0.0).map(size),                duration_ms: entry.duration_ms.filter(|ms| timed && *ms > 0.0).map(|ms| ms.round() as u64),                waveform: entry.waveform.clone().filter(|_| kind == Mark::Voice),                bars: entry.waveform.as_deref().filter(|w| kind == Mark::Voice && !w.is_empty()).map(bars),                played: true,                preview: entry.preview.clone(),                contact: entry.contact.as_ref().map(|c| c.name.clone()),                number: entry.contact.as_ref().and_then(|c| c.phones.first().cloned()),                gone: false,                transcript: None,                message: None,            }        })        .collect()}/// The link card the first link unfolded into.pub fn link_of(row: &Row<'_>) -> Option<LinkCard> {    if row.deleted() {        return None;    }    let preview = row.meta?.preview.as_ref()?;    Some(LinkCard {        url: preview.url.clone(),        site: preview.site_name.clone(),        title: preview.title.clone(),        description: preview.description.clone(),        thumb: preview.thumb.clone(),    })}/// How long a message of the person's own may be on its way before "Sending"/// is drawn under it: a send that goes within it shows no state at all.pub const QUIET_SENDING_MS: i64 = 2_000;/// Until when a message written at `written_ms` (ms) draws no state while its/// tick is sending; `None` for any other tick.pub fn quiet_until(tick: Option<Tick>, written_ms: Option<i64>) -> Option<i64> {    match tick {        Some(Tick::Sending) => written_ms.map(|at| at + QUIET_SENDING_MS),        _ => None,    }}/// Your own message's tick, where the source tells: Cotton's send state.pub fn tick_of(send_state: Option<&str>, cotton: bool, mine: bool) -> Option<Tick> {    if !(cotton && mine) {        return None;    }    match send_state? {        "queued" | "sending" => Some(Tick::Sending),        "sent" => Some(Tick::Sent),        "delivered" => Some(Tick::Delivered),        "read" => Some(Tick::Read),        "failed" => Some(Tick::Failed),        _ => None,    }}/// Reactions, one per emoji in first-seen order: each `(emoji, mine)`.pub fn reactions(seen: &[(String, bool)]) -> Vec<Reaction> {    let mut out: Vec<Reaction> = Vec::new();    for (emoji, mine) in seen {        let emoji = emoji.trim();        if emoji.is_empty() {            continue;        }        match out.iter_mut().find(|r| r.emoji == emoji) {            Some(r) => {                r.count += 1;                r.mine |= *mine;            }            None => out.push(Reaction { emoji: emoji.to_string(), count: 1, mine: *mine }),        }    }    out}/// A message's `reactions` column as an importer wrote it: a JSON array of/// emoji, or of objects carrying `emoji` (and `fromMe`).pub fn stored_reactions(raw: Option<&str>) -> Vec<(String, bool)> {    let Some(raw) = raw.filter(|r| !r.trim().is_empty()) else { return Vec::new() };    let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(raw) else { return Vec::new() };    items        .iter()        .filter_map(|item| match item {            serde_json::Value::String(e) => Some((e.clone(), false)),            serde_json::Value::Object(o) => Some((                o.get("emoji")?.as_str()?.to_string(),                o.get("fromMe").or_else(|| o.get("from_me")).and_then(serde_json::Value::as_bool).unwrap_or(false),            )),            _ => None,        })        .collect()}