//! Which email attachments are PHOTOS, and the rows they become (schema v41) //! — the port of `packages/core/src/engine/emailPhotos.ts`. //! //! The owner's ask: "email photos should be captured too — they are not //! today." An image attached to an email used to be an entry in the email //! row's `attachments` JSON and nothing else: bytes under a key, invisible to //! the Photos grid, to `list_photos`, to the faces and the places. This module //! is the decision half of fixing that — pure, so every rule below has a test //! — and `media_items.rs` is its sibling for chat messages. //! //! WHICH attachments: an image type Cotton keeps as a photo, with bytes //! already in the workspace's object store, above a size floor. The floor is //! the whole point of the filter: a mailbox is full of 2 KB signature logos //! and 1-pixel tracking images, every one of them `image/png`, and a grid //! that showed them would be a grid nobody opens. //! //! WHAT they become: a `cotton_photos` row addressed by the bytes' sha256 — //! the SAME row a forwarded copy of the picture hashes to from a chat or the //! library — and an `email` sighting naming the `cotton_emails` row. The row //! reuses the attachment's own key: the bytes are already there, and a second //! object would double what the person stores to gain nothing. use cotton_store::protocol::derived_id::{media_sighting_id, photo_record_id}; use serde::{Deserialize, Serialize}; use crate::rules::media_items::{MediaFamily, PhotoInsert}; /// The attachment as the email tools carry it — `name` always, the rest when /// known. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EmailAttachmentLike { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub mime: Option, /// Bytes, when the sender's mail server stated a size. /// /// `f64`, like every other number that arrives inside a JSON column: the /// comparisons below are the TypeScript's own, made against a JavaScript /// number, and rounding at the boundary would move the floor. #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option, } /// Below this an image is a logo, an icon or a tracking pixel, not a picture /// the person would want to see in their Photos. 32 KiB: a phone camera's /// smallest JPEG is hundreds of kilobytes, a screenshot tens; the signature /// logos and one-pixel GIFs a mailbox is full of are one to ten. pub const EMAIL_PHOTO_MIN_BYTES: f64 = 32.0 * 1024.0; /// Above this an image attachment is not fetched by the Gmail import. Gmail /// caps a message at 25 MB, so nothing real is refused; the ceiling exists so /// a malformed size can never make the import pull a gigabyte on trust. pub const EMAIL_PHOTO_MAX_BYTES: f64 = 25.0 * 1024.0 * 1024.0; /// The image types an email attachment is kept as a photo under. /// /// Narrower than `MEDIA_LIMITS.photo` by `image/gif` — an animated GIF in an /// email is a signature or a reaction, not a photograph — and wider by /// `image/heif`, which a modern phone attaches when it mails a picture. pub const EMAIL_PHOTO_CONTENT_TYPES: [&str; 5] = [ "image/jpeg", "image/png", "image/webp", "image/heic", "image/heif", ]; /// The type an extension implies when the attachment carries no MIME. const CONTENT_TYPE_BY_EXTENSION: [(&str, &str); 6] = [ ("jpg", "image/jpeg"), ("jpeg", "image/jpeg"), ("png", "image/png"), ("webp", "image/webp"), ("heic", "image/heic"), ("heif", "image/heif"), ]; /// Why an attachment is not becoming a photo. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum EmailPhotoSkipReason { NoBytes, NotAnImage, TooSmall, TooLarge, } impl EmailPhotoSkipReason { pub const fn as_str(self) -> &'static str { match self { EmailPhotoSkipReason::NoBytes => "no_bytes", EmailPhotoSkipReason::NotAnImage => "not_an_image", EmailPhotoSkipReason::TooSmall => "too_small", EmailPhotoSkipReason::TooLarge => "too_large", } } } /// Keep it, with the type it is kept under — or skip it, with the reason. /// /// The TypeScript discriminates on a `photo: boolean` field; Rust uses the /// variant, because nothing serialises this — it is read by the importer in /// the same process that asked. A caller that wants the TypeScript's shape /// builds it from `is_photo()` and the payload. #[derive(Debug, Clone, PartialEq, Eq)] pub enum EmailPhotoDecision { Photo { content_type: String }, Skip { reason: EmailPhotoSkipReason }, } impl EmailPhotoDecision { pub fn is_photo(&self) -> bool { matches!(self, EmailPhotoDecision::Photo { .. }) } /// The type it would be kept under, or `None` for a skip. pub fn content_type(&self) -> Option<&str> { match self { EmailPhotoDecision::Photo { content_type } => Some(content_type), EmailPhotoDecision::Skip { .. } => None, } } pub fn reason(&self) -> Option { match self { EmailPhotoDecision::Photo { .. } => None, EmailPhotoDecision::Skip { reason } => Some(*reason), } } } /// `name.slice(name.lastIndexOf(".") + 1).toLowerCase()`, and the empty string /// when there is no dot at all. fn extension_of(name: &str) -> String { match name.rfind('.') { None => String::new(), Some(dot) => name[dot + 1..].to_lowercase(), } } /// The image type of an attachment, from its MIME first and its name second, /// or `None` when it is not an image Cotton keeps as a photo. /// /// A MIME that is only whitespace falls through to the NAME, because the /// TypeScript trims after splitting on `;` and then asks for `length > 0` — /// a detail pinned by vector rather than reasoned about, since the obvious /// reading (an empty MIME wins and answers null) is wrong. pub fn email_photo_content_type(attachment: &EmailAttachmentLike) -> Option { let mime = attachment.mime.as_deref().unwrap_or("").to_lowercase(); let mime = mime.split(';').next().unwrap_or("").trim(); if !mime.is_empty() { return EMAIL_PHOTO_CONTENT_TYPES .iter() .find(|kept| **kept == mime) .map(|kept| (*kept).to_string()); } let extension = extension_of(&attachment.name); CONTENT_TYPE_BY_EXTENSION .iter() .find(|(ext, _)| *ext == extension) .map(|(_, content_type)| (*content_type).to_string()) } /// Is this many bytes a picture rather than a logo? pub fn is_above_email_photo_floor(size_bytes: f64) -> bool { size_bytes >= EMAIL_PHOTO_MIN_BYTES } /// Should this attachment become a photo? /// /// Judged on what the email row knows. A missing `size` passes here — the /// writer measures the bytes it fetches and applies the floor again — because /// refusing an attachment for not stating its size would drop every picture an /// assistant filed without one. pub fn email_photo_candidate(attachment: &EmailAttachmentLike) -> EmailPhotoDecision { // `if (!attachment.key)` — an EMPTY key is falsy in JavaScript, so a blank // string is "no bytes" here just as an absent one is. if attachment.key.as_deref().unwrap_or("").is_empty() { return EmailPhotoDecision::Skip { reason: EmailPhotoSkipReason::NoBytes, }; } let Some(content_type) = email_photo_content_type(attachment) else { return EmailPhotoDecision::Skip { reason: EmailPhotoSkipReason::NotAnImage, }; }; if let Some(size) = attachment.size { if !is_above_email_photo_floor(size) { return EmailPhotoDecision::Skip { reason: EmailPhotoSkipReason::TooSmall, }; } } EmailPhotoDecision::Photo { content_type } } /// Should the Gmail import FETCH this attachment's bytes? /// /// The same picture test as `email_photo_candidate` without the key (there is /// none yet — fetching is how it gets one) and with the ceiling: the row's /// `size` is Gmail's own count of the part, so a tiny or oversize one is /// refused before a byte moves. A part with no size is fetched and measured. pub fn email_photo_fetch_decision(attachment: &EmailAttachmentLike) -> EmailPhotoDecision { let Some(content_type) = email_photo_content_type(attachment) else { return EmailPhotoDecision::Skip { reason: EmailPhotoSkipReason::NotAnImage, }; }; if let Some(size) = attachment.size { if !is_above_email_photo_floor(size) { return EmailPhotoDecision::Skip { reason: EmailPhotoSkipReason::TooSmall, }; } if size > EMAIL_PHOTO_MAX_BYTES { return EmailPhotoDecision::Skip { reason: EmailPhotoSkipReason::TooLarge, }; } } EmailPhotoDecision::Photo { content_type } } /// The extension a photo key carries for an image type. The empty string for /// anything this module does not keep — the TypeScript's `default` arm, and /// the reason a caller must ask `email_photo_content_type` first. pub fn email_photo_extension(content_type: &str) -> &'static str { match content_type { "image/jpeg" => "jpg", "image/png" => "png", "image/webp" => "webp", "image/heic" => "heic", "image/heif" => "heif", _ => "", } } /// Where an email sighting was seen. Its own single-variant enum rather than a /// widening of `media_items::SightingSource`, because the TypeScript declares /// two separate literal types for the same reason: a chat sighting that could /// say `email`, or an email sighting that could carry a `thread_id`, is a row /// nothing can join back. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum EmailSightingSource { Email, } impl EmailSightingSource { pub const fn as_str(self) -> &'static str { match self { EmailSightingSource::Email => "email", } } } /// A `cotton_media_sightings` row for a picture seen on an email (v41). #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct EmailSightingInsert { pub id: String, pub workspace_id: String, pub record_kind: MediaFamily, pub record_id: String, pub source: EmailSightingSource, /// The `cotton_emails` row the attachment came on. pub source_id: String, /// Always null: an email sighting names no chat. pub thread_id: Option, pub key: String, pub seen_at: String, pub created_at: String, pub updated_at: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EmailPhotoInput { pub workspace_id: String, /// The `cotton_emails` row id. pub email_id: String, /// The email's `sent_at` — the picture's `taken_at` when it is new, and /// the sighting's `seen_at` always. pub sent_at: String, pub key: String, pub content_type: String, pub sha256: String, pub size_bytes: i64, pub now: String, } /// The row and the sighting one email attachment becomes. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct EmailPhotoRows { pub photo: PhotoInsert, pub sighting: EmailSightingInsert, } /// Build both rows. The photo's id is the BYTES' digest, so a picture mailed /// to you and the same picture forwarded in a chat are one row with two /// sightings. pub fn email_photo_rows(input: &EmailPhotoInput) -> EmailPhotoRows { let id = photo_record_id(&input.sha256); EmailPhotoRows { photo: PhotoInsert { id: id.clone(), workspace_id: input.workspace_id.clone(), key: input.key.clone(), sha256: input.sha256.clone(), content_type: input.content_type.clone(), size_bytes: input.size_bytes, // Nothing decodes the picture here: dimensions arrive with the // enrichment the Mac writes, as they do for a chat photo. width: None, height: None, taken_at: input.sent_at.clone(), preview: None, created_at: input.now.clone(), updated_at: input.now.clone(), }, sighting: EmailSightingInsert { id: media_sighting_id( MediaFamily::Photo.as_str(), &id, EmailSightingSource::Email.as_str(), Some(&input.email_id), ), workspace_id: input.workspace_id.clone(), record_kind: MediaFamily::Photo, record_id: id, source: EmailSightingSource::Email, source_id: input.email_id.clone(), thread_id: None, key: input.key.clone(), seen_at: input.sent_at.clone(), created_at: input.now.clone(), updated_at: input.now.clone(), }, } } #[cfg(test)] #[path = "email_photos_tests.rs"] mod tests;