Cotton code
191 lines · 7.4 KB · RustRaw
//! The ids and media keys the Mac names.//!//! A plain row's id is a UUID v5 over (source, external id), so a re-read//! sends the same id and the object answers `duplicate_id` instead of writing//! a second row. A media key is the shape `cotton_core::media::keys` and the//! push job already stored, so the phone keeps resolving it.use sha1::{Digest as _, Sha1};use sha2::Sha256;/// RFC 4122's URL namespace: the name is `cotton-mac:<source>:<external id>`.const NAMESPACE_URL: [u8; 16] = [    0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8,];/// The id a plain row from `source` with the source's own `external_id` has,/// on every read.pub fn row_id(source: &str, external_id: &str) -> String {    let mut hasher = Sha1::new();    hasher.update(NAMESPACE_URL);    hasher.update(format!("cotton-mac:{source}:{external_id}").as_bytes());    let digest = hasher.finalize();    let mut bytes = [0u8; 16];    bytes.copy_from_slice(&digest[..16]);    bytes[6] = (bytes[6] & 0x0f) | 0x50;    bytes[8] = (bytes[8] & 0x3f) | 0x80;    let hex = hex::encode(bytes);    format!(        "{}-{}-{}-{}-{}",        &hex[0..8],        &hex[8..12],        &hex[12..16],        &hex[16..20],        &hex[20..32]    )}pub fn sha256_hex(bytes: &[u8]) -> String {    hex::encode(<Sha256 as sha2::Digest>::digest(bytes))}/// The SHA-256 of the file at `path` and its length, read a block at a time/// so a file of gigabytes is never held whole.pub fn sha256_of_file(path: &std::path::Path) -> std::io::Result<(String, u64)> {    use std::io::Read as _;    let mut file = std::fs::File::open(path)?;    let mut hasher = <Sha256 as sha2::Digest>::new();    let mut block = vec![0u8; 1024 * 1024];    let mut size = 0u64;    loop {        let read = file.read(&mut block)?;        if read == 0 {            break;        }        sha2::Digest::update(&mut hasher, &block[..read]);        size += read as u64;    }    Ok((hex::encode(sha2::Digest::finalize(hasher)), size))}/// `<database id>/photos/<sha256>.<ext>`: a photo or film original.pub fn photo_key(database_id: &str, sha256: &str, ext: &str) -> String {    format!("{database_id}/photos/{sha256}.{ext}")}/// `<database id>/music/<sha256>.<ext>`: a song's file, the shape/// `cotton_core::media::keys::song_key` names and `isSongKey` admits.pub fn song_key(database_id: &str, sha256: &str, ext: &str) -> String {    format!("{database_id}/music/{sha256}.{ext}")}/// `<database id>/messages/<message id>/<sha256>.<ext>`: an attachment. The/// message id is the row id of (channel, the message's external id): the Mac/// cannot know the thread, which is the object's to decide.pub fn message_media_key(database_id: &str, channel: &str, external_id: &str, sha256: &str, ext: &str) -> String {    let message = row_id(channel, external_id);    format!("{database_id}/messages/{message}/{sha256}.{ext}")}/// `{database}/people/{person}/whatsapp/{sha256}.{ext}`: a person's photo that came from their WhatsApp profile, as/// `cotton_core::media::keys::whatsapp_avatar_key` makes it (the `whatsapp` folder is its provenance).pub fn whatsapp_avatar_key(database_id: &str, person_id: &str, sha256: &str, ext: &str) -> String {    format!("{database_id}/people/{person_id}/whatsapp/{sha256}.{ext}")}/// `{database}/messages/{thread}/whatsapp/{sha256}.{ext}`: a WhatsApp group's picture, as/// `cotton_core::media::keys::whatsapp_group_picture_key` makes it.pub fn whatsapp_group_picture_key(database_id: &str, thread_id: &str, sha256: &str, ext: &str) -> String {    format!("{database_id}/messages/{thread_id}/whatsapp/{sha256}.{ext}")}/// `{database}/messages/{contact}/whatsapp/{sha256}.{ext}`: the WhatsApp picture of a sender no person is, on/// their contact (the same five segments `cotton_core::media::keys::is_whatsapp_picture_key` reads as WhatsApp's).pub fn whatsapp_contact_picture_key(database_id: &str, contact_id: &str, sha256: &str, ext: &str) -> String {    format!("{database_id}/messages/{contact_id}/whatsapp/{sha256}.{ext}")}/// The extension a file is stored under: its own name's, lower-cased, else/// the one its content type names, else `bin`.pub fn extension_of(name: Option<&str>, content_type: Option<&str>) -> String {    let from_name = name        .and_then(|n| n.rsplit_once('.').map(|(_, ext)| ext))        .filter(|ext| !ext.is_empty() && ext.len() <= 8 && ext.chars().all(|c| c.is_ascii_alphanumeric()))        .map(str::to_ascii_lowercase);    if let Some(ext) = from_name {        return ext;    }    let ext = match content_type.unwrap_or("") {        "image/jpeg" => "jpg",        "image/png" => "png",        "image/heic" => "heic",        "image/webp" => "webp",        "image/gif" => "gif",        "video/mp4" => "mp4",        "video/quicktime" => "mov",        "audio/ogg" => "ogg",        "audio/mpeg" => "mp3",        "audio/mp4" => "m4a",        "application/pdf" => "pdf",        _ => "bin",    };    ext.to_string()}/// The content type a file goes up with: the source's own, else the one its/// extension names, else `application/octet-stream`.pub fn content_type_of(known: Option<&str>, ext: &str) -> String {    if let Some(known) = known.filter(|t| t.contains('/')) {        return known.to_string();    }    match ext {        "jpg" | "jpeg" => "image/jpeg",        "png" => "image/png",        "heic" => "image/heic",        "webp" => "image/webp",        "gif" => "image/gif",        "mp4" => "video/mp4",        "mov" => "video/quicktime",        "ogg" | "opus" => "audio/ogg",        "mp3" => "audio/mpeg",        "m4a" => "audio/mp4",        "pdf" => "application/pdf",        _ => "application/octet-stream",    }    .to_string()}#[cfg(test)]mod tests {    use super::*;    #[test]    fn row_id_is_a_stable_uuid_v5() {        let id = row_id("mail", "<a@example.com>");        assert_eq!(id, row_id("mail", "<a@example.com>"));        assert_ne!(id, row_id("calendar", "<a@example.com>"));        assert_eq!(id.len(), 36);        assert_eq!(&id[14..15], "5");        assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"));    }    #[test]    fn row_id_matches_the_rfc_construction() {        // uuid.uuid5(uuid.NAMESPACE_URL, "cotton-mac:mail:x") in Python.        assert_eq!(row_id("mail", "x"), "e54ede82-419c-5a3a-b6f4-ca62d0612356");    }    #[test]    fn keys_follow_the_contract() {        let db = "00000000-0000-4000-8000-000000000001";        assert_eq!(photo_key(db, "ab", "heic"), format!("{db}/photos/ab.heic"));        assert!(message_media_key(db, "whatsapp", "X1", "ab", "jpg").starts_with(&format!("{db}/messages/")));    }    #[test]    fn whatsapp_picture_keys_are_the_cores() {        let person = whatsapp_avatar_key("db", "p1", "ab", "jpg");        let group = whatsapp_group_picture_key("db", "t1", "ab", "jpg");        assert_eq!((person.as_str(), group.as_str()), ("db/people/p1/whatsapp/ab.jpg", "db/messages/t1/whatsapp/ab.jpg"));        assert!(cotton_core::media::keys::is_whatsapp_picture_key(&person) && cotton_core::media::keys::is_whatsapp_picture_key(&group));    }    #[test]    fn extension_and_type() {        assert_eq!(extension_of(Some("IMG.JPG"), None), "jpg");        assert_eq!(extension_of(None, Some("video/mp4")), "mp4");        assert_eq!(extension_of(Some("noext"), None), "bin");        assert_eq!(content_type_of(None, "heic"), "image/heic");        assert_eq!(content_type_of(Some("image/png"), "jpg"), "image/png");    }}