Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
A reminder with a time now actually makes a phone ring
Yashwanth Kamireddie420e76d2005
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rsindex 341475e..a2daf20 100644--- a/crates/quince-icloud/src/reminders.rs+++ b/crates/quince-icloud/src/reminders.rs@@ -3156,3 +3156,188 @@ mod other_accounts_tests {assert_eq!(list_from_record(&bare).unwrap().title, "Reminders");}}++/// The date components an alarm is set by, as Apple writes them.+///+/// `DateComponentsData` is declared BYTES and holds JSON — the same trick the sort hint uses.+/// Written out rather than derived from a timestamp at read time because the components carry+/// a named zone: a reminder set for nine in the morning is for nine in the morning wherever+/// the person happens to be, which a fixed instant is not.+fn date_components(at_seconds: i64, timezone: &str) -> Result<String> {+ let zone = jiff::tz::TimeZone::get(timezone).unwrap_or_else(|_| jiff::tz::TimeZone::system());+ let moment = jiff::Timestamp::from_second(at_seconds)+ .map_err(|e| Error::Protocol(format!("that is not a time: {e}")))?+ .to_zoned(zone.clone());+ let components = serde_json::json!({+ "era": 1,+ "year": moment.year(),+ "month": moment.month(),+ "day": moment.day(),+ "hour": moment.hour(),+ "minute": moment.minute(),+ "second": 0,+ "timeZone": { "identifier": zone.iana_name().unwrap_or("UTC") },+ });+ use base64::{engine::general_purpose::STANDARD as B64, Engine};+ Ok(B64.encode(+ serde_json::to_vec(&components)+ .map_err(|e| Error::Protocol(format!("could not write the alarm's date: {e}")))?,+ ))+}++/// Give a reminder the alert that makes a phone actually ring.+///+/// A due date on its own notifies nobody. Every reminder on a real account that has a time has+/// exactly one `Alarm`, which points at an `AlarmTrigger` holding the date to fire on — three+/// records, not one field. Reminders written here had the date and no alarm, so they showed+/// the right time on a phone and then said nothing when it arrived.+///+/// An all-day reminder has no alarm, which is also what the phone does: there is no moment to+/// ring at. Clearing the date takes the alarm away with it.+///+/// # Errors+/// When Apple refuses any of the three writes, or the reminder cannot be read back.+pub async fn set_alarm_cloudkit(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ reminder_guid: &str,+ at_seconds: Option<i64>,+ timezone: &str,+) -> Result<()> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let current = client.lookup_record(ZONE, reminder_guid).await?;+ let existing: Vec<String> = current+ .as_ref()+ .and_then(|r| r.pointer("/fields/AlarmIDs/value"))+ .and_then(Value::as_array)+ .map(|ids| {+ ids.iter()+ .filter_map(|v| v.as_str().map(ToString::to_string))+ .collect()+ })+ .unwrap_or_default();++ // Whatever was there goes, whether it is being replaced or removed. An alarm left behind+ // pointing at an old time is worse than none: the phone rings for something that moved.+ for id in &existing {+ let alarm = client.lookup_record(ZONE, &format!("Alarm/{id}")).await?;+ if let Some(trigger) = alarm+ .as_ref()+ .and_then(|a| a.pointer("/fields/TriggerID/value"))+ .and_then(Value::as_str)+ {+ client+ .delete_record(ZONE, &format!("AlarmTrigger/{trigger}"))+ .await?;+ }+ client.delete_record(ZONE, &format!("Alarm/{id}")).await?;+ }++ let Some(at) = at_seconds else {+ return client+ .update_record(+ ZONE,+ reminder_guid,+ "Reminder",+ None,+ serde_json::json!({ "AlarmIDs": { "type": "STRING_LIST", "value": [] } }),+ )+ .await+ .map(|_| ());+ };++ let alarm_id = uuid::Uuid::new_v4().to_string().to_uppercase();+ let trigger_id = uuid::Uuid::new_v4().to_string().to_uppercase();++ // The alarm first: the trigger points back at it with a reference Apple validates, so it+ // has to exist by then. The alarm's own TriggerID is a plain string and can name a record+ // that is still to come.+ client+ .create_record(+ ZONE,+ &format!("Alarm/{alarm_id}"),+ "Alarm",+ serde_json::json!({+ "AlarmUID": { "type": "STRING", "value": alarm_id },+ "TriggerID": { "type": "STRING", "value": trigger_id },+ "Reminder": client.reference_to(ZONE, reminder_guid),+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },+ "Imported": { "type": "NUMBER_INT64", "value": 0 },+ }),+ )+ .await?;++ client+ .create_record(+ ZONE,+ &format!("AlarmTrigger/{trigger_id}"),+ "AlarmTrigger",+ serde_json::json!({+ "Alarm": client.reference_to(ZONE, &format!("Alarm/{alarm_id}")),+ "DateComponentsData": {+ "type": "BYTES",+ "value": date_components(at, timezone)?,+ },+ "Type": { "type": "STRING", "value": "Date" },+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },+ "Imported": { "type": "NUMBER_INT64", "value": 0 },+ }),+ )+ .await?;++ client+ .update_record(+ ZONE,+ reminder_guid,+ "Reminder",+ None,+ serde_json::json!({+ "AlarmIDs": { "type": "STRING_LIST", "value": [alarm_id] },+ }),+ )+ .await+ .map(|_| ())+}++#[cfg(test)]+mod alarm_tests {+ use super::*;+ use base64::{engine::general_purpose::STANDARD as B64, Engine};++ fn decoded(at: i64, tz: &str) -> Value {+ serde_json::from_slice(&B64.decode(date_components(at, tz).unwrap()).unwrap()).unwrap()+ }++ /// Apple's own alarm on this account decodes to exactly this shape.+ #[test]+ fn the_components_are_the_local_wall_clock_not_the_instant() {+ // A whole minute, the way an alarm always lands on one.+ let at = 1_789_382_400;+ let india = decoded(at, "Asia/Kolkata");+ let utc = decoded(at, "UTC");+ assert_eq!(india["era"], 1);+ assert_eq!(india["second"], 0);+ assert_eq!(india["timeZone"]["identifier"], "Asia/Kolkata");+ assert_eq!(utc["timeZone"]["identifier"], "UTC");+ assert_ne!(+ india["hour"], utc["hour"],+ "the same instant is a different hour in each place, which is the point"+ );+ }++ /// Nine in the morning is nine in the morning wherever the person is, so the zone travels+ /// with the alarm rather than being resolved away.+ #[test]+ fn a_named_zone_is_carried_rather_than_flattened() {+ let v = decoded(1_757_000_000, "America/New_York");+ assert_eq!(v["timeZone"]["identifier"], "America/New_York");+ }++ /// A zone this machine has never heard of must not take the alarm down with it.+ #[test]+ fn an_unknown_zone_falls_back_rather_than_failing() {+ assert!(date_components(1_757_000_000, "Mars/Olympus_Mons").is_ok());+ assert!(date_components(1_757_000_000, "").is_ok());+ }+}diff --git a/probe/examples/alarm_write.rs b/probe/examples/alarm_write.rsnew file mode 100644index 0000000..118c780--- /dev/null+++ b/probe/examples/alarm_write.rs@@ -0,0 +1,166 @@+//! Throwaway: a reminder written here gets the alarm that makes a phone ring.+use anyhow::{anyhow, Result};+use base64::{engine::general_purpose::STANDARD as B64, Engine};+use serde_json::Value;++fn f<'a>(r: &'a Value, k: &str) -> Option<&'a Value> {+ r.pointer(&format!("/fields/{k}/value"))+}++#[tokio::main]+async fn main() -> Result<()> {+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client+ .session()+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;+ let http = client.http().clone();+ let params = client.service_params();+ let zone = quince_icloud::cloudkit::ZoneClient::new(+ &http,+ &root,+ "com.apple.reminders",+ params.clone(),+ );++ // A real list to put it in.+ let walk = zone.all_records("Reminders", None).await?;+ let list = walk+ .records+ .iter()+ .filter(|r| r.get("recordType").and_then(Value::as_str) == Some("List"))+ .find(|r| {+ f(r, "Deleted").and_then(Value::as_i64) != Some(1)+ && f(r, "IsGroup").and_then(Value::as_i64) != Some(1)+ })+ .and_then(|r| r.pointer("/recordName").and_then(Value::as_str))+ .ok_or_else(|| anyhow!("no list to use"))?+ .to_string();++ let guid = quince_icloud::reminders::create_cloudkit(+ &http,+ &root,+ params.clone(),+ &list,+ "Quince alarm test — safe to delete",+ )+ .await?;+ println!("created {guid} in {list}");++ let due = jiff::Timestamp::now().as_second() + 3600;+ quince_icloud::reminders::set_alarm_cloudkit(+ &http,+ &root,+ params.clone(),+ &guid,+ Some(due),+ "Asia/Kolkata",+ )+ .await?;++ // Read it back from Apple, not from what we sent.+ let after = zone.all_records("Reminders", None).await?;+ let reminder = after+ .records+ .iter()+ .find(|r| r.pointer("/recordName").and_then(Value::as_str) == Some(guid.as_str()))+ .ok_or_else(|| anyhow!("the reminder is gone"))?;+ let ids: Vec<String> = f(reminder, "AlarmIDs")+ .and_then(Value::as_array)+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(ToString::to_string))+ .collect()+ })+ .unwrap_or_default();+ println!("AlarmIDs after: {ids:?}");+ if ids.len() != 1 {+ return Err(anyhow!("expected exactly one alarm"));+ }++ let alarm = after+ .records+ .iter()+ .find(|r| {+ r.pointer("/recordName").and_then(Value::as_str)+ == Some(format!("Alarm/{}", ids[0]).as_str())+ })+ .ok_or_else(|| anyhow!("the Alarm record is not in the zone"))?;+ let trigger_id = f(alarm, "TriggerID")+ .and_then(Value::as_str)+ .ok_or_else(|| anyhow!("no TriggerID"))?;+ println!("Alarm -> trigger {trigger_id}");++ let trigger = after+ .records+ .iter()+ .find(|r| {+ r.pointer("/recordName").and_then(Value::as_str)+ == Some(format!("AlarmTrigger/{trigger_id}").as_str())+ })+ .ok_or_else(|| anyhow!("the AlarmTrigger record is not in the zone"))?;+ let raw = f(trigger, "DateComponentsData")+ .and_then(Value::as_str)+ .ok_or_else(|| anyhow!("no date"))?;+ println!("trigger Type={:?}", f(trigger, "Type"));+ println!(+ "trigger fires at: {}",+ String::from_utf8_lossy(&B64.decode(raw)?)+ );++ // Clearing must take all three away, not leave a phone ringing for a time that moved.+ quince_icloud::reminders::set_alarm_cloudkit(+ &http,+ &root,+ params.clone(),+ &guid,+ None,+ "Asia/Kolkata",+ )+ .await?;+ let cleared = zone.all_records("Reminders", None).await?;+ let still_there = cleared+ .records+ .iter()+ .filter(|r| {+ let n = r+ .pointer("/recordName")+ .and_then(Value::as_str)+ .unwrap_or("");+ (n == format!("Alarm/{}", ids[0]) || n == format!("AlarmTrigger/{trigger_id}"))+ && f(r, "Deleted").and_then(Value::as_i64) != Some(1)+ })+ .count();+ let after_clear = cleared+ .records+ .iter()+ .find(|r| r.pointer("/recordName").and_then(Value::as_str) == Some(guid.as_str()))+ .and_then(|r| f(r, "AlarmIDs").and_then(Value::as_array).map(Vec::len))+ .unwrap_or(0);+ println!("after clearing: {still_there} alarm records left, AlarmIDs has {after_clear}");++ // Tidy up: mark it deleted the way the app does.+ let store = std::env::temp_dir().join(format!("quince-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&store)?;+ let mut library = quince_core::Library::open(&store)?;+ quince_icloud::reminders::sync_cloudkit(&http, &root, params.clone(), &mut library, None)+ .await?;+ if let Some(r) = library+ .reminder_lists()?+ .iter()+ .flat_map(|l| library.reminders_in(&l.guid, true).unwrap_or_default())+ .find(|r| r.guid == guid)+ {+ quince_icloud::reminders::delete_cloudkit(&http, &root, params.clone(), &r).await?;+ println!("deleted the test reminder");+ }+ if still_there > 0 || after_clear > 0 {+ return Err(anyhow!("clearing left something behind"));+ }+ println!("\nOK — the alarm lands, points at the right time, and goes away cleanly.");+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 0de0416..2288028 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -559,6 +559,24 @@ async fn reminder_edit(.await.map_err(|e| e.to_string())?;+ // A due date on its own notifies nobody. Every reminder on a real account that has a+ // time carries an Alarm pointing at an AlarmTrigger, and one written here used to have+ // the date and no alarm — so a phone showed the right time and then said nothing when it+ // came. The alert is part of setting a date, not a separate thing to remember.+ if let Some(due) = edit.due_at {+ let zone = jiff::tz::TimeZone::system();+ quince_icloud::reminders::set_alarm_cloudkit(+ &http,+ &root,+ params.clone(),+ &guid,+ due,+ zone.iana_name().unwrap_or("UTC"),+ )+ .await+ .map_err(|e| e.to_string())?;+ }+let mut library = data.0.lock().await;let since = library.sync_token("reminders").map_err(|e| e.to_string())?;quince_icloud::reminders::sync_cloudkit(&http, &root, params, &mut library, since.as_deref())