//! Readers that make a Cotton package out of another format, so a contacts//! file or a calendar file imports through the one path every package takes//! ([`cotton_store::cottonpkg::import`]): minted, ids kept, a second import//! changing nothing.//!//! - **vCard** (`.vcf`): each card is a `cotton_people` record, its phones//! and emails `cotton_person_handles`, its `NOTE` a `cotton_person_notes`//! entry ([`crate::import::vcard::parse_vcards`]).//! - **iCalendar** (`.ics`): the file is one calendar (`cotton_collections`),//! each VEVENT a `cotton_events` record, read by the same reader the CalDAV//! door uses ([`crate::import::ical`]).//!//! **A file never duplicates what the database holds** ([`Holdings`]). A card//! whose phone or email already names a person IS that person: the card fills//! only what the person lacks, and its new handles join them under the ids the//! Contacts import gives a handle (`person_handle_id`). An event whose `UID`//! (and `RECURRENCE-ID`) the database holds is that event, brought up to the//! file. Anything else takes an id derived from the file — a card's `UID` (else//! its name and handles), an event's `UID` — so the same file imported again//! lands on the same records and changes nothing.//!//! A record names its database by the reader's source name ([`VCARD_SOURCE`],//! [`ICS_SOURCE`]), which the import rewrites to its own, as it does a//! package's source id.use std::collections::BTreeMap;use serde_json::{json, Map, Value};use cotton_store::cottonpkg::{Manifest, Package, PackagedTable, FORMAT};use cotton_store::driver::Driver;use cotton_store::file_identity::{read_file_identity, FileIdentity};use cotton_store::protocol::derived_id::{derived_id, person_handle_id};use cotton_store::protocol::person_handles::{normalise_handle_in, HandleKind};use cotton_store::protocol::phone::Region;use cotton_store::schema::ddl::SCHEMA_VERSION;usecrate::import::ical::{ all_day_span, date_of, duration_ms, exdates_from_recurrence, instant_of, parse, rrule_from_recurrence, IcalEvent, NO_TITLE,};usecrate::import::vcard::parse_vcards;/// The database a vCard package's records name until an import makes them its own.pubconst VCARD_SOURCE: &str = "vcard";/// The database an iCalendar package's records name until an import makes them its own.pubconst ICS_SOURCE: &str = "ics";/// What the importing database already holds, as the readers ask it: who a/// handle names, a record by id, an event by its iCalendar identity.pubstructHoldings<'a> { db: &'a Driver, file: FileIdentity,}impl<'a> Holdings<'a> {/// The holdings of `db`, which must be a database with an identity.pubfn of(db: &'a Driver) -> Result<Holdings<'a>, String> {let file = read_file_identity(db) .map_err(|error| error.to_string())? .ok_or("this file has no identity yet, so there is nothing to import into")?;Ok(Holdings { db, file }) }/// The `answer` column of a query's first row.fn text(&self, sql: &str, params: &[&str]) -> Option<String> {let params: Vec<_> = params.iter().map(|param| param.to_string().into()).collect();self.db.get(sql, ¶ms).ok().flatten().and_then(|row| row.text("answer").map(str::to_string)) }/// The person a handle names here.fn handle_owner(&self, kind: HandleKind, normalised: &str) -> Option<String> {self.text("SELECT person_id AS answer FROM cotton_person_handles WHERE workspace_id = ? AND kind = ? AND normalised = ? AND trashed_at IS NULL", &[self.file.id().as_str(), kind.as_str(), normalised], ) }/// A record this file holds, in domain form.fn row(&self, table: &str, id: &str) -> Option<Map<String, Value>> {let spec = cotton_store::schema::package_shape::spec_on(self.db, table).ok().flatten()?;let row = self .db .get(&format!("SELECT * FROM {table} WHERE {} = ?", spec.pk), &[id.to_string().into()]) .ok() .flatten()?; cotton_store::schema::codecs::decode_row(spec.columns, row.columns()).ok() }/// The event this file holds under an iCalendar `UID`: the series or/// single event, or with `original` the one occurrence standing in for/// that instant.fn event(&self, uid: &str, original: Option<&str>) -> Option<String> {match original {None => self.text("SELECT id AS answer FROM cotton_events WHERE ical_uid = ? AND series_id IS NULL AND trashed_at IS NULL ORDER BY created_at, id", &[uid], ),Some(at) => self.text("SELECT id AS answer FROM cotton_events WHERE ical_uid = ? AND original_starts_at = ? AND trashed_at IS NULL ORDER BY created_at, id", &[uid, at], ), } }}/// `row` as a merge into `held`: every column `held` has no value for, and/// none it has — what a person already said stays said.fn filling(id: &str, row: Map<String, Value>, held: &Map<String, Value>) -> Map<String, Value> { row.into_iter() .filter(|(column, value)| { column == "id" || column == "workspace_id" || (!value.is_null() && held.get(column).is_none_or(Value::is_null)) }) .chain([("id".to_string(), Value::from(id))]) .collect()}fn object(value: Value) -> Map<String, Value> {match value {Value::Object(fields) => fields, _ => Map::new(), }}fn package(source: &str, now: &str, records: Vec<(&str, Vec<Map<String, Value>>)>) -> Package {Package { manifest: Manifest { format: FORMAT, schema_version: SCHEMA_VERSION, source_database: source.to_string(), exported_at: now.to_string(), tables: records .iter() .map(|(table, rows)| PackagedTable { table: table.to_string(), rows: rows.len() as u64 }) .collect(), media: Vec::new(), }, records: records.into_iter().map(|(table, rows)| (table.to_string(), rows)).collect(), media: BTreeMap::new(), }}/// A contacts file as a package of people, merged into what `holdings`/// holds. `region` reads a phone written without its country code, as the/// importing database reads one (`cotton_store::phone_fold::region_hint`)./// Two cards of one file that share a handle: the first keeps it, as an/// address book's household landline stays with the first person.pubfn package_from_vcards(text: &str, holdings: &Holdings<'_>, region: Option<Region>, now: &str) -> Package {let (mut people, mut handles, mut notes) = (Vec::new(), Vec::new(), Vec::new());letmut claimed: Vec<(HandleKind, String)> = Vec::new();for card in parse_vcards(text) {let forms: Vec<(HandleKind, &String, String)> = [(HandleKind::Phone, &card.phones), (HandleKind::Email, &card.emails)] .into_iter() .flat_map(|(kind, values)| { values.iter().filter_map(move |value| Some((kind, value, normalise_handle_in(kind, value, region)?))) }) .collect();let key = card .uid .clone() .unwrap_or_else(|| [vec![card.name.clone()], card.phones.clone(), card.emails.clone()].concat().join("\u{1f}"));let person = forms .iter() .find_map(|(kind, _, normalised)| holdings.handle_owner(*kind, normalised)) .unwrap_or_else(|| derived_id("cotton_people", &[VCARD_SOURCE, &key]));letmut row = object(json!({"id": person, "workspace_id": VCARD_SOURCE, "full_name": card.name, "org": card.org,"role_title": card.title, "contact_source": "import", "created_at": now, "updated_at": now, }));ifletSome(birthday) = card.birthday { row.insert("birth_month".to_string(), Value::from(birthday.month)); row.insert("birth_day".to_string(), Value::from(birthday.day)); row.insert("birth_year".to_string(), birthday.year.map_or(Value::Null, Value::from)); }let held = holdings.row("cotton_people", &person); people.push(match &held {Some(held) => filling(&person, row, held),None => row, });letmut position = BTreeMap::new();for (kind, value, normalised) in forms {if claimed.contains(&(kind, normalised.clone())) || holdings.handle_owner(kind, &normalised).is_some() {continue; } claimed.push((kind, normalised.clone()));let at = position.entry(kind.as_str()).or_insert(0_i64); handles.push(object(json!({"id": person_handle_id(holdings.file.namespace(), kind.as_str(), &normalised),"workspace_id": VCARD_SOURCE, "person_id": person, "kind": kind.as_str(), "value": value,"normalised": normalised, "source": "contacts", "position": *at,"created_at": now, "updated_at": now, }))); *at += 1; }ifletSome(note) = card.note {let id = derived_id("cotton_person_notes", &[&person, VCARD_SOURCE, ¬e]);if holdings.row("cotton_person_notes", &id).is_none() { notes.push(object(json!({"id": id, "person_id": person, "body": note, "noted_at": now, "created_at": now}))); } } } package( VCARD_SOURCE, now, vec![("cotton_people", people), ("cotton_person_handles", handles), ("cotton_person_notes", notes)], )}/// The event a VEVENT is: the one this file holds under its `UID` (and, for/// an occurrence, the instant it stands in for), else an id derived from them.fn event_id(event: &IcalEvent, holdings: &Holdings<'_>, zone: &str) -> String {let original = event.recurrence_id.as_ref().and_then(|at| instant_of(at, zone));ifletSome(held) = holdings.event(&event.uid, original.as_deref()) {return held; }let occurrence = event.recurrence_id.as_ref().map_or("", |time| time.value.as_str()); derived_id("cotton_events", &[ICS_SOURCE, &event.uid, occurrence])}/// When an event starts and ends, and whether it is all day: an all-day span/// as [`all_day_span`] stores it, a timed one by its zone (`zone` for a/// floating time), the end by `DTEND` or else `DURATION`.fn span_of(event: &IcalEvent, zone: &str) -> Option<(String, Option<String>, bool)> {let start = event.start.as_ref()?;if start.is_date {let first = date_of(&start.value)?;let end = match (&event.end, &event.duration) { (Some(end), _) => date_of(&end.value), (None, Some(duration)) => {let days = duration_ms(duration)? / 86_400_000;let ms = cotton_store::protocol::js::parse_date_ms(&format!("{first}T00:00:00Z"))?; cotton_store::protocol::js::to_iso_string(ms + days * 86_400_000).map(|iso| iso[..10].to_string()) } (None, None) => None, };let (starts_at, ends_at) = all_day_span(&first, end.as_deref(), zone)?;returnSome((starts_at, Some(ends_at), true)); }let starts_at = instant_of(start, zone)?;let ends_at = match (&event.end, &event.duration) { (Some(end), _) => instant_of(end, zone), (None, Some(duration)) => {let at = cotton_store::protocol::js::parse_date_ms(&starts_at)?; cotton_store::protocol::js::to_iso_string(at + duration_ms(duration)?) } (None, None) => None, };Some((starts_at, ends_at, false))}fn trimmed(value: Option<&String>) -> Option<String> { value.map(|text| text.trim().to_string()).filter(|text| !text.is_empty())}/// A calendar file as a package: one calendar named `calendar`, holding every/// event the file has that `holdings` does not; an event it holds under the/// same `UID` is updated where it is, in its own calendar. A floating time is/// read in `zone`. A cancelled event is left out; a cancelled occurrence of a/// series in the file is one more instant its series skips.pubfn package_from_ics(text: &str, holdings: &Holdings<'_>, calendar: &str, zone: &str, now: &str) -> Package {let collection = derived_id("cotton_collections", &[ICS_SOURCE, calendar]);let events = parse(text);let masters: BTreeMap<&str, String> = events .iter() .filter(|event| event.recurrence_id.is_none()) .map(|event| (event.uid.as_str(), event_id(event, holdings, zone))) .collect();letmut cancelled: BTreeMap<String, Vec<String>> = BTreeMap::new();for event in events.iter().filter(|event| event.status.as_deref() == Some("CANCELLED")) {iflet (Some(at), Some(master)) = (event.recurrence_id.as_ref(), masters.get(event.uid.as_str())) {ifletSome(instant) = instant_of(at, zone) { cancelled.entry(master.clone()).or_default().push(instant); } } }letmut rows = Vec::new();for event in events.iter().filter(|event| event.status.as_deref() != Some("CANCELLED")) {letSome((starts_at, ends_at, all_day)) = span_of(event, zone) else { continue };let id = event_id(event, holdings, zone);letmut exdates = exdates_from_recurrence(Some(&event.recurrence), zone).unwrap_or_default(); exdates.extend(cancelled.remove(&id).unwrap_or_default()); exdates.sort(); exdates.dedup();letmut row = object(json!({"id": id, "collection_id": collection,"title": trimmed(event.summary.as_ref()).unwrap_or_else(|| NO_TITLE.to_string()),"notes": trimmed(event.description.as_ref()), "location": trimmed(event.location.as_ref()),"starts_at": starts_at, "ends_at": ends_at, "all_day": all_day,"rrule": rrule_from_recurrence(Some(&event.recurrence)),"exdates": if exdates.is_empty() { Value::Null } else { json!(exdates) },"ical_uid": event.uid, "created_at": now, "updated_at": now, }));ifletSome(tzid) = event.start.as_ref().and_then(|start| start.tzid.clone()) { row.insert("timezone".to_string(), Value::from(tzid)); }iflet (Some(at), Some(master)) = (event.recurrence_id.as_ref(), masters.get(event.uid.as_str())) { row.insert("series_id".to_string(), Value::from(master.clone())); row.insert("original_starts_at".to_string(), instant_of(at, zone).map_or(Value::Null, Value::from)); }// An event the database holds stays in the calendar it is in.if holdings.row("cotton_events", &id).is_some() { row.remove("collection_id"); } rows.push(row); }let calendar_row = object(json!({"id": collection, "workspace_id": ICS_SOURCE, "kind": "calendar", "name": calendar,"is_default": false, "created_at": now, })); package(ICS_SOURCE, now, vec![("cotton_collections", vec![calendar_row]), ("cotton_events", rows)])}/// The package a file the person brought is: a `.cottonpkg` as it is, a/// `.vcf` or an `.ics` read into one against what `db` holds. `region` and/// `zone` are the importing database's ([`package_from_vcards`],/// [`package_from_ics`]); an `.ics` becomes a calendar named after the file.pubfn package_of_file( file_name: &str, bytes: &[u8], db: &Driver, region: Option<Region>, zone: &str, now: &str,) -> Result<Package, String> {let path = std::path::Path::new(file_name);let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();let text = || String::from_utf8(bytes.to_vec()).map_err(|_| format!("{file_name} is not UTF-8 text"));match extension.as_str() { cotton_store::cottonpkg::EXTENSION => Package::from_bytes(bytes).map_err(|error| error.to_string()),"vcf" | "vcard" => Ok(package_from_vcards(&text()?, &Holdings::of(db)?, region, now)),"ics" | "ical" | "ifb" => {let calendar = path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(file_name);Ok(package_from_ics(&text()?, &Holdings::of(db)?, calendar, zone, now)) } _ => Err(format!("{file_name} is not a file Cotton imports: a .cottonpkg, a .vcf or an .ics")), }}#[cfg(test)]#[path = "package_readers_tests.rs"]mod tests;