//! `days.export { timezone, group? }` — Days' events and to-dos as one `.ics` //! file the phone hands to the share sheet (owner, 23 Nov 2026; CONTRACT.md //! "Export"). Without `group`: every event and every to-do, `Days.ics`. With //! a to-do group (either id of a fold): that group's to-dos only, //! `.ics`. The file is written under the data directory's //! `cache/exports/days/` (emptied first) and answered by its path, never its //! bytes: //! //! ```json //! { "path": "…/Days.ics", "file_name": "Days.ics", "mime": "text/calendar", "count": 42 } //! ``` //! //! What a row becomes is [`cotton_core::export::ics`]'s; this reads the rows. //! A binned event or to-do is left out; a declined invitation and a Google //! event are the person's like any other. A repeating to-do goes as each of //! its occurrences the copy holds, with no rule. use std::collections::HashMap; use cotton_core::cotton_rules::js::parse_date_ms; use cotton_core::cotton_rules::moment_split::split_moment; use cotton_core::cotton_rules::zoned_clock::local_day; use cotton_core::export::ics::{self, Status, When}; use cotton_store::driver::Row; use serde_json::{json, Value}; use super::{database_zone, group_arg, optional, rows, sql, todo_groups, ws, Ctx, MethodError}; /// A line of the days set, filled. fn line(name: &str, fills: &[(&str, &str)]) -> Result { cotton_core::rules::shell_lines::LineSet::shipped("days") .and_then(|lines| lines.say(name, fills)) .ok_or_else(|| MethodError::new("unreadable", format!("the days set says no line {name}"))) } /// The file's name without its kind: what the person reads, with nothing a folder refuses. fn file_base(name: &str, fallback: &str) -> String { let clean: String = name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() { ' ' } else { c }).collect(); let clean = clean.split_whitespace().collect::>().join(" "); if clean.is_empty() { fallback.to_string() } else { clean.chars().take(80).collect() } } /// The calendar as written, its name and how many entries it holds. pub(super) struct Written { pub text: String, pub name: String, pub count: usize, } pub(super) fn calendar(ctx: &mut Ctx<'_>, request: &Value) -> Result { let zone = super::text(request, "timezone").map(str::to_string).unwrap_or_else(|| "UTC".to_string()); let db_zone = database_zone(ctx, &zone)?; let groups = todo_groups(ctx)?; let only = group_arg(ctx, request)?; let events = if only.is_some() { Vec::new() } else { events(ctx, &db_zone)? }; let todos: Vec = todos(ctx, &db_zone)? .into_iter() .filter(|(id, _)| only.as_ref().is_none_or(|group| group.members.contains(id))) .map(|(id, mut todo)| { todo.groups = groups.iter().filter(|g| g.members.contains(&id)).map(|g| g.name.clone()).collect(); todo }) .collect(); let name = match &only { Some(group) => group.name.clone(), None => line("export.file", &[])?, }; let count = events.len() + todos.len(); Ok(Written { text: ics::calendar(&name, &events, &todos, ctx.now.timestamp_millis()), name, count }) } pub(super) fn export(ctx: &mut Ctx<'_>, dir: &std::path::Path, request: &Value) -> Result { let written = calendar(ctx, request)?; if written.count == 0 { return Err(MethodError::new("refused", line("export.nothing", &[])?)); } // not a copy: an export. let _ = std::fs::remove_dir_all(dir); std::fs::create_dir_all(dir).map_err(|why| MethodError::new("unwritten", format!("the exports folder could not be made: {why}")))?; let fallback = line("export.file", &[])?; let file_name = format!("{}.ics", file_base(&written.name, &fallback)); let path = dir.join(&file_name); // not a copy: an export. std::fs::write(&path, written.text.as_bytes()).map_err(|why| MethodError::new("unwritten", format!("{file_name} could not be written: {why}")))?; Ok(json!({ "path": path.to_string_lossy(), "file_name": file_name, "mime": "text/calendar", "count": written.count })) } /// A row's UID where the store keeps none of its own (Google's `ical_uid`). const UID_HOST: &str = "@cottondb.com"; fn uid_of(row: &Row) -> String { match row.text("ical_uid").filter(|uid| !uid.trim().is_empty()) { Some(uid) => uid.to_string(), None => format!("{}{UID_HOST}", row.text("id").unwrap_or_default()), } } fn events(ctx: &Ctx<'_>, db_zone: &str) -> Result, MethodError> { let extra = ["ical_uid", "timezone", "event_place", "your_note"].iter().map(|column| optional(ctx, "cotton_events", column)).collect::, _>>()?.join(", "); let found = rows( ctx, &format!( "SELECT id, title, notes, location, starts_at, ends_at, all_day, rrule, exdates, series_id, original_starts_at, created_at, {extra} FROM cotton_events WHERE trashed_at IS NULL ORDER BY starts_at ASC, id ASC" ), &[], )?; let by_id: HashMap<&str, &Row> = found.iter().filter_map(|row| Some((row.text("id")?, row))).collect(); let mut out = Vec::new(); for row in &found { let all_day = row.int("all_day").unwrap_or(0) != 0; let master = row.text("series_id").and_then(|id| by_id.get(id).copied()); let zone = row.text("timezone").or_else(|| master.and_then(|m| m.text("timezone"))).filter(|z| !z.trim().is_empty()).unwrap_or(db_zone).to_string(); let repeats = row.text("rrule").is_some_and(|r| !r.trim().is_empty()) || master.is_some(); let when = |raw: Option<&str>| -> Option { let ms = parse_date_ms(raw?)?; Some(if all_day { When::Day(local_day(ms, db_zone).ok()?) } else if repeats { When::Zoned { ms, zone: zone.clone() } } else { When::Instant(ms) }) }; let start = when(row.text("starts_at")); // An all-day event's end is kept as the last instant of its last day; the file says the day after. let end = if all_day { match (start.clone(), row.text("ends_at").and_then(parse_date_ms).and_then(|ms| local_day(ms, db_zone).ok())) { (Some(When::Day(first)), Some(last)) if last >= first => Some(When::Day(last + 1)), (Some(When::Day(first)), _) => Some(When::Day(first + 1)), _ => None, } } else { when(row.text("ends_at")) }; let taken_out = row .text("exdates") .and_then(|raw| serde_json::from_str::>(raw).ok()) .unwrap_or_default() .iter() .filter_map(|at| when(Some(at))) .collect(); let notes = [row.text("notes"), row.text("your_note")].into_iter().flatten().map(str::trim).filter(|n| !n.is_empty()).collect::>().join("\n\n"); let place = row.text("event_place").or_else(|| row.text("location")).map(str::to_string); out.push(ics::Event { uid: master.map(uid_of).unwrap_or_else(|| uid_of(row)), title: row.text("title").unwrap_or_default().to_string(), notes: Some(notes).filter(|n| !n.is_empty()), place, start, end, rule: if master.is_some() { None } else { row.text("rrule").map(str::to_string) }, taken_out, replaces: master.and_then(|_| when(row.text("original_starts_at"))), made: row.text("created_at").and_then(parse_date_ms), }); } Ok(out) } /// Each to-do with its id. fn todos(ctx: &Ctx<'_>, db_zone: &str) -> Result, MethodError> { let found = rows( ctx, "SELECT id, title, notes, status, due_at, completed_at, created_at FROM cotton_todos WHERE workspace_id = ?1 AND trashed_at IS NULL ORDER BY created_at ASC, id ASC", &[ws(ctx)], )?; let mut out = Vec::new(); for row in &found { // Midnight in the database's zone is a day with no time (the store's contract); any other instant is itself. let due = match row.text("due_at") { Some(at) => match (parse_date_ms(at), split_moment(at, db_zone).map_err(sql)?) { (Some(ms), split) if split.time.is_some() => Some(When::Instant(ms)), (Some(ms), _) => local_day(ms, db_zone).ok().map(When::Day), _ => None, }, None => None, }; let id = row.text("id").unwrap_or_default().to_string(); out.push((id.clone(), ics::Todo { uid: format!("{id}{UID_HOST}"), title: row.text("title").unwrap_or_default().to_string(), details: row.text("notes").map(str::to_string), due, status: match row.text("status") { Some("done") => Status::Done, Some("dropped") => Status::Dropped, _ => Status::Open, }, done_at: row.text("completed_at").and_then(parse_date_ms), groups: Vec::new(), made: row.text("created_at").and_then(parse_date_ms), })); } Ok(out) } #[cfg(test)] #[path = "days_export_tests.rs"] mod tests;