Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Reminders write back to Apple

Yashwanth Kamireddi3767de3d0018
diff --git a/crates/quince-core/src/reminders.rs b/crates/quince-core/src/reminders.rs
index 187ccf2..5ef7143 100644
--- a/crates/quince-core/src/reminders.rs
+++ b/crates/quince-core/src/reminders.rs
@@ -27,6 +27,10 @@ pub struct Reminder {
pub completed_at: Option<i64>,
pub priority: i64,
pub etag: Option<String>,
+ /// Apple's original JSON for this reminder, kept verbatim so a write can echo every
+ /// field back rather than only the ones we model.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub raw: Option<String>,
}
impl Reminder {
@@ -87,13 +91,14 @@ impl Library {
{
let mut stmt = tx.prepare(
"INSERT INTO reminders (guid, list_guid, title, notes, due_at, completed_at,
- priority, etag, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
+ priority, etag, raw, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
ON CONFLICT(guid) DO UPDATE SET
list_guid = excluded.list_guid, title = excluded.title,
notes = excluded.notes, due_at = excluded.due_at,
completed_at = excluded.completed_at, priority = excluded.priority,
- etag = excluded.etag, updated_at = excluded.updated_at",
+ etag = excluded.etag, raw = excluded.raw,
+ updated_at = excluded.updated_at",
)?;
let stamp = now();
for r in reminders {
@@ -106,6 +111,7 @@ impl Library {
r.completed_at,
r.priority,
r.etag,
+ r.raw,
stamp
])?;
}
@@ -138,7 +144,7 @@ impl Library {
/// is useless.
pub fn reminders_in(&self, list_guid: &str, include_done: bool) -> Result<Vec<Reminder>> {
let mut stmt = self.conn.prepare(
- "SELECT guid, list_guid, title, notes, due_at, completed_at, priority, etag
+ "SELECT guid, list_guid, title, notes, due_at, completed_at, priority, etag, raw
FROM reminders
WHERE list_guid = ?1 AND (?2 = 1 OR completed_at IS NULL)
ORDER BY completed_at IS NOT NULL,
@@ -156,6 +162,7 @@ impl Library {
completed_at: row.get(5)?,
priority: row.get(6)?,
etag: row.get(7)?,
+ raw: row.get(8)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -187,6 +194,7 @@ mod tests {
completed_at: done,
priority: 0,
etag: None,
+ raw: None,
}
}
@@ -244,6 +252,10 @@ mod tests {
#[test]
fn an_existing_library_migrates_to_the_new_schema() {
let lib = Library::in_memory().unwrap();
- assert_eq!(lib.schema_version().unwrap(), 2, "migration 2 must apply");
+ assert_eq!(
+ lib.schema_version().unwrap() as usize,
+ crate::schema::MIGRATIONS.len(),
+ "every migration must apply"
+ );
}
}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index a43f7f6..703a85a 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -77,4 +77,12 @@ pub const MIGRATIONS: &[&str] = &[
CREATE INDEX reminders_by_list ON reminders (list_guid, completed_at, due_at);
CREATE INDEX reminders_by_due ON reminders (due_at);
"#,
+ // 3 — keep Apple's original payload for each reminder.
+ //
+ // Writes must echo the whole task back. Reconstructing one from parsed columns would
+ // silently drop fields Apple sent but we do not model, which is how a sync corrupts
+ // someone's data. Storing the original makes a write a mutation of what Apple gave us.
+ r#"
+ ALTER TABLE reminders ADD COLUMN raw TEXT;
+ "#,
];
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rs
index 21e4563..af63c8c 100644
--- a/crates/quince-icloud/src/calendar.rs
+++ b/crates/quince-icloud/src/calendar.rs
@@ -65,6 +65,23 @@ pub(crate) fn parse_apple_date(raw: &Value, timezone: Option<&str>) -> Result<i6
Ok(zoned.timestamp().as_second())
}
+/// The inverse of [`parse_apple_date`]: Apple's `[YYYYMMDD, y, m, d, h, min, minsSinceMidnight]`.
+///
+/// Writes must speak the same dialect they read, so this is what a completion timestamp or a
+/// due date looks like going back.
+pub(crate) fn format_apple_date(seconds: i64, timezone: Option<&str>) -> Value {
+ let zone = timezone
+ .and_then(|name| TimeZone::get(name).ok())
+ .unwrap_or(TimeZone::UTC);
+ let zoned = jiff::Timestamp::from_second(seconds)
+ .unwrap_or(jiff::Timestamp::UNIX_EPOCH)
+ .to_zoned(zone);
+ let (y, m, d) = (zoned.year(), zoned.month(), zoned.day());
+ let (h, min) = (zoned.hour(), zoned.minute());
+ let packed = i64::from(y) * 10_000 + i64::from(m) * 100 + i64::from(d);
+ serde_json::json!([packed, y, m, d, h, min, i64::from(h) * 60 + i64::from(min)])
+}
+
fn string(v: &Value, key: &str) -> Option<String> {
v.get(key)
.and_then(Value::as_str)
@@ -285,6 +302,41 @@ mod tests {
}
}
+ /// A date written back must read back as the same instant, or a completion would land on
+ /// the wrong day.
+ #[test]
+ fn dates_survive_a_round_trip() {
+ for zone in [Some("Asia/Kolkata"), Some("America/New_York"), None] {
+ for seconds in [0_i64, 1_757_000_000, 1_788_888_888] {
+ let encoded = format_apple_date(seconds, zone);
+ let decoded = parse_apple_date(&encoded, zone).unwrap();
+ // Apple's format carries no seconds, so equality is to the minute.
+ assert_eq!(
+ decoded,
+ seconds - seconds.rem_euclid(60),
+ "{seconds} in {zone:?} did not survive"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn an_encoded_date_has_apples_shape() {
+ let encoded = format_apple_date(1_757_000_000, Some("UTC"));
+ let parts = encoded.as_array().unwrap();
+ assert_eq!(parts.len(), 7);
+ // First element packs the date as YYYYMMDD.
+ let packed = parts[0].as_i64().unwrap();
+ assert_eq!(packed / 10_000, parts[1].as_i64().unwrap(), "year");
+ assert_eq!((packed / 100) % 100, parts[2].as_i64().unwrap(), "month");
+ assert_eq!(packed % 100, parts[3].as_i64().unwrap(), "day");
+ // Last element is minutes since midnight.
+ assert_eq!(
+ parts[6].as_i64().unwrap(),
+ parts[4].as_i64().unwrap() * 60 + parts[5].as_i64().unwrap()
+ );
+ }
+
#[test]
fn a_snapshot_reads_collections_and_events() {
let body = json!({
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rs
index fab5dd3..34da8fe 100644
--- a/crates/quince-icloud/src/reminders.rs
+++ b/crates/quince-icloud/src/reminders.rs
@@ -48,6 +48,9 @@ fn reminder_from(v: &Value) -> Option<Reminder> {
completed_at: optional_date(v, "completedDate"),
priority: v.get("priority").and_then(Value::as_i64).unwrap_or(0),
etag: string(v, "etag"),
+ // Keep Apple's payload verbatim: a write echoes the whole task back, and
+ // reconstructing one from parsed columns would drop fields we do not model.
+ raw: serde_json::to_string(v).ok(),
})
}
@@ -151,6 +154,71 @@ pub async fn sync(
Ok((snapshot.lists.len(), reminders.len()))
}
+/// Mark a reminder done, or put it back.
+///
+/// Apple wants the whole task echoed back, so this mutates the payload it gave us rather
+/// than building a fresh one — anything Apple sent that we do not model survives untouched.
+pub async fn set_completed(
+ http: &reqwest::Client,
+ root: &str,
+ params: &[(String, String)],
+ reminder: &Reminder,
+ done: bool,
+ timezone: &str,
+) -> Result<()> {
+ let raw = reminder.raw.as_deref().ok_or_else(|| {
+ Error::Protocol(
+ "this reminder was stored before Quince kept Apple's original payload; \
+ refresh once and try again"
+ .into(),
+ )
+ })?;
+ let mut task: Value = serde_json::from_str(raw)
+ .map_err(|e| Error::Protocol(format!("stored reminder is unreadable: {e}")))?;
+
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0));
+
+ task["completedDate"] = if done {
+ crate::calendar::format_apple_date(now, Some(timezone))
+ } else {
+ Value::Null
+ };
+ task["lastModifiedDate"] = crate::calendar::format_apple_date(now, Some(timezone));
+
+ let body = serde_json::json!({
+ "Reminders": task,
+ "ClientState": { "Collections": [] },
+ });
+
+ let mut query: Vec<(String, String)> = params.to_vec();
+ query.push(("clientVersion".into(), "4.0".into()));
+ query.push(("lang".into(), "en-us".into()));
+ query.push(("usertz".into(), timezone.into()));
+ // Apple's web client tunnels PUT through POST.
+ query.push(("methodOverride".into(), "PUT".into()));
+
+ let url = format!(
+ "{}/rd/reminders/{}",
+ root.trim_end_matches('/'),
+ reminder.list_guid
+ );
+ let response = http.post(url).query(&query).json(&body).send().await?;
+ let status = response.status();
+ if status.as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ let text = response.text().await.unwrap_or_default();
+ return Err(Error::Protocol(format!(
+ "couldn't update that reminder ({status}): {}",
+ text.chars().take(160).collect::<String>()
+ )));
+ }
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -208,6 +276,90 @@ mod tests {
assert!(snap.reminders[0].due_at.is_none());
}
+ /// The stored payload must be Apple's, verbatim, or a write would drop fields.
+ #[test]
+ fn apples_payload_is_kept_verbatim() {
+ let body = json!({ "Reminders": [{
+ "guid": "r1", "pGuid": "l1", "title": "Milk",
+ "someFieldWeDoNotModel": { "nested": [1, 2, 3] }
+ }]});
+ let reminder = &parse_snapshot(&body).reminders[0];
+ let raw: Value = serde_json::from_str(reminder.raw.as_ref().unwrap()).unwrap();
+ assert_eq!(raw["someFieldWeDoNotModel"]["nested"][2], 3);
+ }
+
+ #[tokio::test]
+ async fn completing_mutates_the_original_payload() {
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/rd/reminders/l1"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+
+ let body = json!({ "Reminders": [{
+ "guid": "r1", "pGuid": "l1", "title": "Milk", "customField": "keep me"
+ }]});
+ let reminder = parse_snapshot(&body).reminders.remove(0);
+
+ let http = reqwest::Client::new();
+ set_completed(&http, &server.uri(), &[], &reminder, true, "UTC")
+ .await
+ .unwrap();
+
+ let requests = server.received_requests().await.unwrap();
+ let sent: Value = serde_json::from_slice(&requests[0].body).unwrap();
+ assert_eq!(
+ sent["Reminders"]["customField"], "keep me",
+ "unmodelled fields must survive"
+ );
+ assert!(
+ sent["Reminders"]["completedDate"].is_array(),
+ "completion must be a date array"
+ );
+ assert!(requests[0]
+ .url
+ .query()
+ .unwrap()
+ .contains("methodOverride=PUT"));
+ }
+
+ /// Un-ticking must clear the date, not set it to something.
+ #[tokio::test]
+ async fn un_completing_clears_the_date() {
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/rd/reminders/l1"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+
+ let body = json!({ "Completed": [{ "guid": "r1", "pGuid": "l1", "title": "Bread",
+ "completedDate": [20260910, 2026, 9, 10, 9, 0, 540] }]});
+ let reminder = parse_snapshot(&body).reminders.remove(0);
+
+ set_completed(
+ &reqwest::Client::new(),
+ &server.uri(),
+ &[],
+ &reminder,
+ false,
+ "UTC",
+ )
+ .await
+ .unwrap();
+
+ let requests = server.received_requests().await.unwrap();
+ let sent: Value = serde_json::from_slice(&requests[0].body).unwrap();
+ assert!(sent["Reminders"]["completedDate"].is_null());
+ }
+
#[test]
fn entries_without_identity_are_skipped() {
let body = json!({ "Reminders": [
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index c711849..87570ae 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -253,6 +253,48 @@ async fn reminders_in(
.map_err(|e| e.to_string())
}
+/// Tick a reminder off, or put it back. Writes to Apple first, then refreshes locally, so
+/// the interface never shows a state Apple has not accepted.
+#[tauri::command]
+async fn reminder_set_done(
+ guid: String,
+ list_guid: String,
+ done: bool,
+ timezone: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<()> {
+ let (http, root, params) = {
+ let client = auth.client.lock().await;
+ let root = client
+ .session()
+ .service_url("reminders")
+ .ok_or("Apple hasn't offered a reminders service for this account.")?;
+ (client.http().clone(), root, client.service_params())
+ };
+
+ let reminder = {
+ let library = data.0.lock().await;
+ library
+ .reminders_in(&list_guid, true)
+ .map_err(|e| e.to_string())?
+ .into_iter()
+ .find(|r| r.guid == guid)
+ .ok_or("That reminder is no longer in the local library.")?
+ };
+
+ quince_icloud::reminders::set_completed(&http, &root, &params, &reminder, done, &timezone)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ // Re-read from Apple so what we show is what Apple stored, not what we hoped.
+ let mut library = data.0.lock().await;
+ quince_icloud::reminders::sync(&http, &root, params, &mut library, &timezone)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(())
+}
+
#[tauri::command]
async fn reminders_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
let library = data.0.lock().await;
@@ -300,6 +342,7 @@ fn main() {
reminder_lists,
reminders_in,
reminders_last_synced,
+ reminder_set_done,
])
.run(tauri::generate_context!())
.expect("Quince failed to start");