diff --git a/Cargo.lock b/Cargo.lock index 4da5ab4..750f7ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -17,12 +26,24 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bitflags" version = "2.13.2" @@ -48,6 +69,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cc" version = "1.9.0" @@ -71,17 +98,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", "serde", + "wasm-bindgen", "windows-link", ] +[[package]] +name = "chrono-tz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" +dependencies = [ + "chrono", + "phf", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "constant_time_eq" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -97,6 +156,17 @@ dependencies = [ "libc", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "errno" version = "0.3.14" @@ -104,7 +174,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -137,6 +207,24 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -161,6 +249,17 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -190,6 +289,103 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -214,12 +410,171 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "js-sys" version = "0.3.106" @@ -254,6 +609,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "log" version = "0.4.34" @@ -266,6 +627,17 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -281,6 +653,36 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -293,6 +695,15 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -302,6 +713,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -317,6 +737,96 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rrule" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74" +dependencies = [ + "chrono", + "chrono-tz", + "log", + "regex", + "thiserror", +] + [[package]] name = "rusqlite" version = "0.37.0" @@ -331,6 +841,15 @@ dependencies = [ "smallvec", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.5" @@ -341,7 +860,80 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -350,6 +942,53 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -405,6 +1044,28 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" @@ -417,6 +1078,28 @@ version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -439,6 +1122,27 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synapse-caldav" +version = "0.1.0" +dependencies = [ + "chrono", + "chrono-tz", + "quick-xml", + "reqwest", + "rrule", + "rusqlite", + "rustls", + "serde", + "serde_json", + "synapse-core", + "tempfile", + "thiserror", + "tokio", + "uuid", + "webpki-roots", +] + [[package]] name = "synapse-core" version = "0.1.0" @@ -453,6 +1157,26 @@ dependencies = [ "uuid", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -460,10 +1184,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -486,19 +1210,159 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "uuid" version = "1.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" dependencies = [ - "getrandom", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -511,6 +1375,31 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -524,6 +1413,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -556,6 +1456,43 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -615,6 +1552,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -624,6 +1570,159 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/crates/synapse-caldav/Cargo.toml b/crates/synapse-caldav/Cargo.toml new file mode 100644 index 0000000..5180a8c --- /dev/null +++ b/crates/synapse-caldav/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "synapse-caldav" +version = "0.1.0" +edition.workspace = true +license.workspace = true +description = "CalDAV events and VTODO tasks, two-way with Synapse blocks and journals" + +[dependencies] +synapse-core.workspace = true +chrono.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +uuid.workspace = true +rusqlite.workspace = true +quick-xml = "0.42.0" +rrule = "0.14.0" +chrono-tz = "0.10.4" +reqwest = { version = "0.13.5", default-features = false, features = ["rustls-no-provider"] } +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } +webpki-roots = "1.0.10" + +[dev-dependencies] +tempfile = "3.27.0" +tokio = { version = "1.54.0", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time"] } diff --git a/crates/synapse-caldav/src/calendar.rs b/crates/synapse-caldav/src/calendar.rs new file mode 100644 index 0000000..25bf685 --- /dev/null +++ b/crates/synapse-caldav/src/calendar.rs @@ -0,0 +1,585 @@ +//! Typed views over iCalendar components: date-times, events, tasks and RRULE expansion. + +use crate::ical::{Component, Prop, escape}; +use crate::{Error, Result, ical}; +use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc}; +use chrono_tz::Tz; + +/// An iCalendar DATE / DATE-TIME value with its zone semantics preserved. +#[derive(Debug, Clone, PartialEq)] +pub enum DtValue { + Date(NaiveDate), + /// No zone: wall-clock time in the viewer's zone. + Floating(NaiveDateTime), + Utc(DateTime), + Zoned(Tz, NaiveDateTime), +} + +impl DtValue { + pub fn parse(p: &Prop) -> Option { + let v = p.value.trim(); + if p.param("VALUE") == Some("DATE") || (v.len() == 8 && !v.contains('T')) { + return NaiveDate::parse_from_str(v, "%Y%m%d") + .ok() + .map(DtValue::Date); + } + if let Some(z) = v.strip_suffix('Z') { + let n = NaiveDateTime::parse_from_str(z, "%Y%m%dT%H%M%S").ok()?; + return Some(DtValue::Utc(Utc.from_utc_datetime(&n))); + } + let n = NaiveDateTime::parse_from_str(v, "%Y%m%dT%H%M%S").ok()?; + match p.param("TZID").and_then(|t| t.parse::().ok()) { + Some(tz) => Some(DtValue::Zoned(tz, n)), + None => Some(DtValue::Floating(n)), + } + } + + pub fn to_prop(&self, name: &str) -> Prop { + match self { + DtValue::Date(d) => { + Prop::new(name, d.format("%Y%m%d").to_string()).with_param("VALUE", "DATE") + } + DtValue::Floating(n) => Prop::new(name, n.format("%Y%m%dT%H%M%S").to_string()), + DtValue::Utc(u) => Prop::new(name, u.format("%Y%m%dT%H%M%SZ").to_string()), + DtValue::Zoned(tz, n) => { + Prop::new(name, n.format("%Y%m%dT%H%M%S").to_string()).with_param("TZID", tz.name()) + } + } + } + + pub fn is_date(&self) -> bool { + matches!(self, DtValue::Date(_)) + } + + /// Wall-clock time in the viewer's zone `view` (all-day values become midnight). + pub fn local(&self, view: Tz) -> NaiveDateTime { + match self { + DtValue::Date(d) => d.and_time(NaiveTime::MIN), + DtValue::Floating(n) => *n, + DtValue::Utc(u) => u.with_timezone(&view).naive_local(), + DtValue::Zoned(tz, n) => match tz.from_local_datetime(n).earliest() { + Some(t) => t.with_timezone(&view).naive_local(), + None => *n, // non-existent local time (DST gap) + }, + } + } + + pub fn local_date(&self, view: Tz) -> NaiveDate { + match self { + DtValue::Date(d) => *d, + _ => self.local(view).date(), + } + } +} + +fn parse_duration(s: &str) -> Option { + let s = s.trim(); + let (neg, s) = match s.strip_prefix('-') { + Some(r) => (true, r), + None => (false, s.strip_prefix('+').unwrap_or(s)), + }; + let s = s.strip_prefix('P')?; + let (mut secs, mut num) = (0i64, String::new()); + let mut in_time = false; + for c in s.chars() { + match c { + 'T' => in_time = true, + '0'..='9' => num.push(c), + _ => { + let n: i64 = num.parse().ok()?; + num.clear(); + secs += n * match (c, in_time) { + ('W', _) => 604_800, + ('D', _) => 86_400, + ('H', true) => 3600, + ('M', true) => 60, + ('S', true) => 1, + _ => return None, + }; + } + } + } + Some(Duration::seconds(if neg { -secs } else { secs })) +} + +fn add(dt: &DtValue, d: Duration) -> DtValue { + match dt { + DtValue::Date(x) => DtValue::Date(*x + d), + DtValue::Floating(x) => DtValue::Floating(*x + d), + DtValue::Utc(x) => DtValue::Utc(*x + d), + DtValue::Zoned(tz, x) => DtValue::Zoned(*tz, *x + d), + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Event { + pub uid: String, + pub summary: String, + pub description: Option, + pub location: Option, + pub start: DtValue, + pub end: Option, + pub status: Option, + pub recurrence_id: Option, + pub has_rrule: bool, +} + +impl Event { + pub fn from_component(c: &Component) -> Option { + let start = DtValue::parse(c.prop("DTSTART")?)?; + let end = match c.prop("DTEND").and_then(DtValue::parse) { + Some(e) => Some(e), + None => c + .prop("DURATION") + .and_then(|p| parse_duration(&p.value)) + .map(|d| add(&start, d)), + }; + Some(Event { + uid: c.text("UID")?, + summary: c.text("SUMMARY").unwrap_or_default(), + description: c.text("DESCRIPTION"), + location: c.text("LOCATION"), + start, + end, + status: c.text("STATUS"), + recurrence_id: c.prop("RECURRENCE-ID").and_then(DtValue::parse), + has_rrule: c.prop("RRULE").is_some(), + }) + } + + /// Length used for occurrences: DTEND-DTSTART, one day for dates, zero for instants. + pub fn duration(&self, view: Tz) -> Duration { + match &self.end { + Some(e) => e.local(view) - self.start.local(view), + None if self.start.is_date() => Duration::days(1), + None => Duration::zero(), + } + } +} + +/// One concrete instance of an event inside a requested window. +#[derive(Debug, Clone, PartialEq)] +pub struct Occurrence { + pub uid: String, + pub calendar: String, + pub href: String, + pub summary: String, + pub description: Option, + pub location: Option, + /// Wall-clock in the viewer's zone. + pub start: NaiveDateTime, + pub end: NaiveDateTime, + pub all_day: bool, + pub recurring: bool, +} + +/// Parses the VCALENDAR in `ics` and returns its top-level component list's inner components. +pub fn parse_calendar(ics: &str) -> Result { + ical::parse(ics)? + .into_iter() + .find(|c| c.name == "VCALENDAR") + .ok_or_else(|| Error::Ical("no VCALENDAR".into())) +} + +fn rrule_text(c: &Component, start: &DtValue) -> Option { + let rule = c.prop("RRULE")?; + // The recurrence engine wants DTSTART in text form; dates and floating times are treated + // as UTC wall-clock (windows are padded and re-filtered in the viewer's zone afterwards). + let dtstart = match start { + DtValue::Date(d) => format!("DTSTART:{}T000000Z", d.format("%Y%m%d")), + DtValue::Floating(n) => format!("DTSTART:{}Z", n.format("%Y%m%dT%H%M%S")), + DtValue::Utc(u) => format!("DTSTART:{}", u.format("%Y%m%dT%H%M%SZ")), + DtValue::Zoned(tz, n) => { + format!("DTSTART;TZID={}:{}", tz.name(), n.format("%Y%m%dT%H%M%S")) + } + }; + // For all-day events UNTIL is a DATE; the engine needs a date-time. + let rule_text: Vec = rule + .value + .split(';') + .map(|kv| match kv.strip_prefix("UNTIL=") { + Some(u) if start.is_date() && u.len() == 8 => format!("UNTIL={u}T235959Z"), + _ => kv.to_string(), + }) + .collect(); + let mut s = format!("{dtstart}\nRRULE:{}", rule_text.join(";")); + for ex in c.props_named("EXDATE") { + for v in ex.value.split(',') { + let dt = DtValue::parse(&Prop { + value: v.to_string(), + ..ex.clone() + })?; + let line = match dt { + DtValue::Date(d) => format!("EXDATE:{}T000000Z", d.format("%Y%m%d")), + DtValue::Floating(n) => format!("EXDATE:{}Z", n.format("%Y%m%dT%H%M%S")), + DtValue::Utc(u) => format!("EXDATE:{}", u.format("%Y%m%dT%H%M%SZ")), + DtValue::Zoned(tz, n) => { + format!("EXDATE;TZID={}:{}", tz.name(), n.format("%Y%m%dT%H%M%S")) + } + }; + s.push('\n'); + s.push_str(&line); + } + } + Some(s) +} + +/// Start values of a (possibly recurring) component that fall in `[from, to)` (viewer-zone +/// wall-clock). Non-recurring components yield their own start. +pub fn expand_starts( + c: &Component, + start: &DtValue, + view: Tz, + from: NaiveDateTime, + to: NaiveDateTime, +) -> Vec { + let Some(text) = rrule_text(c, start) else { + return vec![start.clone()]; + }; + let Ok(set) = text.parse::() else { + return vec![start.clone()]; + }; + let pad = Duration::days(2); + let utc = |n: NaiveDateTime| rrule::Tz::UTC.from_utc_datetime(&n); + let res = set.after(utc(from - pad)).before(utc(to + pad)).all(2000); + res.dates + .into_iter() + .map(|d| { + // Rebuild a DtValue of the same flavour as the master start. + match start { + DtValue::Date(_) => DtValue::Date(d.date_naive()), + DtValue::Floating(_) => DtValue::Floating(d.naive_utc()), + DtValue::Utc(_) => DtValue::Utc(d.with_timezone(&Utc)), + DtValue::Zoned(tz, _) => DtValue::Zoned(*tz, d.with_timezone(tz).naive_local()), + } + }) + .filter(|v| { + let s = v.local(view); + s < to && s >= from - Duration::days(366) + }) + .collect() +} + +/// Occurrences of all VEVENTs in one calendar object overlapping `[from, to)`. +pub fn event_occurrences( + cal: &Component, + calendar: &str, + href: &str, + view: Tz, + from: NaiveDateTime, + to: NaiveDateTime, +) -> Vec { + let comps: Vec<&Component> = cal.children_named("VEVENT").collect(); + let events: Vec<(&Component, Event)> = comps + .iter() + .filter_map(|c| Event::from_component(c).map(|e| (*c, e))) + .collect(); + // Overrides replace the generated instance with the same RECURRENCE-ID. + let overridden: Vec<(&str, NaiveDateTime)> = events + .iter() + .filter_map(|(_, e)| { + e.recurrence_id + .as_ref() + .map(|r| (e.uid.as_str(), r.local(view))) + }) + .collect(); + let mut out = Vec::new(); + for (c, e) in &events { + if e.status.as_deref() == Some("CANCELLED") { + continue; + } + let dur = e.duration(view); + let all_day = e.start.is_date(); + let starts = if e.recurrence_id.is_some() { + vec![e.start.clone()] + } else { + expand_starts(c, &e.start, view, from, to) + }; + for s in starts { + let sl = s.local(view); + if e.recurrence_id.is_none() && overridden.contains(&(e.uid.as_str(), sl)) { + continue; + } + let el = sl + dur; + // Overlap test; zero-length events count when their start is inside. + let overlaps = if dur.is_zero() { + sl >= from && sl < to + } else { + sl < to && el > from + }; + if overlaps { + out.push(Occurrence { + uid: e.uid.clone(), + calendar: calendar.to_string(), + href: href.to_string(), + summary: e.summary.clone(), + description: e.description.clone(), + location: e.location.clone(), + start: sl, + end: el, + all_day, + recurring: e.has_rrule || e.recurrence_id.is_some(), + }); + } + } + } + out.sort_by_key(|o| (o.start, o.summary.clone())); + out +} + +// ------------------------------------------------------------------------------- tasks + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TodoStatus { + NeedsAction, + InProcess, + Completed, + Cancelled, +} + +impl TodoStatus { + pub fn as_str(self) -> &'static str { + match self { + TodoStatus::NeedsAction => "NEEDS-ACTION", + TodoStatus::InProcess => "IN-PROCESS", + TodoStatus::Completed => "COMPLETED", + TodoStatus::Cancelled => "CANCELLED", + } + } + + pub fn parse(s: &str) -> TodoStatus { + match s.to_ascii_uppercase().as_str() { + "IN-PROCESS" => TodoStatus::InProcess, + "COMPLETED" => TodoStatus::Completed, + "CANCELLED" => TodoStatus::Cancelled, + _ => TodoStatus::NeedsAction, + } + } +} + +/// The task fields Synapse understands; everything else stays in the raw component. +#[derive(Debug, Clone, PartialEq)] +pub struct Todo { + pub uid: String, + pub summary: String, + pub description: Option, + pub status: TodoStatus, + pub percent: Option, + /// iCalendar PRIORITY: 0 = none, 1 = highest … 9 = lowest. + pub priority: u8, + pub start: Option, + pub due: Option, + pub completed: Option>, + pub last_modified: Option>, + pub has_rrule: bool, +} + +fn utc_prop(c: &Component, name: &str) -> Option> { + match DtValue::parse(c.prop(name)?)? { + DtValue::Utc(u) => Some(u), + DtValue::Floating(n) | DtValue::Zoned(_, n) => Some(Utc.from_utc_datetime(&n)), + DtValue::Date(d) => Some(Utc.from_utc_datetime(&d.and_time(NaiveTime::MIN))), + } +} + +impl Todo { + pub fn from_component(c: &Component) -> Option { + Some(Todo { + uid: c.text("UID")?, + summary: c.text("SUMMARY").unwrap_or_default(), + description: c.text("DESCRIPTION").filter(|s| !s.trim().is_empty()), + status: c + .text("STATUS") + .map(|s| TodoStatus::parse(&s)) + .unwrap_or(TodoStatus::NeedsAction), + percent: c + .text("PERCENT-COMPLETE") + .and_then(|s| s.trim().parse().ok()), + priority: c + .text("PRIORITY") + .and_then(|s| s.trim().parse().ok()) + .unwrap_or(0), + start: c.prop("DTSTART").and_then(DtValue::parse), + due: c.prop("DUE").and_then(DtValue::parse), + completed: utc_prop(c, "COMPLETED"), + last_modified: utc_prop(c, "LAST-MODIFIED").or_else(|| utc_prop(c, "DTSTAMP")), + has_rrule: c.prop("RRULE").is_some(), + }) + } + + /// Writes this task's fields onto `c`, keeping unknown properties, and stamps + /// LAST-MODIFIED/DTSTAMP with `now`. + pub fn apply_to(&self, c: &mut Component, now: DateTime) { + c.set(Prop::new("UID", &self.uid)); + c.set(Prop::new("SUMMARY", escape(&self.summary))); + match &self.description { + Some(d) => c.set(Prop::new("DESCRIPTION", escape(d))), + None => c.remove("DESCRIPTION"), + } + c.set(Prop::new("STATUS", self.status.as_str())); + match (self.status, self.percent) { + (TodoStatus::Completed, _) => c.set(Prop::new("PERCENT-COMPLETE", "100")), + (_, Some(p)) if p < 100 => c.set(Prop::new("PERCENT-COMPLETE", p.to_string())), + _ => c.remove("PERCENT-COMPLETE"), + } + if self.priority == 0 { + c.remove("PRIORITY"); + } else { + c.set(Prop::new("PRIORITY", self.priority.to_string())); + } + match &self.start { + Some(s) => c.set(s.to_prop("DTSTART")), + None => c.remove("DTSTART"), + } + match &self.due { + Some(d) => c.set(d.to_prop("DUE")), + None => c.remove("DUE"), + } + match self.completed { + Some(t) if self.status == TodoStatus::Completed => { + c.set(DtValue::Utc(t).to_prop("COMPLETED")) + } + _ => c.remove("COMPLETED"), + } + let stamp = DtValue::Utc(now); + c.set(stamp.to_prop("LAST-MODIFIED")); + c.set(stamp.to_prop("DTSTAMP")); + } + + /// A fresh VCALENDAR wrapping one VTODO. + pub fn to_calendar(&self, now: DateTime) -> Component { + let mut cal = Component::new("VCALENDAR"); + cal.props.push(Prop::new("VERSION", "2.0")); + cal.props + .push(Prop::new("PRODID", "-//Synapse//CalDAV//EN")); + let mut t = Component::new("VTODO"); + self.apply_to(&mut t, now); + cal.children.push(t); + cal + } +} + +/// First VTODO of a calendar object that is not a recurrence override. +pub fn master_todo(cal: &Component) -> Option<&Component> { + cal.children_named("VTODO") + .find(|c| c.prop("RECURRENCE-ID").is_none()) + .or_else(|| cal.children_named("VTODO").next()) +} + +pub fn master_todo_mut(cal: &mut Component) -> Option<&mut Component> { + let idx = cal + .children + .iter() + .position(|c| c.name == "VTODO" && c.prop("RECURRENCE-ID").is_none()) + .or_else(|| cal.children.iter().position(|c| c.name == "VTODO"))?; + Some(&mut cal.children[idx]) +} + +/// Due/start instances of a recurring task inside `[from, to)`. +pub fn todo_occurrences( + c: &Component, + view: Tz, + from: NaiveDateTime, + to: NaiveDateTime, +) -> Vec { + let Some(anchor) = c + .prop("DTSTART") + .or_else(|| c.prop("DUE")) + .and_then(DtValue::parse) + else { + return Vec::new(); + }; + expand_starts(c, &anchor, view, from, to) +} + +pub fn calendar_kinds(cal: &Component) -> (bool, bool) { + ( + cal.children.iter().any(|c| c.name == "VEVENT"), + cal.children.iter().any(|c| c.name == "VTODO"), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() + } + + #[test] + fn weekly_zoned_with_exdate_and_override() { + let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:s1\r\nSUMMARY:Standup\r\nDTSTART;TZID=Europe/Madrid:20261007T100000\r\nDTEND;TZID=Europe/Madrid:20261007T103000\r\nRRULE:FREQ=WEEKLY;BYDAY=WE\r\nEXDATE;TZID=Europe/Madrid:20261014T100000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:s1\r\nSUMMARY:Standup (moved)\r\nRECURRENCE-ID;TZID=Europe/Madrid:20261028T100000\r\nDTSTART;TZID=Europe/Madrid:20261028T150000\r\nDTEND;TZID=Europe/Madrid:20261028T153000\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + let cal = parse_calendar(ics).unwrap(); + let tz = chrono_tz::Europe::Madrid; + let win = |a: NaiveDate, b: NaiveDate| { + event_occurrences( + &cal, + "c", + "h", + tz, + a.and_time(NaiveTime::MIN), + b.and_time(NaiveTime::MIN), + ) + }; + assert_eq!(win(d(2026, 10, 14), d(2026, 10, 15)).len(), 0, "exdate"); + let o = win(d(2026, 10, 21), d(2026, 10, 22)); + assert_eq!(o.len(), 1); + assert_eq!( + o[0].start.time(), + NaiveTime::from_hms_opt(10, 0, 0).unwrap() + ); + assert!(o[0].recurring); + // Override moved the 28th to 15:00 and replaced the generated instance. + let o = win(d(2026, 10, 28), d(2026, 10, 29)); + assert_eq!(o.len(), 1); + assert_eq!(o[0].summary, "Standup (moved)"); + // Same wall-clock across the DST change (Oct 25 2026): Nov 4 is still 10:00. + let o = win(d(2026, 11, 4), d(2026, 11, 5)); + assert_eq!( + o[0].start.time(), + NaiveTime::from_hms_opt(10, 0, 0).unwrap() + ); + } + + #[test] + fn utc_event_shown_in_viewer_zone_and_all_day_daily_count() { + let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:u\r\nSUMMARY:Call\r\nDTSTART:20261021T230000Z\r\nDURATION:PT1H\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:a\r\nSUMMARY:Holiday\r\nDTSTART;VALUE=DATE:20261021\r\nRRULE:FREQ=DAILY;COUNT=3;UNTIL=20261110\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + let cal = parse_calendar(ics).unwrap(); + let tz = chrono_tz::Europe::Madrid; + let day = |n: NaiveDate| { + event_occurrences( + &cal, + "c", + "h", + tz, + n.and_time(NaiveTime::MIN), + (n + Duration::days(1)).and_time(NaiveTime::MIN), + ) + }; + // 23:00Z is 01:00 on the 22nd in Madrid (CEST, UTC+2). + assert!(day(d(2026, 10, 21)).iter().all(|o| o.summary != "Call")); + let o = day(d(2026, 10, 22)); + assert!( + o.iter() + .any(|o| o.summary == "Call" && o.end - o.start == Duration::hours(1)) + ); + assert!(o.iter().any(|o| o.summary == "Holiday" && o.all_day)); + assert!(day(d(2026, 10, 24)).is_empty()); + } + + #[test] + fn todo_roundtrip_preserves_unknown() { + let ics = "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nUID:t\r\nSUMMARY:Pay\r\nX-APPLE-SORT-ORDER:5\r\nPRIORITY:1\r\nDUE;VALUE=DATE:20261025\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"; + let mut cal = parse_calendar(ics).unwrap(); + let mut t = Todo::from_component(master_todo(&cal).unwrap()).unwrap(); + assert_eq!(t.priority, 1); + t.status = TodoStatus::Completed; + t.completed = Some(Utc.with_ymd_and_hms(2026, 10, 21, 8, 0, 0).unwrap()); + t.apply_to(master_todo_mut(&mut cal).unwrap(), Utc::now()); + let out = ical::serialize(&cal); + assert!(out.contains("X-APPLE-SORT-ORDER:5")); + assert!(out.contains("STATUS:COMPLETED") && out.contains("PERCENT-COMPLETE:100")); + assert!(out.contains("COMPLETED:20261021T080000Z")); + } +} diff --git a/crates/synapse-caldav/src/dav.rs b/crates/synapse-caldav/src/dav.rs new file mode 100644 index 0000000..e9b10ca --- /dev/null +++ b/crates/synapse-caldav/src/dav.rs @@ -0,0 +1,410 @@ +//! Async CalDAV client (RFC 4791 / RFC 6578). Credentials are supplied by the caller and held +//! only in memory. + +use crate::xml::{Multistatus, esc, parse_multistatus}; +use crate::{Error, Result}; +use reqwest::header::{ + CONTENT_TYPE, ETAG, HeaderMap, HeaderValue, IF_MATCH, IF_NONE_MATCH, LOCATION, +}; +use reqwest::{Method, StatusCode, Url}; +use std::sync::Arc; + +#[derive(Clone)] +pub struct Credentials { + pub username: String, + /// Account password or (preferably) an app password. + pub password: String, +} + +impl std::fmt::Debug for Credentials { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Credentials") + .field("username", &self.username) + .finish_non_exhaustive() + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CalendarInfo { + /// Server-relative path, as returned by the server (identity of the collection). + pub href: String, + pub name: String, + pub supports_events: bool, + pub supports_tasks: bool, + pub ctag: Option, + pub sync_token: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct RemoteObject { + pub href: String, + pub etag: String, + pub ics: String, +} + +#[derive(Debug, Default)] +pub struct SyncChanges { + /// (href, etag) of created/modified members. + pub changed: Vec<(String, String)>, + pub deleted: Vec, + pub new_token: Option, +} + +pub struct DavClient { + http: reqwest::Client, + base: Url, + creds: Credentials, +} + +const NS: &str = r#"xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:cs="http://calendarserver.org/ns/""#; + +fn tls_client() -> Result { + let mut roots = rustls::RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + let cfg = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .map_err(|e| Error::Tls(e.to_string()))? + .with_root_certificates(roots) + .with_no_client_auth(); + Ok(reqwest::Client::builder() + .use_preconfigured_tls(cfg) + .redirect(reqwest::redirect::Policy::none()) + .user_agent("synapse-caldav") + .build()?) +} + +fn strip_quotes_etag(h: &HeaderMap) -> Option { + h.get(ETAG) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) +} + +impl DavClient { + /// `base` is the server root (`https://cloud.example.com`) or any DAV URL below it. + pub fn new(base: &str, creds: Credentials) -> Result { + Ok(DavClient { + http: tls_client()?, + base: Url::parse(base).map_err(|e| Error::Discovery(format!("bad url: {e}")))?, + creds, + }) + } + + fn url(&self, href: &str) -> Result { + self.base + .join(href) + .map_err(|e| Error::Other(format!("bad href {href}: {e}"))) + } + + /// Sends a request, following redirects manually so the method and body are preserved + /// (credentials only ever go to the original host). + async fn send( + &self, + method: &str, + url: Url, + headers: &[(&'static str, String)], + body: Option, + ) -> Result<(StatusCode, HeaderMap, String)> { + let m = Method::from_bytes(method.as_bytes()).map_err(|e| Error::Other(e.to_string()))?; + let mut url = url; + for _ in 0..6 { + let mut rb = self.http.request(m.clone(), url.clone()); + if url.host_str() == self.base.host_str() + && url.port_or_known_default() == self.base.port_or_known_default() + { + rb = rb.basic_auth(&self.creds.username, Some(&self.creds.password)); + } + for (k, v) in headers { + rb = rb.header( + *k, + HeaderValue::from_str(v).map_err(|e| Error::Other(e.to_string()))?, + ); + } + if let Some(b) = &body { + rb = rb.body(b.clone()); + } + let resp = rb.send().await?; + let status = resp.status(); + if status.is_redirection() + && let Some(loc) = resp.headers().get(LOCATION).and_then(|v| v.to_str().ok()) + { + url = url.join(loc).map_err(|e| Error::Other(e.to_string()))?; + continue; + } + let h = resp.headers().clone(); + let text = resp.text().await?; + return Ok((status, h, text)); + } + Err(Error::Other("too many redirects".into())) + } + + async fn xml( + &self, + method: &str, + href: &str, + depth: Option<&str>, + body: String, + ) -> Result<(StatusCode, Multistatus)> { + let mut hs = vec![( + CONTENT_TYPE.as_str(), + "application/xml; charset=utf-8".to_string(), + )]; + if let Some(d) = depth { + hs.push(("depth", d.to_string())); + } + let url = self.url(href)?; + let (st, _, text) = self.send(method, url, &hs, Some(body)).await?; + if st.as_u16() == 207 { + Ok((st, parse_multistatus(&text)?)) + } else { + Ok((st, Multistatus::default())) + } + } + + fn check(st: StatusCode, what: &str) -> Result<()> { + if st.as_u16() == 207 || st.is_success() { + Ok(()) + } else { + Err(Error::Status { + status: st.as_u16(), + what: what.to_string(), + }) + } + } + + // ------------------------------------------------------------------ discovery + + /// Resolves the calendar-home-set path: `.well-known/caldav`, current-user-principal, + /// calendar-home-set. + pub async fn discover(&self) -> Result { + let principal_body = format!( + r#""# + ); + let mut candidates = vec!["/.well-known/caldav".to_string()]; + let base_path = self.base.path().to_string(); + if base_path != "/" && !base_path.is_empty() { + candidates.push(base_path); + } + candidates.push("/".to_string()); + let mut principal = None; + let mut last = String::from("no candidate answered"); + for c in &candidates { + let (st, ms) = self + .xml("PROPFIND", c, Some("0"), principal_body.clone()) + .await?; + if st.as_u16() != 207 { + last = format!("{c}: HTTP {st}"); + continue; + } + if let Some(h) = ms + .responses + .iter() + .find_map(|r| r.text(&["current-user-principal", "href"])) + { + principal = Some(h.to_string()); + break; + } + last = format!("{c}: no current-user-principal"); + } + let principal = principal.ok_or(Error::Discovery(last))?; + let home_body = format!( + r#""# + ); + let (st, ms) = self + .xml("PROPFIND", &principal, Some("0"), home_body) + .await?; + Self::check(st, "calendar-home-set")?; + ms.responses + .iter() + .find_map(|r| r.text(&["calendar-home-set", "href"])) + .map(str::to_string) + .ok_or_else(|| Error::Discovery("no calendar-home-set".into())) + } + + /// Calendar collections below `home` that hold events and/or tasks. + pub async fn list_calendars(&self, home: &str) -> Result> { + let body = format!( + r#""# + ); + let (st, ms) = self.xml("PROPFIND", home, Some("1"), body).await?; + Self::check(st, "list calendars")?; + let mut out = Vec::new(); + for r in ms.responses { + if !r.has(&["resourcetype", "calendar"]) { + continue; + } + let (ev, td) = ( + r.has(&["supported-calendar-component-set", "comp:VEVENT"]), + r.has(&["supported-calendar-component-set", "comp:VTODO"]), + ); + // Servers omitting the set support everything. + let none = !r.has(&["supported-calendar-component-set"]); + let name = r + .text(&["displayname"]) + .map(str::to_string) + .unwrap_or_else(|| { + r.href + .trim_end_matches('/') + .rsplit('/') + .next() + .unwrap_or("") + .to_string() + }); + out.push(CalendarInfo { + name, + supports_events: ev || none, + supports_tasks: td || none, + ctag: r.text(&["getctag"]).map(str::to_string), + sync_token: r.text(&["sync-token"]).map(str::to_string), + href: r.href, + }); + } + Ok(out) + } + + // ----------------------------------------------------------------------- sync + + /// RFC 6578 incremental sync. Returns `Ok(None)` when the server does not support it or + /// rejected the token; callers then fall back to [`DavClient::list_etags`]. + pub async fn sync_collection( + &self, + cal: &str, + token: Option<&str>, + ) -> Result> { + let body = format!( + r#"{}1"#, + esc(token.unwrap_or("")) + ); + let (st, ms) = self.xml("REPORT", cal, None, body).await?; + if matches!(st.as_u16(), 403 | 405 | 409 | 410 | 412 | 415 | 501) { + return Ok(None); + } + Self::check(st, "sync-collection")?; + let Some(new_token) = ms.sync_token else { + return Ok(None); + }; + let mut ch = SyncChanges { + new_token: Some(new_token), + ..Default::default() + }; + for r in ms.responses { + if r.is_removed() { + ch.deleted.push(r.href); + } else if let Some(e) = r.text(&["getetag"]) { + ch.changed.push((r.href.clone(), e.to_string())); + } + } + Ok(Some(ch)) + } + + /// All members of a collection with their etags (fallback when no sync-collection). + pub async fn list_etags(&self, cal: &str) -> Result> { + let body = format!( + r#""# + ); + let (st, ms) = self.xml("PROPFIND", cal, Some("1"), body).await?; + Self::check(st, "list etags")?; + let me = cal.trim_end_matches('/'); + Ok(ms + .responses + .into_iter() + .filter(|r| r.href.trim_end_matches('/') != me) + .filter_map(|r| { + r.text(&["getetag"]) + .map(|e| (r.href.clone(), e.to_string())) + }) + .collect()) + } + + /// Current ctag of a collection. + pub async fn ctag(&self, cal: &str) -> Result> { + let body = format!( + r#""# + ); + let (st, ms) = self.xml("PROPFIND", cal, Some("0"), body).await?; + Self::check(st, "ctag")?; + Ok(ms + .responses + .iter() + .find_map(|r| r.text(&["getctag"]).map(str::to_string))) + } + + pub async fn multiget(&self, cal: &str, hrefs: &[String]) -> Result> { + let mut out = Vec::new(); + for chunk in hrefs.chunks(50) { + let items: String = chunk + .iter() + .map(|h| format!("{}", esc(h))) + .collect(); + let body = format!( + r#"{items}"# + ); + let (st, ms) = self.xml("REPORT", cal, Some("1"), body).await?; + Self::check(st, "calendar-multiget")?; + for r in ms.responses { + if let (Some(e), Some(d)) = (r.text(&["getetag"]), r.text(&["calendar-data"])) { + out.push(RemoteObject { + href: r.href.clone(), + etag: e.to_string(), + ics: d.to_string(), + }); + } + } + } + Ok(out) + } + + // ------------------------------------------------------------------ resources + + pub async fn get(&self, href: &str) -> Result { + let (st, h, text) = self.send("GET", self.url(href)?, &[], None).await?; + Self::check(st, &format!("GET {href}"))?; + Ok(RemoteObject { + href: href.to_string(), + etag: strip_quotes_etag(&h).unwrap_or_default(), + ics: text, + }) + } + + /// Creates (`if_match = None`, only if absent) or replaces (`Some(etag)`) an object. + /// Returns the new etag. A 412 becomes [`Error::PreconditionFailed`]. + pub async fn put(&self, href: &str, ics: &str, if_match: Option<&str>) -> Result { + let hs = vec![ + ( + CONTENT_TYPE.as_str(), + "text/calendar; charset=utf-8".to_string(), + ), + match if_match { + Some(e) => (IF_MATCH.as_str(), e.to_string()), + None => (IF_NONE_MATCH.as_str(), "*".to_string()), + }, + ]; + let (st, h, _) = self + .send("PUT", self.url(href)?, &hs, Some(ics.to_string())) + .await?; + if st == StatusCode::PRECONDITION_FAILED { + return Err(Error::PreconditionFailed(href.to_string())); + } + Self::check(st, &format!("PUT {href}"))?; + match strip_quotes_etag(&h) { + Some(e) => Ok(e), + // Some servers rewrite the object on PUT and omit the etag. + None => Ok(self.get(href).await?.etag), + } + } + + pub async fn delete(&self, href: &str, if_match: Option<&str>) -> Result<()> { + let hs: Vec<(&'static str, String)> = if_match + .map(|e| vec![(IF_MATCH.as_str(), e.to_string())]) + .unwrap_or_default(); + let (st, _, _) = self.send("DELETE", self.url(href)?, &hs, None).await?; + if st == StatusCode::PRECONDITION_FAILED { + return Err(Error::PreconditionFailed(href.to_string())); + } + if st == StatusCode::NOT_FOUND { + return Ok(()); + } + Self::check(st, &format!("DELETE {href}")) + } +} diff --git a/crates/synapse-caldav/src/error.rs b/crates/synapse-caldav/src/error.rs new file mode 100644 index 0000000..ae7d4f4 --- /dev/null +++ b/crates/synapse-caldav/src/error.rs @@ -0,0 +1,27 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("core: {0}")] + Core(#[from] synapse_core::Error), + #[error("sqlite: {0}")] + Sqlite(#[from] rusqlite::Error), + #[error("http: {0}")] + Http(#[from] reqwest::Error), + #[error("server answered {status} for {what}")] + Status { status: u16, what: String }, + #[error("etag mismatch for {0}")] + PreconditionFailed(String), + #[error("xml: {0}")] + Xml(String), + #[error("icalendar: {0}")] + Ical(String), + #[error("discovery failed: {0}")] + Discovery(String), + #[error("tls: {0}")] + Tls(String), + #[error("{0}")] + Other(String), +} + +pub type Result = std::result::Result; diff --git a/crates/synapse-caldav/src/ical.rs b/crates/synapse-caldav/src/ical.rs new file mode 100644 index 0000000..f79399f --- /dev/null +++ b/crates/synapse-caldav/src/ical.rs @@ -0,0 +1,288 @@ +//! Minimal RFC 5545 content-line parser/serialiser. +//! +//! Components keep every property (including unknown `X-` ones) in order, so a VTODO fetched +//! from a server can be edited and written back without losing data we do not understand. + +use crate::{Error, Result}; + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Prop { + pub name: String, + pub params: Vec<(String, String)>, + /// Raw (still escaped) value. + pub value: String, +} + +impl Prop { + pub fn new(name: &str, value: impl Into) -> Self { + Prop { + name: name.to_ascii_uppercase(), + params: Vec::new(), + value: value.into(), + } + } + + pub fn with_param(mut self, k: &str, v: &str) -> Self { + self.params.push((k.to_ascii_uppercase(), v.to_string())); + self + } + + pub fn param(&self, k: &str) -> Option<&str> { + self.params + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(k)) + .map(|(_, v)| v.as_str()) + } + + /// Value with TEXT escapes resolved. + pub fn text(&self) -> String { + unescape(&self.value) + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Component { + pub name: String, + pub props: Vec, + pub children: Vec, +} + +impl Component { + pub fn new(name: &str) -> Self { + Component { + name: name.to_ascii_uppercase(), + ..Default::default() + } + } + + pub fn prop(&self, name: &str) -> Option<&Prop> { + self.props + .iter() + .find(|p| p.name.eq_ignore_ascii_case(name)) + } + + pub fn props_named<'a>(&'a self, name: &'a str) -> impl Iterator { + self.props + .iter() + .filter(move |p| p.name.eq_ignore_ascii_case(name)) + } + + pub fn text(&self, name: &str) -> Option { + self.prop(name).map(Prop::text) + } + + /// Replaces the first property of that name (or appends it) and drops duplicates. + pub fn set(&mut self, prop: Prop) { + let name = prop.name.clone(); + let mut placed = false; + let mut out = Vec::with_capacity(self.props.len() + 1); + for p in self.props.drain(..) { + if p.name == name { + if !placed { + out.push(prop.clone()); + placed = true; + } + } else { + out.push(p); + } + } + if !placed { + out.push(prop); + } + self.props = out; + } + + pub fn remove(&mut self, name: &str) { + self.props.retain(|p| !p.name.eq_ignore_ascii_case(name)); + } + + pub fn children_named<'a>(&'a self, name: &'a str) -> impl Iterator { + self.children + .iter() + .filter(move |c| c.name.eq_ignore_ascii_case(name)) + } +} + +pub fn escape(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '\\' => o.push_str("\\\\"), + ';' => o.push_str("\\;"), + ',' => o.push_str("\\,"), + '\n' => o.push_str("\\n"), + '\r' => {} + c => o.push(c), + } + } + o +} + +pub fn unescape(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + let mut it = s.chars(); + while let Some(c) = it.next() { + if c == '\\' { + match it.next() { + Some('n') | Some('N') => o.push('\n'), + Some(x) => o.push(x), + None => o.push('\\'), + } + } else { + o.push(c); + } + } + o +} + +fn unfold(input: &str) -> Vec { + let mut lines: Vec = Vec::new(); + for raw in input.split('\n') { + let line = raw.strip_suffix('\r').unwrap_or(raw); + if let Some(rest) = line.strip_prefix([' ', '\t']) + && let Some(last) = lines.last_mut() + { + last.push_str(rest); + continue; + } + if !line.is_empty() { + lines.push(line.to_string()); + } + } + lines +} + +fn parse_line(line: &str) -> Result { + // name *(;param=value) : value ; colons inside quoted params are not separators. + let mut in_quotes = false; + let mut colon = None; + for (i, c) in line.char_indices() { + match c { + '"' => in_quotes = !in_quotes, + ':' if !in_quotes => { + colon = Some(i); + break; + } + _ => {} + } + } + let colon = colon.ok_or_else(|| Error::Ical(format!("bad content line: {line}")))?; + let (head, value) = (&line[..colon], &line[colon + 1..]); + let mut parts: Vec<&str> = Vec::new(); + let (mut start, mut q) = (0, false); + for (i, c) in head.char_indices() { + match c { + '"' => q = !q, + ';' if !q => { + parts.push(&head[start..i]); + start = i + 1; + } + _ => {} + } + } + parts.push(&head[start..]); + let mut prop = Prop::new(parts[0], value); + for p in &parts[1..] { + if let Some((k, v)) = p.split_once('=') { + prop.params + .push((k.to_ascii_uppercase(), v.trim_matches('"').to_string())); + } + } + Ok(prop) +} + +/// Parses a calendar object; returns the top-level components (normally one `VCALENDAR`). +pub fn parse(input: &str) -> Result> { + let mut stack: Vec = Vec::new(); + let mut done = Vec::new(); + for line in unfold(input) { + let prop = parse_line(&line)?; + match prop.name.as_str() { + "BEGIN" => stack.push(Component::new(&prop.value)), + "END" => { + let c = stack + .pop() + .ok_or_else(|| Error::Ical("END without BEGIN".into()))?; + match stack.last_mut() { + Some(parent) => parent.children.push(c), + None => done.push(c), + } + } + _ => match stack.last_mut() { + Some(c) => c.props.push(prop), + None => return Err(Error::Ical("property outside component".into())), + }, + } + } + if !stack.is_empty() { + return Err(Error::Ical("unterminated component".into())); + } + Ok(done) +} + +fn fold(line: &str, out: &mut String) { + // Fold at 75 octets without splitting a UTF-8 character. + let mut count = 0; + for c in line.chars() { + let n = c.len_utf8(); + if count + n > 75 { + out.push_str("\r\n "); + count = 1; + } + out.push(c); + count += n; + } + out.push_str("\r\n"); +} + +fn write_component(c: &Component, out: &mut String) { + fold(&format!("BEGIN:{}", c.name), out); + for p in &c.props { + let mut l = p.name.clone(); + for (k, v) in &p.params { + l.push(';'); + l.push_str(k); + l.push('='); + if v.contains([';', ':', ',']) { + l.push('"'); + l.push_str(v); + l.push('"'); + } else { + l.push_str(v); + } + } + l.push(':'); + l.push_str(&p.value); + fold(&l, out); + } + for ch in &c.children { + write_component(ch, out); + } + fold(&format!("END:{}", c.name), out); +} + +pub fn serialize(c: &Component) -> String { + let mut s = String::new(); + write_component(c, &mut s); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip_with_folding_and_params() { + let src = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:a\r\nSUMMARY:Long \r\n title\\, with comma\r\nDTSTART;TZID=\"Europe/Madrid\":20261021T100000\r\nX-FOO;P=\"a:b\":bar\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + let cal = parse(src).unwrap(); + let ev = &cal[0].children[0]; + assert_eq!(ev.text("SUMMARY").unwrap(), "Long title, with comma"); + assert_eq!( + ev.prop("DTSTART").unwrap().param("TZID"), + Some("Europe/Madrid") + ); + assert_eq!(ev.prop("X-FOO").unwrap().param("P"), Some("a:b")); + let again = parse(&serialize(&cal[0])).unwrap(); + assert_eq!(cal, again); + } +} diff --git a/crates/synapse-caldav/src/lib.rs b/crates/synapse-caldav/src/lib.rs new file mode 100644 index 0000000..b00e8e0 --- /dev/null +++ b/crates/synapse-caldav/src/lib.rs @@ -0,0 +1,14 @@ +//! CalDAV events and VTODO tasks, two-way with Synapse. See `docs/caldav.md`. + +pub mod calendar; +pub mod dav; +mod error; +pub mod ical; +pub mod mapping; +pub mod store; +pub mod sync; +pub mod xml; + +pub use dav::{CalendarInfo, Credentials, DavClient}; +pub use error::{Error, Result}; +pub use sync::{Config, SyncReport, events_for_day, materialize_day, refresh_calendars, sync}; diff --git a/crates/synapse-caldav/src/mapping.rs b/crates/synapse-caldav/src/mapping.rs new file mode 100644 index 0000000..6ee1709 --- /dev/null +++ b/crates/synapse-caldav/src/mapping.rs @@ -0,0 +1,263 @@ +//! Logseq task syntax <-> VTODO fields. +//! +//! ```text +//! TODO [#A] Pay rent +//! SCHEDULED: <2026-10-21 Wed> +//! DEADLINE: <2026-10-25 Sun 14:00> +//! free-form notes (become DESCRIPTION) +//! ``` + +use crate::calendar::{DtValue, Todo, TodoStatus}; +use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc}; +use chrono_tz::Tz; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Marker { + Todo, + Later, + Doing, + Now, + Done, + Canceled, +} + +impl Marker { + pub const ALL: [(&'static str, Marker); 7] = [ + ("TODO", Marker::Todo), + ("LATER", Marker::Later), + ("DOING", Marker::Doing), + ("NOW", Marker::Now), + ("DONE", Marker::Done), + ("CANCELED", Marker::Canceled), + ("CANCELLED", Marker::Canceled), + ]; + + pub fn as_str(self) -> &'static str { + match self { + Marker::Todo => "TODO", + Marker::Later => "LATER", + Marker::Doing => "DOING", + Marker::Now => "NOW", + Marker::Done => "DONE", + Marker::Canceled => "CANCELED", + } + } + + pub fn status(self) -> TodoStatus { + match self { + Marker::Todo | Marker::Later => TodoStatus::NeedsAction, + Marker::Doing | Marker::Now => TodoStatus::InProcess, + Marker::Done => TodoStatus::Completed, + Marker::Canceled => TodoStatus::Cancelled, + } + } + + /// Marker for a remote status, keeping `prev` when it is an equivalent spelling. + pub fn for_status(s: TodoStatus, prev: Option) -> Marker { + match prev { + Some(p) if p.status() == s => p, + _ => match s { + TodoStatus::NeedsAction => Marker::Todo, + TodoStatus::InProcess => Marker::Doing, + TodoStatus::Completed => Marker::Done, + TodoStatus::Cancelled => Marker::Canceled, + }, + } + } +} + +/// Parsed form of a task block's content. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskText { + pub marker: Marker, + pub priority: Option, + pub title: String, + pub scheduled: Option, + pub deadline: Option, + pub notes: String, +} + +fn split_marker(content: &str) -> Option<(Marker, &str)> { + let first = content.lines().next()?; + Marker::ALL.iter().find_map(|(word, m)| { + let rest = first.strip_prefix(word)?; + (rest.is_empty() || rest.starts_with(' ')).then_some((*m, rest)) + }) +} + +/// Detects the marker at the start of `content` (first line). +pub fn marker_of(content: &str) -> Option { + split_marker(content).map(|(m, _)| m) +} + +fn parse_ldate(s: &str) -> Option { + // `<2026-10-21 Wed>` or `<2026-10-21 Wed 14:00>`; repeaters (`+1w`) are ignored. + let inner = s.trim().strip_prefix('<')?.split('>').next()?; + let mut parts = inner.split_whitespace(); + let date = NaiveDate::parse_from_str(parts.next()?, "%Y-%m-%d").ok()?; + let time = parts.find_map(|p| NaiveTime::parse_from_str(p, "%H:%M").ok()); + Some(match time { + Some(t) => DtValue::Floating(NaiveDateTime::new(date, t)), + None => DtValue::Date(date), + }) +} + +fn fmt_ldate(v: &DtValue, view: Tz) -> String { + let n = v.local(view); + let day = n.format("%Y-%m-%d %a"); + if v.is_date() { + format!("<{day}>") + } else { + format!("<{day} {}>", n.format("%H:%M")) + } +} + +pub fn parse_task(content: &str) -> Option { + let (marker, rest) = split_marker(content)?; + let mut lines = content.lines(); + lines.next(); + let mut title = rest.trim().to_string(); + let mut priority = None; + if let Some(rest) = title.strip_prefix("[#") + && let Some((p, tail)) = rest.split_once(']') + && p.len() == 1 + { + priority = p.chars().next().map(|c| c.to_ascii_uppercase()); + title = tail.trim().to_string(); + } + let (mut scheduled, mut deadline) = (None, None); + let mut notes = Vec::new(); + for l in lines { + let t = l.trim(); + if let Some(r) = t.strip_prefix("SCHEDULED:") { + scheduled = parse_ldate(r); + } else if let Some(r) = t.strip_prefix("DEADLINE:") { + deadline = parse_ldate(r); + } else { + notes.push(l); + } + } + Some(TaskText { + marker, + priority, + title, + scheduled, + deadline, + notes: notes.join("\n").trim().to_string(), + }) +} + +pub fn render_task(t: &TaskText, view: Tz) -> String { + let mut out = t.marker.as_str().to_string(); + if let Some(p) = t.priority { + out.push_str(&format!(" [#{p}]")); + } + if !t.title.is_empty() { + out.push(' '); + out.push_str(&t.title); + } + if let Some(s) = &t.scheduled { + out.push_str(&format!("\nSCHEDULED: {}", fmt_ldate(s, view))); + } + if let Some(d) = &t.deadline { + out.push_str(&format!("\nDEADLINE: {}", fmt_ldate(d, view))); + } + if !t.notes.is_empty() { + out.push('\n'); + out.push_str(&t.notes); + } + out +} + +pub fn priority_to_ical(p: Option) -> u8 { + match p { + Some('A') => 1, + Some('B') => 5, + Some('C') => 9, + _ => 0, + } +} + +pub fn priority_from_ical(p: u8) -> Option { + match p { + 1..=4 => Some('A'), + 5 => Some('B'), + 6..=9 => Some('C'), + _ => None, + } +} + +/// Re-zones a floating local time so that the remote keeps an unambiguous instant. +fn to_remote(v: DtValue, view: Tz) -> DtValue { + match v { + DtValue::Floating(n) => DtValue::Zoned(view, n), + o => o, + } +} + +/// Task fields from block content. `existing` supplies the fields Synapse does not model +/// (percent, COMPLETED timestamp) and the previous values for unchanged dates. +pub fn todo_from_text( + t: &TaskText, + uid: &str, + existing: Option<&Todo>, + view: Tz, + now: DateTime, +) -> Todo { + let status = t.marker.status(); + // Keep the original zoned value when the local rendering did not change. + let keep = |new: &Option, old: Option<&DtValue>| match (new, old) { + (Some(n), Some(o)) if n.local(view) == o.local(view) && n.is_date() == o.is_date() => { + Some(o.clone()) + } + (Some(n), _) => Some(to_remote(n.clone(), view)), + (None, _) => None, + }; + Todo { + uid: uid.to_string(), + summary: t.title.clone(), + description: (!t.notes.is_empty()).then(|| t.notes.clone()), + status, + percent: existing.and_then(|e| e.percent), + priority: priority_to_ical(t.priority), + start: keep(&t.scheduled, existing.and_then(|e| e.start.as_ref())), + due: keep(&t.deadline, existing.and_then(|e| e.due.as_ref())), + completed: match status { + TodoStatus::Completed => Some(existing.and_then(|e| e.completed).unwrap_or(now)), + _ => None, + }, + last_modified: Some(now), + has_rrule: existing.is_some_and(|e| e.has_rrule), + } +} + +pub fn text_from_todo(t: &Todo, prev: Option) -> TaskText { + TaskText { + marker: Marker::for_status(t.status, prev), + priority: priority_from_ical(t.priority), + title: t.summary.clone(), + scheduled: t.start.clone(), + deadline: t.due.clone(), + notes: t.description.clone().unwrap_or_default(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_render() { + let c = "TODO [#A] Pay rent\nSCHEDULED: <2026-10-21 Wed>\nDEADLINE: <2026-10-25 Sun 14:00>\nsome note"; + let t = parse_task(c).unwrap(); + assert_eq!(t.marker, Marker::Todo); + assert_eq!(t.priority, Some('A')); + assert_eq!(t.title, "Pay rent"); + assert_eq!(t.notes, "some note"); + assert!(t.scheduled.as_ref().unwrap().is_date()); + assert_eq!(render_task(&t, chrono_tz::UTC), c); + assert!(parse_task("TODOS x").is_none()); + assert_eq!(parse_task("DONE").unwrap().title, ""); + assert_eq!(priority_from_ical(priority_to_ical(Some('B'))), Some('B')); + } +} diff --git a/crates/synapse-caldav/src/store.rs b/crates/synapse-caldav/src/store.rs new file mode 100644 index 0000000..3e79426 --- /dev/null +++ b/crates/synapse-caldav/src/store.rs @@ -0,0 +1,204 @@ +//! `caldav_*` tables living in the graph database (sync tokens, etags, uid <-> block ids). + +use crate::Result; +use rusqlite::{Connection, OptionalExtension, params}; + +const SCHEMA: &str = r#" +CREATE TABLE IF NOT EXISTS caldav_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS caldav_calendar ( + href TEXT PRIMARY KEY, + name TEXT NOT NULL, + events INTEGER NOT NULL, + tasks INTEGER NOT NULL, + ctag TEXT, + sync_token TEXT +); +-- One row per remote calendar object. `ics` is the last server version (needed to edit a task +-- without losing unknown properties and to answer events_for_day offline). +CREATE TABLE IF NOT EXISTS caldav_object ( + href TEXT PRIMARY KEY, + calendar TEXT NOT NULL, + uid TEXT NOT NULL, + kind TEXT NOT NULL, + etag TEXT NOT NULL, + ics TEXT NOT NULL, + block_id TEXT, + synced_content TEXT +); +CREATE INDEX IF NOT EXISTS caldav_object_cal ON caldav_object(calendar, kind); +CREATE INDEX IF NOT EXISTS caldav_object_uid ON caldav_object(uid); +CREATE INDEX IF NOT EXISTS caldav_object_block ON caldav_object(block_id); +-- Event occurrences materialised as journal blocks. +CREATE TABLE IF NOT EXISTS caldav_event_block ( + uid TEXT NOT NULL, + day TEXT NOT NULL, + block_id TEXT NOT NULL, + content TEXT NOT NULL, + PRIMARY KEY (uid, day, block_id) +); +"#; + +pub fn ensure_schema(conn: &Connection) -> Result<()> { + conn.execute_batch(SCHEMA)?; + Ok(()) +} + +#[derive(Debug, Clone)] +pub struct CalendarRow { + pub href: String, + pub name: String, + pub events: bool, + pub tasks: bool, + pub ctag: Option, + pub sync_token: Option, +} + +#[derive(Debug, Clone)] +pub struct ObjectRow { + pub href: String, + pub calendar: String, + pub uid: String, + pub kind: String, + pub etag: String, + pub ics: String, + pub block_id: Option, + pub synced_content: Option, +} + +const OBJ_COLS: &str = "href, calendar, uid, kind, etag, ics, block_id, synced_content"; + +fn obj_row(r: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(ObjectRow { + href: r.get(0)?, + calendar: r.get(1)?, + uid: r.get(2)?, + kind: r.get(3)?, + etag: r.get(4)?, + ics: r.get(5)?, + block_id: r.get(6)?, + synced_content: r.get(7)?, + }) +} + +pub fn meta_get(c: &Connection, key: &str) -> Result> { + Ok( + c.query_row("SELECT value FROM caldav_meta WHERE key=?1", [key], |r| { + r.get(0) + }) + .optional()?, + ) +} + +pub fn meta_set(c: &Connection, key: &str, value: &str) -> Result<()> { + c.execute( + "INSERT INTO caldav_meta(key, value) VALUES(?1, ?2) ON CONFLICT(key) DO UPDATE SET value=?2", + [key, value], + )?; + Ok(()) +} + +pub fn calendars(c: &Connection) -> Result> { + let mut st = c.prepare("SELECT href, name, events, tasks, ctag, sync_token FROM caldav_calendar ORDER BY name, href")?; + let rows = st + .query_map([], |r| { + Ok(CalendarRow { + href: r.get(0)?, + name: r.get(1)?, + events: r.get::<_, i64>(2)? != 0, + tasks: r.get::<_, i64>(3)? != 0, + ctag: r.get(4)?, + sync_token: r.get(5)?, + }) + })? + .collect::>()?; + Ok(rows) +} + +pub fn calendar(c: &Connection, href: &str) -> Result> { + Ok(calendars(c)?.into_iter().find(|r| r.href == href)) +} + +/// Inserts or updates a calendar's descriptive fields, keeping its sync state. +pub fn upsert_calendar( + c: &Connection, + name: &str, + href: &str, + events: bool, + tasks: bool, +) -> Result<()> { + c.execute( + "INSERT INTO caldav_calendar(href, name, events, tasks) VALUES(?1, ?2, ?3, ?4) + ON CONFLICT(href) DO UPDATE SET name=?2, events=?3, tasks=?4", + params![href, name, events, tasks], + )?; + Ok(()) +} + +pub fn set_calendar_state( + c: &Connection, + href: &str, + ctag: Option<&str>, + token: Option<&str>, +) -> Result<()> { + c.execute( + "UPDATE caldav_calendar SET ctag=COALESCE(?2, ctag), sync_token=COALESCE(?3, sync_token) WHERE href=?1", + params![href, ctag, token], + )?; + Ok(()) +} + +pub fn clear_calendar_token(c: &Connection, href: &str) -> Result<()> { + c.execute( + "UPDATE caldav_calendar SET sync_token=NULL, ctag=NULL WHERE href=?1", + [href], + )?; + Ok(()) +} + +pub fn object(c: &Connection, href: &str) -> Result> { + Ok(c.query_row( + &format!("SELECT {OBJ_COLS} FROM caldav_object WHERE href=?1"), + [href], + obj_row, + ) + .optional()?) +} + +pub fn object_by_block(c: &Connection, block: &str) -> Result> { + Ok(c.query_row( + &format!("SELECT {OBJ_COLS} FROM caldav_object WHERE block_id=?1"), + [block], + obj_row, + ) + .optional()?) +} + +pub fn objects( + c: &Connection, + calendar: Option<&str>, + kind: Option<&str>, +) -> Result> { + let mut st = c.prepare(&format!( + "SELECT {OBJ_COLS} FROM caldav_object WHERE (?1 IS NULL OR calendar=?1) AND (?2 IS NULL OR kind=?2) ORDER BY href" + ))?; + let rows = st + .query_map(params![calendar, kind], obj_row)? + .collect::>()?; + Ok(rows) +} + +pub fn put_object(c: &Connection, o: &ObjectRow) -> Result<()> { + c.execute( + &format!( + "INSERT INTO caldav_object({OBJ_COLS}) VALUES(?1,?2,?3,?4,?5,?6,?7,?8) + ON CONFLICT(href) DO UPDATE SET calendar=?2, uid=?3, kind=?4, etag=?5, ics=?6, block_id=?7, synced_content=?8" + ), + params![o.href, o.calendar, o.uid, o.kind, o.etag, o.ics, o.block_id, o.synced_content], + )?; + Ok(()) +} + +pub fn delete_object(c: &Connection, href: &str) -> Result<()> { + c.execute("DELETE FROM caldav_object WHERE href=?1", [href])?; + Ok(()) +} diff --git a/crates/synapse-caldav/src/sync.rs b/crates/synapse-caldav/src/sync.rs new file mode 100644 index 0000000..8264fdc --- /dev/null +++ b/crates/synapse-caldav/src/sync.rs @@ -0,0 +1,638 @@ +//! Two-way synchronisation between a CalDAV account and a Synapse graph. +//! +//! The futures hold `&Graph` (which is `Send` but not `Sync`) across awaits, so they are not +//! `Send`: drive them with `block_on` on a current-thread runtime / dedicated thread. + +use crate::calendar::{ + self, Event, Todo, event_occurrences, master_todo, master_todo_mut, parse_calendar, +}; +use crate::dav::{CalendarInfo, DavClient, RemoteObject}; +use crate::mapping::{self, Marker, TaskText}; +use crate::store::{self, ObjectRow}; +use crate::{Error, Result, ical}; +use chrono::{DateTime, Duration, NaiveDate, NaiveTime, TimeZone, Utc}; +use chrono_tz::Tz; +use serde_json::Value; +use synapse_core::{Block, BlockId, Graph, Placement, Properties}; +use uuid::Uuid; + +pub const PROP_UID: &str = "caldav-uid"; +pub const PROP_CALENDAR: &str = "caldav-calendar"; +pub const PROP_EVENT: &str = "caldav-event"; + +#[derive(Debug, Clone)] +pub struct Config { + /// Zone used to show UTC/zoned times and to interpret floating ones. + pub tz: Tz, + /// Href of the task list that receives new tasks written in journals + /// (default: the first calendar that supports VTODO). + pub default_task_calendar: Option, +} + +impl Config { + pub fn new(tz: Tz) -> Self { + Config { + tz, + default_task_calendar: None, + } + } +} + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct SyncReport { + pub calendars: usize, + pub events_changed: usize, + pub tasks_pulled: usize, + pub removed_remote: usize, + pub tasks_created_remote: usize, + pub tasks_updated_remote: usize, + pub tasks_deleted_remote: usize, + pub conflicts: usize, +} + +fn now_utc(graph: &Graph) -> DateTime { + Utc.timestamp_millis_opt(graph.now_ms()) + .single() + .unwrap_or_else(Utc::now) +} + +/// Discovers the account's calendars and records them locally (sync state is preserved). +pub async fn refresh_calendars(graph: &Graph, client: &DavClient) -> Result> { + store::ensure_schema(graph.conn())?; + let home = match store::meta_get(graph.conn(), "home")? { + Some(h) => h, + None => { + let h = client.discover().await?; + store::meta_set(graph.conn(), "home", &h)?; + h + } + }; + let cals = client.list_calendars(&home).await?; + for c in &cals { + if c.supports_events || c.supports_tasks { + store::upsert_calendar( + graph.conn(), + &c.name, + &c.href, + c.supports_events, + c.supports_tasks, + )?; + } + } + Ok(cals) +} + +/// Full two-way sync: pull every calendar, then push local task changes. +pub async fn sync(graph: &Graph, client: &DavClient, cfg: &Config) -> Result { + store::ensure_schema(graph.conn())?; + if store::meta_get(graph.conn(), "enabled_at")?.is_none() { + store::meta_set(graph.conn(), "enabled_at", &graph.now_ms().to_string())?; + } + refresh_calendars(graph, client).await?; + let mut rep = SyncReport::default(); + let cals = store::calendars(graph.conn())?; + rep.calendars = cals.len(); + for cal in &cals { + pull_calendar(graph, client, cfg, cal, &mut rep).await?; + } + push_tasks(graph, client, cfg, &mut rep).await?; + Ok(rep) +} + +// ------------------------------------------------------------------------------- pull + +async fn pull_calendar( + graph: &Graph, + client: &DavClient, + cfg: &Config, + cal: &store::CalendarRow, + rep: &mut SyncReport, +) -> Result<()> { + let known: std::collections::HashMap = + store::objects(graph.conn(), Some(&cal.href), None)? + .into_iter() + .map(|o| (o.href, o.etag)) + .collect(); + type Pulled = ( + Vec<(String, String)>, + Vec, + Option, + Option, + ); + let (changed, deleted, new_token, new_ctag): Pulled; + let incremental = match client + .sync_collection(&cal.href, cal.sync_token.as_deref()) + .await? + { + Some(ch) => Some(ch), + None if cal.sync_token.is_some() => { + // Token rejected: restart with a full sync-collection. + store::clear_calendar_token(graph.conn(), &cal.href)?; + client.sync_collection(&cal.href, None).await? + } + None => None, + }; + if let Some(ch) = incremental { + changed = ch.changed; + deleted = ch.deleted; + new_token = ch.new_token; + new_ctag = None; + } else { + // ctag/etag fallback. + let ctag = client.ctag(&cal.href).await?; + if ctag.is_some() && ctag == cal.ctag { + return Ok(()); + } + let all = client.list_etags(&cal.href).await?; + let present: std::collections::HashSet<&String> = all.iter().map(|(h, _)| h).collect(); + deleted = known + .keys() + .filter(|h| !present.contains(h)) + .cloned() + .collect(); + changed = all.to_vec(); + new_token = None; + new_ctag = ctag; + } + for h in &deleted { + remove_remote(graph, h, rep)?; + } + let want: Vec = changed + .iter() + .filter(|(h, e)| known.get(h) != Some(e)) + .map(|(h, _)| h.clone()) + .collect(); + if !want.is_empty() { + for obj in client.multiget(&cal.href, &want).await? { + apply_remote(graph, cfg, &cal.href, &cal.name, &obj, rep)?; + } + } + store::set_calendar_state( + graph.conn(), + &cal.href, + new_ctag.as_deref(), + new_token.as_deref(), + )?; + Ok(()) +} + +fn merge_props(block: &Block, uid: &str, cal: &str) -> Properties { + let mut p = block.properties.clone(); + p.insert(PROP_UID.into(), Value::String(uid.into())); + p.insert(PROP_CALENDAR.into(), Value::String(cal.into())); + p +} + +fn conflict_note(graph: &Graph, block: &Block, label: &str, content: &str) -> Result<()> { + let note = format!("CalDAV conflict: {label} version (older, kept as note)\n{content}"); + graph.insert_block(block.page_id, Placement::LastChildOf(Some(block.id)), ¬e)?; + Ok(()) +} + +fn remove_remote(graph: &Graph, href: &str, rep: &mut SyncReport) -> Result<()> { + let Some(row) = store::object(graph.conn(), href)? else { + return Ok(()); + }; + rep.removed_remote += 1; + if let Some(bid) = row + .block_id + .as_deref() + .and_then(|s| Uuid::parse_str(s).ok()) + && let Some(block) = graph.get_block(bid)? + { + if Some(&block.content) == row.synced_content.as_ref() { + graph.delete_block(bid)?; + } else { + // Local edits win over a remote delete: detach and let the push re-create it. + let mut p = block.properties.clone(); + p.remove(PROP_UID); + p.remove(PROP_CALENDAR); + graph.set_block_properties(bid, p)?; + } + } + store::delete_object(graph.conn(), href) +} + +fn apply_remote( + graph: &Graph, + cfg: &Config, + cal_href: &str, + cal_name: &str, + obj: &RemoteObject, + rep: &mut SyncReport, +) -> Result<()> { + let cal = parse_calendar(&obj.ics)?; + let is_task = cal.children_named("VTODO").next().is_some(); + let is_event = cal.children_named("VEVENT").next().is_some(); + let comp = if is_task { + master_todo(&cal) + } else { + cal.children_named("VEVENT").next() + }; + let Some(comp) = comp else { return Ok(()) }; + let Some(uid) = comp.text("UID") else { + return Ok(()); + }; + let existing = store::object(graph.conn(), &obj.href)?; + + if !is_task { + if is_event { + rep.events_changed += 1; + } + store::put_object( + graph.conn(), + &ObjectRow { + href: obj.href.clone(), + calendar: cal_href.to_string(), + uid, + kind: if is_event { "VEVENT" } else { "OTHER" }.into(), + etag: obj.etag.clone(), + ics: obj.ics.clone(), + block_id: None, + synced_content: None, + }, + )?; + return Ok(()); + } + + let Some(todo) = Todo::from_component(comp) else { + return Ok(()); + }; + rep.tasks_pulled += 1; + let block = existing + .as_ref() + .and_then(|r| r.block_id.as_deref()) + .and_then(|s| Uuid::parse_str(s).ok()) + .map(|id| graph.get_block(id)) + .transpose()? + .flatten(); + let mut row = ObjectRow { + href: obj.href.clone(), + calendar: cal_href.to_string(), + uid: uid.clone(), + kind: "VTODO".into(), + etag: obj.etag.clone(), + ics: obj.ics.clone(), + block_id: existing.as_ref().and_then(|r| r.block_id.clone()), + synced_content: existing.as_ref().and_then(|r| r.synced_content.clone()), + }; + match block { + None if existing.as_ref().is_some_and(|r| r.block_id.is_some()) => { + // Deleted locally: keep the old etag so the push phase can delete remotely. + return Ok(()); + } + None => { + let page = graph.ensure_page(cal_name, None)?; + let content = mapping::render_task(&mapping::text_from_todo(&todo, None), cfg.tz); + let b = graph.insert_block(page.id, Placement::LastChildOf(None), &content)?; + graph.set_block_properties(b.id, merge_props(&b, &uid, cal_href))?; + row.block_id = Some(b.id.to_string()); + row.synced_content = Some(content); + } + Some(b) => { + let prev = mapping::marker_of(&b.content); + let content = mapping::render_task(&mapping::text_from_todo(&todo, prev), cfg.tz); + let local_changed = Some(&b.content) != row.synced_content.as_ref(); + if !local_changed || b.content == content { + if b.content != content { + graph.update_block(b.id, &content)?; + } + row.synced_content = Some(content); + } else { + rep.conflicts += 1; + let remote_ms = todo + .last_modified + .map(|t| t.timestamp_millis()) + .unwrap_or(0); + if remote_ms >= b.updated_at { + conflict_note(graph, &b, "local", &b.content)?; + graph.update_block(b.id, &content)?; + row.synced_content = Some(content); + } else { + // Local is newer: keep it (the push phase uploads it) and note the remote. + conflict_note(graph, &b, "remote", &content)?; + } + } + } + } + store::put_object(graph.conn(), &row) +} + +// ------------------------------------------------------------------------------- push + +fn default_task_calendar(graph: &Graph, cfg: &Config) -> Result> { + let cals = store::calendars(graph.conn())?; + Ok(match &cfg.default_task_calendar { + Some(h) => cals.into_iter().find(|c| &c.href == h), + None => cals.into_iter().find(|c| c.tasks), + }) +} + +async fn push_tasks( + graph: &Graph, + client: &DavClient, + cfg: &Config, + rep: &mut SyncReport, +) -> Result<()> { + // Tracked tasks: edits and deletions. + for row in store::objects(graph.conn(), None, Some("VTODO"))? { + if row.block_id.is_none() { + continue; + } + push_tracked(graph, client, cfg, row, rep).await?; + } + // New tasks typed into journals. + let Some(cal) = default_task_calendar(graph, cfg)? else { + return Ok(()); + }; + let since: i64 = store::meta_get(graph.conn(), "enabled_at")? + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let mut st = graph.conn().prepare( + "SELECT b.id FROM blocks b JOIN pages p ON p.id=b.page_id + WHERE p.journal_date IS NOT NULL AND b.updated_at >= ?1 + AND b.properties NOT LIKE '%caldav-uid%' ORDER BY b.created_at", + )?; + let ids: Vec = st + .query_map([since], |r| r.get(0))? + .collect::>()?; + drop(st); + for id in ids { + let Some(b) = Uuid::parse_str(&id) + .ok() + .map(|i| graph.get_block(i)) + .transpose()? + .flatten() + else { + continue; + }; + let Some(task) = mapping::parse_task(&b.content) else { + continue; + }; + if matches!(task.marker, Marker::Done | Marker::Canceled) { + continue; + } + let uid = Uuid::now_v7().to_string(); + let todo = mapping::todo_from_text(&task, &uid, None, cfg.tz, now_utc(graph)); + let ics = ical::serialize(&todo.to_calendar(now_utc(graph))); + let href = format!("{}/{}.ics", cal.href.trim_end_matches('/'), uid); + let etag = client.put(&href, &ics, None).await?; + graph.set_block_properties(b.id, merge_props(&b, &uid, &cal.href))?; + store::put_object( + graph.conn(), + &ObjectRow { + href, + calendar: cal.href.clone(), + uid, + kind: "VTODO".into(), + etag, + ics, + block_id: Some(b.id.to_string()), + synced_content: Some(b.content.clone()), + }, + )?; + rep.tasks_created_remote += 1; + } + Ok(()) +} + +async fn push_tracked( + graph: &Graph, + client: &DavClient, + cfg: &Config, + row: ObjectRow, + rep: &mut SyncReport, +) -> Result<()> { + let mut row = row; + for attempt in 0..2 { + let block = row + .block_id + .as_deref() + .and_then(|s| Uuid::parse_str(s).ok()) + .map(|id| graph.get_block(id)) + .transpose()? + .flatten(); + let Some(block) = block else { + // Deleted locally. + match client.delete(&row.href, Some(&row.etag)).await { + Ok(()) => { + store::delete_object(graph.conn(), &row.href)?; + rep.tasks_deleted_remote += 1; + } + Err(Error::PreconditionFailed(_)) => { + // Changed remotely meanwhile: the remote edit wins, bring it back. + let obj = client.get(&row.href).await?; + store::delete_object(graph.conn(), &row.href)?; + let name = store::calendar(graph.conn(), &row.calendar)? + .map(|c| c.name) + .unwrap_or_default(); + apply_remote(graph, cfg, &row.calendar, &name, &obj, rep)?; + } + Err(e) => return Err(e), + } + return Ok(()); + }; + if Some(&block.content) == row.synced_content.as_ref() { + return Ok(()); + } + let Some(task) = mapping::parse_task(&block.content) else { + return Ok(()); // no longer a task; leave the remote alone + }; + let mut cal = parse_calendar(&row.ics)?; + let existing = master_todo(&cal).and_then(Todo::from_component); + let now = now_utc(graph); + let todo = mapping::todo_from_text(&task, &row.uid, existing.as_ref(), cfg.tz, now); + let Some(comp) = master_todo_mut(&mut cal) else { + return Ok(()); + }; + todo.apply_to(comp, now); + let ics = ical::serialize(&cal); + match client.put(&row.href, &ics, Some(&row.etag)).await { + Ok(etag) => { + row.etag = etag; + row.ics = ics; + row.synced_content = Some(block.content.clone()); + store::put_object(graph.conn(), &row)?; + rep.tasks_updated_remote += 1; + return Ok(()); + } + Err(Error::PreconditionFailed(_)) if attempt == 0 => { + // Both sides changed: resolve by last-modified, then retry once. + let obj = client.get(&row.href).await?; + let name = store::calendar(graph.conn(), &row.calendar)? + .map(|c| c.name) + .unwrap_or_default(); + apply_remote(graph, cfg, &row.calendar, &name, &obj, rep)?; + row = store::object(graph.conn(), &row.href)? + .ok_or_else(|| Error::Other("object vanished".into()))?; + } + Err(e) => return Err(e), + } + } + Ok(()) +} + +// ------------------------------------------------------------------------------ events + +/// Events (with recurrences expanded) overlapping `day`, from the local cache. +pub fn events_for_day(graph: &Graph, day: NaiveDate, tz: Tz) -> Result> { + events_between(graph, day, day + Duration::days(1), tz) +} + +/// Events overlapping `[from, to)` (dates), from the local cache. +pub fn events_between( + graph: &Graph, + from: NaiveDate, + to: NaiveDate, + tz: Tz, +) -> Result> { + store::ensure_schema(graph.conn())?; + let names: std::collections::HashMap = store::calendars(graph.conn())? + .into_iter() + .map(|c| (c.href, c.name)) + .collect(); + let (f, t) = (from.and_time(NaiveTime::MIN), to.and_time(NaiveTime::MIN)); + let mut out = Vec::new(); + for o in store::objects(graph.conn(), None, Some("VEVENT"))? { + let Ok(cal) = parse_calendar(&o.ics) else { + continue; + }; + let name = names.get(&o.calendar).cloned().unwrap_or_default(); + out.extend(event_occurrences(&cal, &name, &o.href, tz, f, t)); + } + out.sort_by_key(|o| (o.start, o.summary.clone())); + Ok(out) +} + +fn clean(s: &str) -> String { + s.replace("[[", "[ [") + .replace("]]", "] ]") + .replace('\n', " ") +} + +fn occurrence_text(o: &calendar::Occurrence) -> String { + let when = if o.all_day { + "All day".to_string() + } else { + format!("{}-{}", o.start.format("%H:%M"), o.end.format("%H:%M")) + }; + let title = clean(&o.summary); + // A page per recurring meeting collects its notes across occurrences. + let title = if o.recurring && !title.is_empty() { + format!("[[{title}]]") + } else { + title + }; + format!("{when} {title}") +} + +/// Writes the day's events into its journal as blocks (idempotent; updates changed events and +/// removes blocks of events that vanished). Returns the block ids, in time order. +pub fn materialize_day(graph: &Graph, day: NaiveDate, tz: Tz) -> Result> { + let occs = events_for_day(graph, day, tz)?; + let journal = graph.journal(day)?; + let day_s = day.to_string(); + let mut ids = Vec::new(); + let mut keep = Vec::new(); + for o in &occs { + let text = occurrence_text(o); + let key = format!("{}@{}", o.uid, o.start.format("%Y%m%dT%H%M%S")); + let existing: Option<(String, String)> = graph + .conn() + .query_row( + "SELECT block_id, content FROM caldav_event_block WHERE uid=?1 AND day=?2", + [&key, &day_s], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .ok(); + let block = match existing { + Some((bid, old)) => match Uuid::parse_str(&bid) + .ok() + .map(|i| graph.get_block(i)) + .transpose()? + .flatten() + { + Some(b) => { + // Do not overwrite text the user edited by hand. + if b.content == old && old != text { + graph.update_block(b.id, &text)?; + } + b + } + None => new_event_block(graph, &journal, &text, &o.uid)?, + }, + None => new_event_block(graph, &journal, &text, &o.uid)?, + }; + graph.conn().execute( + "DELETE FROM caldav_event_block WHERE uid=?1 AND day=?2", + [&key, &day_s], + )?; + graph.conn().execute( + "INSERT INTO caldav_event_block(uid, day, block_id, content) VALUES(?1,?2,?3,?4)", + [&key, &day_s, &block.id.to_string(), &text], + )?; + keep.push(key); + ids.push(block.id); + } + // Events no longer on that day. + let mut st = graph + .conn() + .prepare("SELECT uid, block_id, content FROM caldav_event_block WHERE day=?1")?; + let rows: Vec<(String, String, String)> = st + .query_map([&day_s], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? + .collect::>()?; + drop(st); + for (key, bid, content) in rows { + if keep.contains(&key) { + continue; + } + if let Some(b) = Uuid::parse_str(&bid) + .ok() + .map(|i| graph.get_block(i)) + .transpose()? + .flatten() + && b.content == content + { + graph.delete_block(b.id)?; + } + graph.conn().execute( + "DELETE FROM caldav_event_block WHERE uid=?1 AND day=?2", + [&key, &day_s], + )?; + } + Ok(ids) +} + +fn new_event_block( + graph: &Graph, + journal: &synapse_core::Page, + text: &str, + uid: &str, +) -> Result { + let b = graph.insert_block(journal.id, Placement::LastChildOf(None), text)?; + let mut p = b.properties.clone(); + p.insert(PROP_EVENT.into(), Value::String(uid.into())); + Ok(graph.set_block_properties(b.id, p)?) +} + +/// Helper for UIs: the event model behind a cached object. +pub fn event_of(ics: &str) -> Option { + let cal = parse_calendar(ics).ok()?; + cal.children_named("VEVENT").find_map(Event::from_component) +} + +/// Marks a task block done/undone locally (the next sync pushes it). +pub fn set_task_done(graph: &Graph, id: BlockId, done: bool) -> Result<()> { + let b = graph + .get_block(id)? + .ok_or_else(|| Error::Other("block not found".into()))?; + let Some(t) = mapping::parse_task(&b.content) else { + return Err(Error::Other("not a task block".into())); + }; + let new = TaskText { + marker: if done { Marker::Done } else { Marker::Todo }, + ..t + }; + graph.update_block(id, &mapping::render_task(&new, chrono_tz::UTC))?; + Ok(()) +} diff --git a/crates/synapse-caldav/src/xml.rs b/crates/synapse-caldav/src/xml.rs new file mode 100644 index 0000000..c570f54 --- /dev/null +++ b/crates/synapse-caldav/src/xml.rs @@ -0,0 +1,223 @@ +//! WebDAV multistatus parsing (namespace prefixes are ignored; local names only). + +use crate::{Error, Result}; +use quick_xml::Reader; +use quick_xml::events::Event; + +#[derive(Debug, Default, Clone)] +pub struct Response { + pub href: String, + /// Response-level status (used by `sync-collection` for removed members). + pub status: Option, + /// Elements found under `prop` in successful propstats: (path below `prop`, text). + /// Every element yields an entry, so presence can be tested with `has`. + pub items: Vec<(Vec, String)>, +} + +impl Response { + pub fn text(&self, path: &[&str]) -> Option<&str> { + self.items + .iter() + .find(|(p, t)| p.iter().map(String::as_str).eq(path.iter().copied()) && !t.is_empty()) + .map(|(_, t)| t.as_str()) + } + + pub fn has(&self, path: &[&str]) -> bool { + self.items + .iter() + .any(|(p, _)| p.iter().map(String::as_str).eq(path.iter().copied())) + } + + pub fn is_removed(&self) -> bool { + self.status.as_deref().is_some_and(|s| s.contains(" 404")) + } +} + +#[derive(Debug, Default)] +pub struct Multistatus { + pub responses: Vec, + pub sync_token: Option, +} + +fn local(s: &str) -> String { + s.rsplit(':').next().unwrap_or("").to_string() +} + +fn xerr(e: impl std::fmt::Display) -> Error { + Error::Xml(e.to_string()) +} + +#[derive(Default)] +struct Parser { + out: Multistatus, + stack: Vec, + resp: Option, + ps_items: Vec<(Vec, String)>, + ps_status: String, + text: String, +} + +impl Parser { + fn in_prop(&self) -> Option { + self.stack.iter().position(|s| s == "prop") + } + + fn start(&mut self, name: String) { + self.text.clear(); + match name.as_str() { + "response" => self.resp = Some(Response::default()), + "propstat" => { + self.ps_items.clear(); + self.ps_status.clear(); + } + _ => {} + } + self.stack.push(name); + if let Some(pos) = self.in_prop() + && self.stack.len() > pos + 1 + && self.resp.is_some() + { + self.ps_items + .push((self.stack[pos + 1..].to_vec(), String::new())); + } + } + + fn end(&mut self) { + let Some(name) = self.stack.last().cloned() else { + return; + }; + let t = std::mem::take(&mut self.text); + let t = t.trim(); + let in_propstat = self.stack.iter().any(|s| s == "propstat"); + match name.as_str() { + "href" if self.in_prop().is_none() && self.stack.len() == 3 => { + if let Some(r) = self.resp.as_mut() { + r.href = t.to_string(); + } + } + "status" if in_propstat => self.ps_status = t.to_string(), + "status" => { + if let Some(r) = self.resp.as_mut() { + r.status = Some(t.to_string()); + } + } + "sync-token" if self.in_prop().is_none() && self.stack.len() == 2 => { + self.out.sync_token = Some(t.to_string()); + } + "propstat" => { + if let Some(r) = self.resp.as_mut() + && self.ps_status.contains(" 2") + { + r.items.append(&mut self.ps_items); + } + self.ps_items.clear(); + } + "response" => { + if let Some(r) = self.resp.take() { + self.out.responses.push(r); + } + } + _ => {} + } + if let Some(pos) = self.in_prop() + && self.stack.len() > pos + 1 + && !t.is_empty() + { + let path = self.stack[pos + 1..].to_vec(); + if let Some(it) = self + .ps_items + .iter_mut() + .rev() + .find(|(p, v)| *p == path && v.is_empty()) + { + it.1 = t.to_string(); + } + } + self.stack.pop(); + } +} + +fn element_name(e: &quick_xml::events::BytesStart<'_>) -> String { + let mut name = local(e.name().as_ref()); + // `` is distinguished by its attribute. + if name == "comp" { + for a in e.attributes().flatten() { + if a.key.as_ref() == "name" { + name = format!("comp:{}", a.value); + } + } + } + name +} + +pub fn parse_multistatus(xml: &str) -> Result { + let mut rd = Reader::from_str(xml); + let mut p = Parser::default(); + loop { + match rd.read_event().map_err(xerr)? { + Event::Start(e) => p.start(element_name(&e)), + Event::Empty(e) => { + p.start(element_name(&e)); + p.end(); + } + Event::Text(t) => p + .text + .push_str(&Ok::<_, std::convert::Infallible>(t.xml10_content()).map_err(xerr)?), + Event::CData(c) => p.text.push_str(c.as_ref()), + Event::GeneralRef(r) => match r.resolve_char_ref() { + Ok(Some(c)) => p.text.push(c), + _ => match &*r { + "amp" => p.text.push('&'), + "lt" => p.text.push('<'), + "gt" => p.text.push('>'), + "quot" => p.text.push('"'), + "apos" => p.text.push('\''), + _ => {} + }, + }, + Event::End(_) => p.end(), + Event::Eof => break, + _ => {} + } + } + Ok(p.out) +} + +/// Escapes text for inclusion in an XML request body. +pub fn esc(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn multistatus_basic() { + let x = r#" + +/cal/a.ics"e1" +BEGIN:VCALENDAR +SUMMARY:A & B +END:VCALENDARHTTP/1.1 200 OK +HTTP/1.1 404 Not Found +/cal/gone.icsHTTP/1.1 404 Not Found +tok-7 +"#; + let m = parse_multistatus(x).unwrap(); + assert_eq!(m.sync_token.as_deref(), Some("tok-7")); + assert_eq!(m.responses.len(), 2); + assert_eq!(m.responses[0].href, "/cal/a.ics"); + assert_eq!(m.responses[0].text(&["getetag"]), Some("\"e1\"")); + assert!( + m.responses[0] + .text(&["calendar-data"]) + .unwrap() + .contains("A & B") + ); + assert!(!m.responses[0].has(&["getctag"]), "404 propstat ignored"); + assert!(m.responses[1].is_removed()); + } +} diff --git a/crates/synapse-caldav/tests/mock.rs b/crates/synapse-caldav/tests/mock.rs new file mode 100644 index 0000000..bac9119 --- /dev/null +++ b/crates/synapse-caldav/tests/mock.rs @@ -0,0 +1,398 @@ +//! A tiny in-process CalDAV server (just enough of RFC 4791/6578 for the client). +#![allow(dead_code)] + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +pub const HOME: &str = "/dav/calendars/user/"; +pub const PERSONAL: &str = "/dav/calendars/user/personal/"; +pub const TASKS: &str = "/dav/calendars/user/tasks/"; + +#[derive(Default)] +pub struct State { + pub objects: BTreeMap, // path -> (etag, body) + pub rev: u64, + log: Vec<(u64, String, bool)>, // rev, path, deleted + pub support_sync: bool, + pub requests: Vec, + pub puts: Vec<(String, Option)>, // path, if-match +} + +#[derive(Clone)] +pub struct Mock { + pub state: Arc>, + pub base: String, +} + +impl Mock { + pub async fn start() -> Mock { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", l.local_addr().unwrap()); + let state = Arc::new(Mutex::new(State { + support_sync: true, + ..Default::default() + })); + let st = state.clone(); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = l.accept().await else { + break; + }; + let st = st.clone(); + tokio::spawn(async move { + if let Some(req) = read_request(&mut sock).await { + let resp = handle(&st, req); + let _ = sock.write_all(resp.as_bytes()).await; + let _ = sock.shutdown().await; + } + }); + } + }); + Mock { state, base } + } + + /// Server-side write (as another client would do). Returns the new etag. + pub fn set(&self, path: &str, body: &str) -> String { + let mut s = self.state.lock().unwrap(); + put(&mut s, path, body) + } + + pub fn remove(&self, path: &str) { + let mut s = self.state.lock().unwrap(); + s.objects.remove(path); + s.rev += 1; + let r = s.rev; + s.log.push((r, path.to_string(), true)); + } + + pub fn body(&self, path: &str) -> Option { + self.state + .lock() + .unwrap() + .objects + .get(path) + .map(|o| o.1.clone()) + } + + pub fn paths(&self, dir: &str) -> Vec { + self.state + .lock() + .unwrap() + .objects + .keys() + .filter(|p| p.starts_with(dir)) + .cloned() + .collect() + } + + pub fn disable_sync_collection(&self) { + self.state.lock().unwrap().support_sync = false; + } + + pub fn count_requests(&self, needle: &str) -> usize { + self.state + .lock() + .unwrap() + .requests + .iter() + .filter(|r| r.contains(needle)) + .count() + } +} + +fn put(s: &mut State, path: &str, body: &str) -> String { + s.rev += 1; + let etag = format!("\"e{}\"", s.rev); + s.objects + .insert(path.to_string(), (etag.clone(), body.to_string())); + let r = s.rev; + s.log.push((r, path.to_string(), false)); + etag +} + +struct Req { + method: String, + path: String, + headers: BTreeMap, + body: String, +} + +async fn read_request(sock: &mut tokio::net::TcpStream) -> Option { + let mut buf = Vec::new(); + let mut tmp = [0u8; 4096]; + let head_end = loop { + let n = sock.read(&mut tmp).await.ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&tmp[..n]); + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break i + 4; + } + }; + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let mut lines = head.lines(); + let first = lines.next()?; + let mut parts = first.split_whitespace(); + let (method, path) = (parts.next()?.to_string(), parts.next()?.to_string()); + let headers: BTreeMap = lines + .filter_map(|l| { + l.split_once(':') + .map(|(k, v)| (k.trim().to_lowercase(), v.trim().to_string())) + }) + .collect(); + let len: usize = headers + .get("content-length") + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + while buf.len() < head_end + len { + let n = sock.read(&mut tmp).await.ok()?; + if n == 0 { + break; + } + buf.extend_from_slice(&tmp[..n]); + } + let body = String::from_utf8_lossy(&buf[head_end..]).to_string(); + Some(Req { + method, + path, + headers, + body, + }) +} + +fn http(status: &str, headers: &[(&str, String)], body: &str) -> String { + let mut s = format!( + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n", + body.len() + ); + for (k, v) in headers { + s.push_str(&format!("{k}: {v}\r\n")); + } + s.push_str("\r\n"); + s.push_str(body); + s +} + +fn xml_escape(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +fn multistatus(inner: &str) -> String { + let body = format!( + r#"{inner}"# + ); + http( + "207 Multi-Status", + &[("Content-Type", "application/xml".into())], + &body, + ) +} + +fn prop_response(href: &str, props: &str) -> String { + format!( + "{href}{props}HTTP/1.1 200 OK" + ) +} + +fn ctag(s: &State, dir: &str) -> String { + // Per-collection ctag: highest revision touching the collection. + let r = s + .log + .iter() + .filter(|(_, p, _)| p.starts_with(dir)) + .map(|(r, _, _)| *r) + .max() + .unwrap_or(0); + format!("ctag-{r}") +} + +fn calendar_props(s: &State, dir: &str, name: &str, comps: &[&str]) -> String { + let comps: String = comps + .iter() + .map(|c| format!(r#""#)) + .collect(); + format!( + "{name}{comps}{}", + ctag(s, dir) + ) +} + +fn hrefs_in(body: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = body; + while let Some(i) = rest.find("") { + let after = &rest[i + 8..]; + let Some(j) = after.find("") else { + break; + }; + out.push(after[..j].replace("&", "&")); + rest = &after[j..]; + } + out +} + +fn handle(st: &Arc>, req: Req) -> String { + let mut s = st.lock().unwrap(); + s.requests.push(format!("{} {}", req.method, req.path)); + if !req + .headers + .get("authorization") + .is_some_and(|a| a.starts_with("Basic ")) + { + return http( + "401 Unauthorized", + &[("WWW-Authenticate", "Basic realm=\"mock\"".into())], + "", + ); + } + let (m, p, b) = (req.method.as_str(), req.path.as_str(), req.body.as_str()); + match (m, p) { + ("PROPFIND", "/.well-known/caldav") => { + http("301 Moved Permanently", &[("Location", "/dav/".into())], "") + } + ("PROPFIND", "/dav/") => multistatus(&prop_response( + "/dav/", + "/dav/principals/user/", + )), + ("PROPFIND", "/dav/principals/user/") => multistatus(&prop_response( + p, + &format!("{HOME}"), + )), + ("PROPFIND", HOME) => { + let mut inner = prop_response(HOME, ""); + inner += &prop_response( + PERSONAL, + &calendar_props(&s, PERSONAL, "Personal", &["VEVENT", "VTODO"]), + ); + inner += &prop_response(TASKS, &calendar_props(&s, TASKS, "Tasks", &["VTODO"])); + multistatus(&inner) + } + ("PROPFIND", cal) if cal == PERSONAL || cal == TASKS => { + if b.contains("getctag") { + multistatus(&prop_response( + cal, + &format!("{}", ctag(&s, cal)), + )) + } else { + let mut inner = + prop_response(cal, ""); + for (path, (etag, _)) in s.objects.iter().filter(|(k, _)| k.starts_with(cal)) { + inner += &prop_response( + path, + &format!("{}", xml_escape(etag)), + ); + } + multistatus(&inner) + } + } + ("REPORT", cal) if b.contains("sync-collection") => { + if !s.support_sync { + return http("501 Not Implemented", &[], ""); + } + let since: u64 = b + .split("") + .nth(1) + .and_then(|t| t.split("").next()) + .and_then(|t| t.strip_prefix("tok-")) + .and_then(|t| t.parse().ok()) + .unwrap_or(0); + let mut latest: BTreeMap<&String, bool> = BTreeMap::new(); + for (r, path, deleted) in &s.log { + if *r > since && path.starts_with(cal) { + latest.insert(path, *deleted); + } + } + let mut inner = String::new(); + for (path, deleted) in latest { + if deleted { + inner += &format!( + "{path}HTTP/1.1 404 Not Found" + ); + } else if let Some((etag, _)) = s.objects.get(path) { + inner += &prop_response( + path, + &format!("{}", xml_escape(etag)), + ); + } + } + inner += &format!("tok-{}", s.rev); + multistatus(&inner) + } + ("REPORT", _) if b.contains("calendar-multiget") => { + let mut inner = String::new(); + for h in hrefs_in(b) { + if let Some((etag, body)) = s.objects.get(&h) { + inner += &prop_response( + &h, + &format!( + "{}{}", + xml_escape(etag), + xml_escape(body) + ), + ); + } + } + multistatus(&inner) + } + ("GET", path) => match s.objects.get(path) { + Some((etag, body)) => http( + "200 OK", + &[ + ("ETag", etag.clone()), + ("Content-Type", "text/calendar".into()), + ], + body, + ), + None => http("404 Not Found", &[], ""), + }, + ("PUT", path) => { + let if_match = req.headers.get("if-match").cloned(); + s.puts.push((path.to_string(), if_match.clone())); + let current = s.objects.get(path).map(|o| o.0.clone()); + let ok = match ( + &if_match, + req.headers.get("if-none-match").map(String::as_str), + ¤t, + ) { + (Some(m), _, Some(c)) => m == c, + (Some(_), _, None) => false, + (None, Some("*"), Some(_)) => false, + _ => true, + }; + if !ok { + return http("412 Precondition Failed", &[], ""); + } + let etag = put(&mut s, path, b); + http( + if current.is_some() { + "204 No Content" + } else { + "201 Created" + }, + &[("ETag", etag)], + "", + ) + } + ("DELETE", path) => { + if let (Some(m), Some((c, _))) = (req.headers.get("if-match"), s.objects.get(path)) + && m != c + { + return http("412 Precondition Failed", &[], ""); + } + if s.objects.remove(path).is_some() { + s.rev += 1; + let r = s.rev; + s.log.push((r, path.to_string(), true)); + http("204 No Content", &[], "") + } else { + http("404 Not Found", &[], "") + } + } + _ => http("404 Not Found", &[], ""), + } +} diff --git a/crates/synapse-caldav/tests/sync.rs b/crates/synapse-caldav/tests/sync.rs new file mode 100644 index 0000000..d6f0590 --- /dev/null +++ b/crates/synapse-caldav/tests/sync.rs @@ -0,0 +1,367 @@ +mod mock; + +use chrono::NaiveDate; +use chrono_tz::Europe::Madrid; +use mock::{HOME, Mock, PERSONAL, TASKS}; +use synapse_caldav::{ + Config, Credentials, DavClient, events_for_day, materialize_day, refresh_calendars, sync, +}; +use synapse_core::{Graph, Placement}; + +fn day(y: i32, m: u32, d: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, d).unwrap() +} + +fn ms(y: i32, m: u32, d: u32, h: u32) -> i64 { + day(y, m, d) + .and_hms_opt(h, 0, 0) + .unwrap() + .and_utc() + .timestamp_millis() +} + +fn client(m: &Mock) -> DavClient { + DavClient::new( + &m.base, + Credentials { + username: "u".into(), + password: "app-pw".into(), + }, + ) + .unwrap() +} + +fn graph() -> (tempfile::TempDir, Graph) { + let dir = tempfile::tempdir().unwrap(); + let g = Graph::open(dir.path()).unwrap(); + g.set_now(Some(ms(2026, 10, 21, 9))); + (dir, g) +} + +fn vtodo(uid: &str, body: &str) -> String { + format!( + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Other//EN\r\nBEGIN:VTODO\r\nUID:{uid}\r\n{body}END:VTODO\r\nEND:VCALENDAR\r\n" + ) +} + +fn page_blocks(g: &Graph, title: &str) -> Vec<(usize, synapse_core::Block)> { + let p = g.page_by_title(title).unwrap().unwrap(); + g.page_tree(p.id).unwrap() +} + +const STANDUP: &str = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:standup\r\nSUMMARY:Standup\r\nDTSTART;TZID=Europe/Madrid:20261007T100000\r\nDTEND;TZID=Europe/Madrid:20261007T103000\r\nRRULE:FREQ=WEEKLY;BYDAY=WE\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:dentist\r\nSUMMARY:Dentist\r\nDTSTART;TZID=Europe/Madrid:20261021T170000\r\nDURATION:PT45M\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + +#[tokio::test] +async fn discovery_and_calendar_listing() { + let m = Mock::start().await; + let (_d, g) = graph(); + let c = client(&m); + let cals = refresh_calendars(&g, &c).await.unwrap(); + assert_eq!(cals.len(), 2); + let tasks = cals.iter().find(|c| c.href == TASKS).unwrap(); + assert!(tasks.supports_tasks && !tasks.supports_events); + let personal = cals.iter().find(|c| c.href == PERSONAL).unwrap(); + assert!(personal.supports_events && personal.supports_tasks); + assert!(m.count_requests("PROPFIND /.well-known/caldav") >= 1); + assert_eq!(c.discover().await.unwrap(), HOME); +} + +#[tokio::test] +async fn events_recurrence_and_journal_materialisation() { + let m = Mock::start().await; + m.set(&format!("{PERSONAL}standup.ics"), STANDUP); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let rep = sync(&g, &client(&m), &cfg).await.unwrap(); + assert_eq!(rep.events_changed, 1); + + // 2026-10-21 is a Wednesday: the weekly standup and the dentist. + let evs = events_for_day(&g, day(2026, 10, 21), Madrid).unwrap(); + let names: Vec<_> = evs.iter().map(|e| e.summary.as_str()).collect(); + assert_eq!(names, ["Standup", "Dentist"]); + assert!(evs[0].recurring && !evs[1].recurring); + assert_eq!(evs[1].end - evs[1].start, chrono::Duration::minutes(45)); + assert!( + events_for_day(&g, day(2026, 10, 22), Madrid) + .unwrap() + .is_empty() + ); + assert_eq!( + events_for_day(&g, day(2026, 10, 28), Madrid).unwrap().len(), + 1 + ); + + let ids = materialize_day(&g, day(2026, 10, 21), Madrid).unwrap(); + assert_eq!(ids.len(), 2); + let j = g.journal(day(2026, 10, 21)).unwrap(); + let tree = g.page_tree(j.id).unwrap(); + assert_eq!(tree[0].1.content, "10:00-10:30 [[Standup]]"); + assert_eq!(tree[1].1.content, "17:00-17:45 Dentist"); + // The recurring meeting got its own page (via the [[link]]), the one-off did not. + assert!(g.page_by_title("Standup").unwrap().is_some()); + assert!(g.page_by_title("Dentist").unwrap().is_none()); + // Idempotent. + assert_eq!(materialize_day(&g, day(2026, 10, 21), Madrid).unwrap(), ids); + assert_eq!(g.page_tree(j.id).unwrap().len(), 2); + + // Dentist cancelled remotely: the next sync + materialise removes its block only. + m.remove(&format!("{PERSONAL}standup.ics")); + m.set( + &format!("{PERSONAL}standup.ics"), + &STANDUP.replace("UID:dentist", "UID:dentist\r\nSTATUS:CANCELLED"), + ); + sync(&g, &client(&m), &cfg).await.unwrap(); + materialize_day(&g, day(2026, 10, 21), Madrid).unwrap(); + let tree = g.page_tree(j.id).unwrap(); + assert_eq!(tree.len(), 1); + assert_eq!(tree[0].1.content, "10:00-10:30 [[Standup]]"); +} + +#[tokio::test] +async fn task_round_trip_both_directions() { + let m = Mock::start().await; + let path = format!("{TASKS}milk.ics"); + m.set(&path, &vtodo("milk", "SUMMARY:Buy milk\r\nPRIORITY:1\r\nDUE;VALUE=DATE:20261025\r\nX-KEEP:me\r\nLAST-MODIFIED:20261020T080000Z\r\n")); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + + // Remote -> local. + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.tasks_pulled, 1); + let blocks = page_blocks(&g, "Tasks"); + assert_eq!(blocks.len(), 1); + let b = &blocks[0].1; + assert_eq!(b.content, "TODO [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>"); + assert_eq!(b.properties["caldav-uid"], "milk"); + assert_eq!(b.properties["caldav-calendar"], TASKS); + + // Local completion -> remote. + g.set_now(Some(ms(2026, 10, 21, 10))); + g.update_block(b.id, "DONE [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>") + .unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.tasks_updated_remote, 1); + let remote = m.body(&path).unwrap(); + assert!( + remote.contains("STATUS:COMPLETED") && remote.contains("PERCENT-COMPLETE:100"), + "{remote}" + ); + assert!(remote.contains("COMPLETED:20261021T100000Z"), "{remote}"); + assert!( + remote.contains("X-KEEP:me"), + "unknown properties survive: {remote}" + ); + // The PUT was conditional on the etag we had. + assert!( + m.state + .lock() + .unwrap() + .puts + .iter() + .any(|(p, im)| p == &path && im.is_some()) + ); + // No echo: another sync changes nothing. + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!((rep.tasks_updated_remote, rep.conflicts), (0, 0)); + + // Remote reopens it as in-process -> local DOING. + let reopened = remote + .replace("STATUS:COMPLETED", "STATUS:IN-PROCESS") + .replace("PERCENT-COMPLETE:100", "PERCENT-COMPLETE:30") + .replace("COMPLETED:20261021T100000Z\r\n", ""); + m.set(&path, &reopened); + sync(&g, &c, &cfg).await.unwrap(); + let b = g.get_block(b.id).unwrap().unwrap(); + assert_eq!(b.content, "DOING [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>"); +} + +#[tokio::test] +async fn new_journal_task_goes_to_default_list_and_completes_remotely() { + let m = Mock::start().await; + m.set(&format!("{PERSONAL}standup.ics"), STANDUP); // gives the account an events-only-ish calendar + let (_d, g) = graph(); + let mut cfg = Config::new(Madrid); + cfg.default_task_calendar = Some(TASKS.into()); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); // establishes "enabled_at" + + let j = g.today_journal().unwrap(); + let plain = g + .insert_block(j.id, Placement::LastChildOf(None), "just a note") + .unwrap(); + let t = g + .insert_block( + j.id, + Placement::LastChildOf(None), + "LATER [#B] Call the bank\nSCHEDULED: <2026-10-22 Thu 09:30>", + ) + .unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.tasks_created_remote, 1); + let paths = m.paths(TASKS); + assert_eq!(paths.len(), 1); + let body = m.body(&paths[0]).unwrap(); + assert!( + body.contains("SUMMARY:Call the bank") && body.contains("PRIORITY:5"), + "{body}" + ); + assert!( + body.contains("DTSTART;TZID=Europe/Madrid:20261022T093000"), + "{body}" + ); + assert!( + g.get_block(plain.id) + .unwrap() + .unwrap() + .properties + .is_empty() + ); + let t = g.get_block(t.id).unwrap().unwrap(); + assert!(t.properties.contains_key("caldav-uid")); + assert_eq!( + t.content, "LATER [#B] Call the bank\nSCHEDULED: <2026-10-22 Thu 09:30>", + "content untouched" + ); + + // Completed in another app -> DONE here; LATER spelling kept only for open states. + m.set( + &paths[0], + &body.replace("STATUS:NEEDS-ACTION", "STATUS:COMPLETED"), + ); + sync(&g, &c, &cfg).await.unwrap(); + let t = g.get_block(t.id).unwrap().unwrap(); + assert!( + t.content.starts_with("DONE [#B] Call the bank"), + "{}", + t.content + ); +} + +#[tokio::test] +async fn conflict_last_modified_wins_and_loser_kept_as_child() { + let m = Mock::start().await; + let path = format!("{TASKS}t.ics"); + m.set( + &path, + &vtodo( + "t", + "SUMMARY:Plan trip\r\nLAST-MODIFIED:20261021T080000Z\r\n", + ), + ); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); + let b = page_blocks(&g, "Tasks")[0].1.clone(); + + // Case 1: remote edited later (11:00) than the local edit (10:00): remote wins. + g.set_now(Some(ms(2026, 10, 21, 10))); + g.update_block(b.id, "TODO Plan trip to Rome").unwrap(); + m.set( + &path, + &vtodo( + "t", + "SUMMARY:Plan trip to Paris\r\nLAST-MODIFIED:20261021T110000Z\r\n", + ), + ); + g.set_now(Some(ms(2026, 10, 21, 12))); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.conflicts, 1); + let tree = page_blocks(&g, "Tasks"); + assert_eq!(tree[0].1.content, "TODO Plan trip to Paris"); + assert_eq!(tree[1].0, 1); + assert!(tree[1].1.content.contains("local") && tree[1].1.content.contains("Plan trip to Rome")); + + // Case 2: local edited later (14:00) than the remote (13:00): local wins and is pushed. + m.set( + &path, + &vtodo( + "t", + "SUMMARY:Plan trip to Oslo\r\nLAST-MODIFIED:20261021T130000Z\r\n", + ), + ); + g.set_now(Some(ms(2026, 10, 21, 14))); + g.update_block(b.id, "TODO Plan trip to Lima").unwrap(); + g.set_now(Some(ms(2026, 10, 21, 15))); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.conflicts, 1); + assert_eq!( + g.get_block(b.id).unwrap().unwrap().content, + "TODO Plan trip to Lima" + ); + assert!(m.body(&path).unwrap().contains("SUMMARY:Plan trip to Lima")); + let tree = page_blocks(&g, "Tasks"); + assert!( + tree.iter() + .any(|(d, x)| *d == 1 && x.content.contains("remote") && x.content.contains("Oslo")) + ); +} + +#[tokio::test] +async fn stale_etag_on_push_refetches_and_retries() { + let m = Mock::start().await; + let path = format!("{TASKS}r.ics"); + m.set( + &path, + &vtodo("r", "SUMMARY:Race\r\nLAST-MODIFIED:20261021T080000Z\r\n"), + ); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); + let b = page_blocks(&g, "Tasks")[0].1.clone(); + g.set_now(Some(ms(2026, 10, 21, 10))); + g.update_block(b.id, "TODO Race local").unwrap(); + // Our cached etag is out of date although the pull sees no change since its token. + g.conn() + .execute("UPDATE caldav_object SET etag='\"stale\"'", []) + .unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.conflicts, 1); + assert_eq!(rep.tasks_updated_remote, 1); + assert!(m.body(&path).unwrap().contains("SUMMARY:Race local")); + let puts = m.state.lock().unwrap().puts.clone(); + assert_eq!( + puts.len(), + 2, + "first PUT rejected with 412, second accepted: {puts:?}" + ); +} + +#[tokio::test] +async fn deletions_both_ways_and_ctag_fallback() { + let m = Mock::start().await; + m.disable_sync_collection(); + m.set(&format!("{TASKS}a.ics"), &vtodo("a", "SUMMARY:Alpha\r\n")); + m.set(&format!("{TASKS}b.ics"), &vtodo("b", "SUMMARY:Beta\r\n")); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(page_blocks(&g, "Tasks").len(), 2); + assert_eq!( + m.count_requests("REPORT"), + 3, + "two refused sync-collections + one multiget" + ); + + // Unchanged ctag: the second sync lists nothing. + let before = m.count_requests("depth"); + sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(m.count_requests("depth"), before); + + // Remote delete of Alpha -> block gone; local delete of Beta -> remote gone. + m.remove(&format!("{TASKS}a.ics")); + let beta = page_blocks(&g, "Tasks") + .into_iter() + .find(|(_, b)| b.content.contains("Beta")) + .unwrap() + .1; + g.delete_block(beta.id).unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.removed_remote, 1); + assert_eq!(rep.tasks_deleted_remote, 1); + assert!(page_blocks(&g, "Tasks").is_empty()); + assert!(m.paths(TASKS).is_empty()); +} diff --git a/docs/caldav.md b/docs/caldav.md new file mode 100644 index 0000000..d569cb6 --- /dev/null +++ b/docs/caldav.md @@ -0,0 +1,65 @@ +# CalDAV (`synapse-caldav`) + +Two-way sync of CalDAV calendars (VEVENT) and task lists (VTODO) with a Synapse graph. + +## Usage +```rust +let client = DavClient::new("https://cloud.example.com", Credentials { username, password })?; +let cfg = Config::new(chrono_tz::Europe::Madrid); // viewer zone; optional default task list +let report = synapse_caldav::sync(&graph, &client, &cfg).await?; // pull, then push +let events = events_for_day(&graph, date, cfg.tz)?; // from the local cache +materialize_day(&graph, date, cfg.tz)?; // optional: events as journal blocks +``` +Credentials (use an app password on Nextcloud) are passed by the caller and never stored. +The futures hold `&Graph` across awaits and are therefore not `Send`: run them with `block_on` +on a dedicated thread. + +## Protocol +Discovery: `/.well-known/caldav` → `current-user-principal` → `calendar-home-set`. Changes come +from `sync-collection` (RFC 6578); servers without it (or rejecting the token) fall back to +ctag + etag listing. Changed objects are fetched with `calendar-multiget`; writes are `PUT` +with `If-Match` (or `If-None-Match: *` for creation) and `DELETE` with `If-Match`. TLS is +rustls with the bundled webpki roots (self-signed servers are not supported yet). + +## Mapping +| Logseq block | VTODO | +|---|---| +| `TODO`/`LATER` | `STATUS:NEEDS-ACTION` | +| `DOING`/`NOW` | `IN-PROCESS` | +| `DONE` | `COMPLETED` + `PERCENT-COMPLETE:100` + `COMPLETED` | +| `CANCELED` | `CANCELLED` | +| `[#A]`/`[#B]`/`[#C]` | `PRIORITY` 1/5/9 (read back: 1–4 A, 5 B, 6–9 C) | +| `SCHEDULED: <2026-10-21 Wed [14:00]>` | `DTSTART` (date, or zoned time in `Config::tz`) | +| `DEADLINE: <…>` | `DUE` | +| other lines | `DESCRIPTION` | + +Block properties: `caldav-uid::`, `caldav-calendar::` (list href). Unknown VTODO properties are +preserved on write-back (the last server copy is cached and edited in place). Remote tasks with +no block yet are created on a page named after the task list. + +New tasks: a block in a **journal** that starts with a marker (not `DONE`/`CANCELED`), has no +`caldav-uid`, and was edited after the first sync is created in the default task list +(`Config::default_task_calendar`, else the first list supporting VTODO). Older journals are +never scanned, so imported history is not uploaded. + +## Events +Events live only in the cache (`caldav_object.ics`). `events_for_day` / `events_between` expand +`RRULE`/`EXDATE`/`RECURRENCE-ID` overrides, convert zones (`TZID`, UTC, floating, all-day) to the +viewer zone and skip `CANCELLED`. `materialize_day` writes `10:00-10:30 [[Standup]]` blocks in +that day's journal (property `caldav-event`); recurring meetings link to a page named after +the summary. It is idempotent, refreshes unedited blocks and removes blocks of vanished events. +Event blocks are not pushed back. + +## Conflicts +If a task changed on both sides since the last sync, the newer one wins (remote +`LAST-MODIFIED`/`DTSTAMP` vs block `updated_at`); the loser is kept as a child block +(`CalDAV conflict: … version (older, kept as note)`). A 412 on push triggers a re-fetch, the same +resolution and one retry. Delete vs edit: the edit wins (the block is detached and re-pushed). + +## Tables (graph DB) +`caldav_meta`, `caldav_calendar` (ctag, sync token), `caldav_object` (href, uid, etag, last +server ICS, block id, last synced content), `caldav_event_block`. + +## Not done yet +Pushing event edits, RRULE-aware completion of recurring tasks (the whole VTODO is completed), +custom CA certificates, multiple accounts, VALARM, attendees.