Compare commits

..

235 Commits

Author SHA1 Message Date
Lennart K
c763a682ed update .gitignore 2026-01-27 23:07:19 +01:00
Lennart K
8ab9c61b0f Move commands to lib.rs 2026-01-27 23:06:57 +01:00
Lennart
8b2bb1b0d6 docs: Mention NixOS package 2026-01-26 12:20:04 +01:00
Lennart
da72aa26cb update README.md 2026-01-24 22:53:51 +01:00
Lennart
b89ff1a2b5 version 0.12.3 2026-01-24 22:49:02 +01:00
Lennart
246a1aa738 Add truncation for automatically derived timezones 2026-01-24 22:48:08 +01:00
Lennart
bb0484ac4a version 0.12.2 2026-01-24 20:09:42 +01:00
Lennart
1b3da2a99b update caldata-rs 2026-01-24 20:07:38 +01:00
Lennart
3b01ae1cf6 update test snapshots 2026-01-24 19:52:13 +01:00
Lennart K
d918a255a9 PUT calendar_object: Allow omission of timezones as in RFC7809 2026-01-24 19:44:58 +01:00
Lennart K
6a31d3000c Update vtimezones-rs 2026-01-24 18:05:42 +01:00
Lennart K
d5892ab56b Migrate ical-rs to caldata-rs 2026-01-22 11:01:00 +01:00
Lennart K
11a61cf8b1 version 0.12.1 2026-01-20 13:20:04 +01:00
Lennart Kämmle
227d4bc61a Merge pull request #171 from wrvsrx/fix-anniversayr-typo
Fix a typo about anniversary
2026-01-20 13:17:44 +01:00
wrvsrx
d9afc85222 Fix a typo about anniversary 2026-01-20 19:45:50 +08:00
Lennart
c9fe5706a9 clippy appeasement 2026-01-19 17:03:14 +01:00
Lennart
1b6214d426 MKCALENDAR: Handling of invalid timezones 2026-01-19 16:36:25 +01:00
Lennart
be34cc3091 xml: Implement namespace for Unparsed 2026-01-19 16:22:21 +01:00
Lennart
99287f85f4 version 0.12.0 2026-01-19 15:48:56 +01:00
Lennart
df3143cd4c Fix status code for failed preconditions 2026-01-19 15:37:41 +01:00
Lennart Kämmle
92a3418f8e Merge pull request #164 from lennart-k/feat/ical-rewrite
ical-rs overhaul
2026-01-19 15:14:14 +01:00
Lennart
ea2f841269 ical-rs: Pin version to Git commit 2026-01-19 15:04:54 +01:00
Lennart
15e1509fe3 sqlite_store: Add option to skip broken objects and add validation on start-up 2026-01-19 14:48:21 +01:00
Lennart
0eef4ffabf Add test for uploading invalid calendar object and fix precondition 2026-01-19 13:40:54 +01:00
Lennart
303f9aff68 Remove IcalError from caldav/carddav since it had an ambiguous status code 2026-01-19 12:51:51 +01:00
Lennart
3460a2821e dav: Check Host matching for MV,COPY 2026-01-19 12:37:35 +01:00
Lennart
f73658b32f Re-enable calendar-query test and fix calendar expansion 2026-01-19 12:09:34 +01:00
Lennart K
7e099bcd6e Merge branch 'main' into feat/ical-rewrite 2026-01-16 16:47:17 +01:00
Lennart K
dde05d2f45 Workflow: Publish container images for feature branches too 2026-01-16 16:29:38 +01:00
Lennart K
4adf1818d4 Merge branch 'main' into feat/ical-rewrite 2026-01-16 15:58:17 +01:00
Lennart K
f503bf2bf7 Update quick-xml 2026-01-16 15:47:10 +01:00
Lennart K
7c15976a1a rebase main 2026-01-16 15:41:39 +01:00
Lennart K
669d81aea0 address_object resource: Implement displayname 2026-01-16 15:39:56 +01:00
Lennart K
967d18de95 Fix comp-filter 2026-01-16 15:39:55 +01:00
Lennart K
63373ad525 simplify handling of ical-related errors 2026-01-16 15:39:54 +01:00
Lennart K
2c67890343 Update ical-rs 2026-01-16 15:39:53 +01:00
Lennart K
5ec2787ecf build MVP for birthday calendar 2026-01-16 15:39:53 +01:00
Lennart K
7eecd95757 Remove calendar-query integration test for now 2026-01-16 15:39:52 +01:00
Lennart K
c165e761be update ical-rs 2026-01-16 15:39:51 +01:00
Lennart K
5f68a5ae5c Re-add get_last_occurence for sqlite store 2026-01-16 15:39:50 +01:00
Lennart K
c77b59dcb0 Remove unused code 2026-01-16 15:39:49 +01:00
Lennart K
276fdcacf5 Re-implement calendar imports 2026-01-16 15:39:48 +01:00
Lennart K
43fff63008 Calendar export: Fix PRODID 2026-01-16 15:39:47 +01:00
Lennart K
977fd75500 Re-implement calendar export 2026-01-16 15:39:46 +01:00
Lennart K
5639127782 clean up ical-related stuff 2026-01-16 15:39:44 +01:00
Lennart K
a2255bc7f1 make calendar object id extrinsic 2026-01-16 15:39:34 +01:00
Lennart K
758793a11a Make AddressObject object_id an extrinsic property 2026-01-16 15:39:33 +01:00
Lennart K
a9f3833a32 small fixes 2026-01-16 15:39:30 +01:00
Lennart K
896e934c0a Decrease folder nesting 2026-01-16 15:39:01 +01:00
Lennart K
bb880aa403 incorporate get_first_occurenec 2026-01-16 15:39:00 +01:00
Lennart K
69acde10ba migrate to new ical-rs version 2026-01-16 15:38:57 +01:00
Lennart K
d84158e8ad version 0.11.17 2026-01-16 12:26:43 +01:00
Lennart K
7ef566040a Disable a test that will be fixed in 0.12 2026-01-16 12:16:02 +01:00
Lennart K
1c1f0c6da2 Update ical-rs@dev to fix cargo vendor 2026-01-16 12:10:10 +01:00
Lennart
3fafbd22f4 version 0.11.16 2026-01-15 23:43:00 +01:00
Lennart
e68dc921e6 Now actually fix builds 2026-01-15 23:19:35 +01:00
Lennart
60b45e70ad fix docker builds 2026-01-15 22:31:40 +01:00
Lennart
a0c33c82dd version 0.11.14 2026-01-15 13:32:45 +01:00
Lennart
8ae5e46abf Automatic repair for calendar objects with invalid VERSION:4.0 2026-01-15 13:30:14 +01:00
Lennart
48b2e614a8 Suppress ical invalid version error 2026-01-15 11:15:20 +01:00
Lennart K
f26214abb9 build Docker images for dev branch 2026-01-12 11:15:08 +01:00
Lennart
276e65d41a version 0.11.11 2026-01-10 13:37:24 +01:00
Lennart
7c3e9ecbc1 update ical-rs dev to remove panics 2026-01-10 13:35:14 +01:00
Lennart
53f81a9433 Add a startup test to check whether existing data will be compatible with v0.12 2026-01-10 13:22:49 +01:00
Lennart
55eabfde4a version 0.11.10 2026-01-04 00:06:43 +01:00
Lennart
5d9d6e3fdf update snapshots 2026-01-04 00:06:16 +01:00
Lennart
1567bc64ef addressbook-query: Fix filter matching for empty filters 2026-01-04 00:05:07 +01:00
Lennart
44ae995f29 Some small fixes on recurrence expansion 2025-12-31 19:54:06 +01:00
Lennart
9c1cd24d32 test data fix uid 2025-12-31 19:47:29 +01:00
Lennart
ff0c5697cf caldav expand: accept <prop> 2025-12-31 19:47:13 +01:00
Lennart
6ccb5a67e4 ical: Respect that calendar do not have to contain a main event 2025-12-31 17:55:58 +01:00
Lennart
da718dd290 caldav: Add import test case from RFC Appendix B 2025-12-31 17:55:30 +01:00
Lennart
4112347e24 more integration tests 2025-12-31 17:36:02 +01:00
Lennart
f4fd1cdd21 caldav max-resource-size: Fix namespace 2025-12-31 17:35:51 +01:00
Lennart
5f0ca67e54 docs: Add document to track progress of CardDAV support 2025-12-31 17:00:14 +01:00
Lennart
3aef9abe48 carddav: Add more integration tests 2025-12-31 16:50:55 +01:00
Lennart
9784f2b53f PUT object: Properly check If-None-Match header 2025-12-31 16:50:32 +01:00
Lennart
271fdfd686 PUT object: Return ETag 2025-12-31 16:17:34 +01:00
Lennart
4fabf74333 version 0.11.9 2025-12-31 15:58:49 +01:00
Lennart
7b154adec3 remove stray dbg! 2025-12-31 15:57:56 +01:00
Lennart
951a1e4bdc update mkdocs.yml 2025-12-31 15:57:23 +01:00
Lennart
8c44733d0a carddav: Fix namespace for max-resource-size 2025-12-31 15:57:13 +01:00
Lennart
829f7b727f carddav calendar-query: Add parsing support for limit 2025-12-31 15:15:07 +01:00
Lennart
037e6f5c92 version 0.11.8 2025-12-31 14:57:54 +01:00
Lennart
311ceb6bc5 Update README.md 2025-12-31 14:56:39 +01:00
Lennart
1174af3a4b carddav: Add some tests to make sure the filters work 2025-12-31 14:47:23 +01:00
Lennart
845b3e61e3 carddav: Fix filter test="allof"|"anyof" 2025-12-31 14:46:49 +01:00
Lennart
e5d6541ffb fix prop-filter when multiple properties of a name exist 2025-12-31 13:46:43 +01:00
Lennart
b632ff6fe8 update dependencies 2025-12-31 13:31:17 +01:00
Lennart
1ee873ac93 caldav: Add basic filtering test 2025-12-31 13:31:07 +01:00
Lennart
bf5bdb96bc implement param-filter for caldav 2025-12-31 13:07:43 +01:00
Lennart
47c2a55941 implement text-match and prop-filter for carddav 2025-12-31 13:02:53 +01:00
Lennart
bfcd94f096 update test snapshot 2025-12-31 12:35:57 +01:00
Lennart
8cbb72719d fix text-match test 2025-12-31 12:31:09 +01:00
Lennart
ff0246c4fc clippy appeasement 2025-12-31 12:29:19 +01:00
Lennart
15124a2fd5 clippy appeasement 2025-12-31 12:25:59 +01:00
Lennart
5c6f63a5f3 carddav addressbook: Add supported-collation-set 2025-12-31 12:25:35 +01:00
Lennart
17ba8faef2 text-match: Support match types and unicode-casemap collation 2025-12-31 12:25:04 +01:00
Lennart
578ddde36d ResourceName trait: Use Cow instead of String 2025-12-31 10:57:28 +01:00
Lennart
9c3972e21c fix addressbook import test 2025-12-31 01:59:19 +01:00
Lennart
816c26565a clippy appeasement 2025-12-31 01:56:16 +01:00
Lennart
4de0f9f665 add basic addressbook import test 2025-12-31 01:55:49 +01:00
Lennart
cf31a51965 small changes to regression tests and xml namespaces 2025-12-31 01:43:03 +01:00
Lennart
9fc099f6f4 fix carddav integration tests 2025-12-31 01:30:35 +01:00
Lennart
498be172c9 clippy appeasement 2025-12-31 01:23:48 +01:00
Lennart
b8c395e746 add basic integration test for carddav addressbook 2025-12-31 01:23:21 +01:00
Lennart
4b8a8c61f2 Tests: Fix scope of store 2025-12-31 01:05:56 +01:00
Lennart
f778c470d0 update GitHub workflows 2025-12-30 19:16:59 +01:00
Lennart
d44a172261 bump Rust version to 1.92 2025-12-30 19:10:05 +01:00
Lennart
e0ba34baea clippy appeasement 2025-12-30 19:08:58 +01:00
Lennart
a7893ddbda Replace deprecated axum Host extractor with Host header 2025-12-30 13:53:42 +01:00
Lennart
ed7becffc2 update askama to 0.15 2025-12-28 21:02:44 +01:00
Lennart
c29400a799 version 0.11.7 2025-12-28 19:27:27 +01:00
Lennart
047552a726 update dependencies 2025-12-28 19:24:00 +01:00
Lennart K
1cfc8e7c23 frontend: Update dependencies 2025-12-27 15:07:06 +01:00
Lennart
b0fdca1b64 clippy appeasement 2025-12-27 14:30:36 +01:00
Lennart
b65cca9d17 version 0.11.6 2025-12-27 14:23:56 +01:00
Lennart
55ecbdcd41 carddav: Implement addressbook-query 2025-12-27 14:22:23 +01:00
Lennart
89d3d3b7a4 caldav: Outsource text-match to rustical_dav 2025-12-27 13:45:26 +01:00
Lennart K
a74b74369c version 0.11.5 2025-12-21 16:16:48 +01:00
Lennart K
85c49a0bdf update ical-rs 2025-12-20 14:30:26 +01:00
Lennart K
f2e4e2c1a7 add a database benchmark 2025-12-20 11:48:30 +01:00
Lennart K
28c925301e calendar store: Add method for bulk insert 2025-12-20 11:48:05 +01:00
Lennart K
b50ea478db Content-Type: Add charset=utf-8 2025-12-18 21:43:27 +01:00
Lennart K
2c7748255c update test snapshot 2025-12-18 21:40:39 +01:00
Lennart K
f40a23a1f1 update Cargo.toml and fix calendar export ical version 2025-12-18 21:39:36 +01:00
Lennart K
2a4ba33e45 refactor recurrence expansion 2025-12-18 21:27:40 +01:00
Lennart K
6bc4bd3fa3 Update ical-rs dependency 2025-12-18 14:14:26 +01:00
Lennart
7b32d478b8 version 0.11.4 2025-12-17 17:35:11 +01:00
Lennart
fb0bd67176 Update ical-rs version to fix bug with unicode characters in params
addresses #157
2025-12-17 17:33:46 +01:00
Lennart
ecad0d4490 frontend: update vite 2025-12-15 20:44:50 +01:00
Lennart
e702e77656 version 0.11.3 2025-12-15 12:02:59 +01:00
Lennart Kämmle
141f881382 Merge pull request #154 from quantenzitrone/nonlegacy-ip
src/config.rs: bind to legacy and nonlegacy ip addresses by default
2025-12-15 12:02:16 +01:00
quantenzitrone
b8d2ac0654 src/config.rs: bind to legacy and nonlegacy ip addresses by default
see https://github.com/tokio-rs/axum/discussions/834#discussioncomment-2302918
2025-12-15 07:14:00 +01:00
Lennart
16aae73cd1 integration tests: Fix snapshot naming 2025-12-13 00:20:36 +01:00
Lennart
120d45eb0a caldav: Add proppatch test 2025-12-12 23:56:29 +01:00
Lennart
0bdfb786ff clippy appeasement 2025-12-12 23:47:10 +01:00
Lennart
d9cca5a298 improve caldav integration test 2025-12-12 23:43:14 +01:00
Lennart
50a74e3a25 fix integration tests 2025-12-12 14:46:10 +01:00
Lennart
ed8a9e718a more integration tests 2025-12-12 14:35:47 +01:00
Lennart
38b5a3812e add integration tests 2025-12-12 14:12:09 +01:00
Lennart
d3e7ede93c frontend: Merge components into single bundle 2025-12-12 13:00:44 +01:00
Lennart
4e90f725e0 update dependencies 2025-12-12 11:47:15 +01:00
Lennart
ef40f5ea8c version 0.11.2 2025-12-11 20:34:34 +01:00
Lennart
1230e29243 frontend: tiny improvement to import forms 2025-12-11 20:17:04 +01:00
Lennart
1b2296c00a clippy appeasement 2025-12-11 20:16:44 +01:00
Lennart
ac6ab0ca9a clippy appeasement 2025-12-11 20:01:04 +01:00
Lennart
6312f52b10 update license information 2025-12-11 19:59:20 +01:00
Lennart
ec28cb9d9a frontend: improve calendar creation form and fix data binding bugs 2025-12-11 19:52:48 +01:00
Lennart
4b4210b4d7 Add initial test for app initialisation 2025-12-10 14:43:06 +01:00
Lennart
8fadff1b57 fix insta snapshots 2025-12-10 14:30:18 +01:00
Lennart
61a8c32af4 add some more propfind regression tests 2025-12-10 14:22:04 +01:00
Lennart
a45e0b2efd carddav: Try out some tests with insta 2025-12-10 12:26:31 +01:00
Lennart
eecc03b7b7 caldav: add debug to principal resource 2025-12-10 12:25:59 +01:00
Lennart
e8303b9c82 main: slight refactoring 2025-12-10 12:25:13 +01:00
Lennart
a686286d06 sqlite_store: Refactor notification logic 2025-12-10 10:44:41 +01:00
Lennart
d81074de3b version 0.11.1 2025-12-05 20:32:17 +01:00
Lennart
42386adcfa frontend: remove debug statement from template 2025-12-05 20:31:58 +01:00
Lennart
d2f5f7c89b version 0.11.0 2025-12-05 15:06:01 +01:00
Lennart Kämmle
15e431ce12 Merge pull request #138 from lennart-k/feature/birthday-calendar
Feature/birthday calendar
2025-12-05 15:03:56 +01:00
Lennart
96a16951f4 sqlx prepare 2025-12-05 14:55:30 +01:00
Lennart
a32b766c0c Merge branch 'main' into feature/birthday-calendar 2025-12-05 14:51:51 +01:00
Lennart
7a101b7364 frontend: Fix cursor for anchors 2025-12-05 14:51:34 +01:00
Lennart
57275a10b4 Add birthday calendar creation to frontend 2025-12-05 14:50:02 +01:00
Lennart
af239e34bf birthday calendar store: Support manual birthday calendar creation 2025-12-05 14:49:09 +01:00
Lennart
e99b1d9123 calendar resource: Remove prop write guards 2025-12-05 14:48:35 +01:00
Lennart
e39657eb29 PROPPATCH: Fix privileges 2025-12-05 14:48:11 +01:00
Lennart
607db62859 Merge branch 'main' into feature/birthday-calendar 2025-12-05 11:47:42 +01:00
Lennart
eba377b980 update dependencies 2025-12-05 11:47:11 +01:00
Lennart
d5c1ddc590 caldav: Update test_propfind regression test 2025-11-22 18:49:32 +01:00
Lennart
a79e1901b8 test_propfind: Revert assert_eq order 2025-11-22 18:48:36 +01:00
Lennart
f29c8fa925 Merge branch 'main' into feature/birthday-calendar 2025-11-22 18:46:59 +01:00
Lennart
54f1ee0788 use similar-asserts for regression tests 2025-11-22 18:46:47 +01:00
Lennart
96f221f721 birthday_calendar: Refactor insert_birthday_calendar 2025-11-22 18:35:26 +01:00
Lennart
ba3b64a9c4 Merge branch 'main' into feature/birthday-calendar 2025-11-22 18:30:44 +01:00
Lennart
22a0337375 version 0.10.5 2025-11-17 19:14:17 +01:00
Lennart
21902e108a fix some error messages 2025-11-17 19:13:13 +01:00
Lennart
08f526fa5b Add startup routine to fix orphaned objects
fixes #145, related to #142
2025-11-17 19:11:30 +01:00
Lennart
ac73f3aaff addressbook_store: Commit import addressbooks to changelog 2025-11-17 18:35:10 +01:00
Lennart
9fdc8434db calendar import: log added events 2025-11-17 18:22:33 +01:00
Lennart
85f3d89235 version 0.10.4 2025-11-17 01:21:55 +01:00
Lennart
092604694a multiget: percent-decode hrefs 2025-11-17 01:21:20 +01:00
Lennart
8ef24668ba version 0.10.3 2025-11-14 11:02:27 +01:00
Lennart
416658d069 frontend: Fix missing getTimezones import in create-calendar-form
fixes #141
2025-11-14 11:01:59 +01:00
Lennart
80eae5db9e version 0.10.2 2025-11-09 21:39:09 +01:00
Lennart
66f541f1c7 Drop log level for 404 to info
fixes #139
2025-11-09 21:36:17 +01:00
Lennart
ea7196501e docs: Add verification for Google Search Console (not analytics) 2025-11-06 00:19:33 +01:00
Lennart
33d14a9ba0 sqlite_store: Add some more basic tests 2025-11-05 23:17:59 +01:00
Lennart
d843909084 Update Cargo.toml 2025-11-05 16:16:01 +01:00
Lennart
873b40ad10 stylesheet: Add flex-wrap to actions 2025-11-05 16:05:55 +01:00
Lennart
5588137f73 sqlx prepare 2025-11-04 17:01:54 +01:00
Lennart
7bf00da0e5 implement deleting and restoring birthday calendars 2025-11-04 16:56:17 +01:00
Lennart
be08275cd3 Merge branch 'main' into feature/birthday-calendar 2025-11-04 16:28:08 +01:00
Lennart
3a10a695f5 frontend: Only show logout button when logged in 2025-11-04 15:33:13 +01:00
Lennart
53c6e3b1f4 frontend: Update calendar,addressbook pages 2025-11-04 15:32:00 +01:00
Lennart
6838e8e379 frontend: update stylesheet 2025-11-04 15:31:35 +01:00
Lennart
9f28aaec41 frontend: Update deno dependencies 2025-11-04 15:31:18 +01:00
Lennart
381af1b877 run .sqlx prepare 2025-11-03 15:37:40 +01:00
Lennart
7ec62bc6ab attempt to fix docs build 2025-11-02 22:57:29 +01:00
Lennart
9538b68e77 version 0.10.1 2025-11-02 22:21:25 +01:00
Lennart
ea5175387b update licenses 2025-11-02 22:21:16 +01:00
Lennart
0095491a20 frontend: dumb test for timezones 2025-11-02 22:17:23 +01:00
Lennart
e9392cc00b frontend: Add dropdown for timezone selection 2025-11-02 22:08:28 +01:00
Lennart
425d10cb99 CalendarStore::is_read_only now refers to its content only and not its metadata 2025-11-02 21:07:06 +01:00
Lennart
5cdbb3b9d3 migrate birthday store to sqlite 2025-11-02 21:06:43 +01:00
Lennart
547e477eca make sure a birthday calendar will be created for each addressbook 2025-11-02 21:05:31 +01:00
Lennart
c19c3492c3 frontend: Remove birthday calendar guard 2025-11-02 20:45:58 +01:00
Lennart
5878b93d62 add birthday_calendar table migrations 2025-11-02 20:45:31 +01:00
Lennart
888591c952 add test case for converting filter to calendar query 2025-11-02 19:17:59 +01:00
Lennart
de77223170 Merge pull request #137 from lennart-k/feature/comp-filter
Re-implement comp-filter for calendar-query
2025-11-02 18:56:56 +01:00
Lennart
c42f8e5614 clippy appeasement 2025-11-02 18:42:55 +01:00
Lennart
f72559d027 caldav: Add supported-collation-set property 2025-11-02 18:33:54 +01:00
Lennart
167492318f xml: serialize: Support non-string text fields 2025-11-02 18:33:30 +01:00
Lennart
32f43951ac refactor text-match to support collations 2025-11-02 17:48:35 +01:00
Lennart
cd9993cd97 implement comp-filter matching for VTIMEZONE 2025-11-02 17:21:44 +01:00
Lennart
9f911fe5d7 prop-filter: Add time-range checking 2025-11-02 15:09:31 +01:00
Lennart
6361907152 re-implement comp-filter and add property filtering 2025-11-02 15:00:53 +01:00
Lennart
0c0be859f9 calendar object: Move occurence methods to CalendarObjectComponent and add get_property method 2025-11-02 15:00:13 +01:00
Lennart
d2c786eba6 merge main into feature/comp-filter 2025-11-02 13:10:56 +01:00
Lennart
dabddc6282 version 0.10.0 2025-11-01 21:49:44 +01:00
Lennart
76b4194b94 lift restriction on object_id and UID having to match
addresses #135
2025-11-01 21:48:37 +01:00
Lennart
db144ebcae calendarobject: Rename get_id to get_uid 2025-11-01 21:23:55 +01:00
Lennart
a53c333f1f version 0.9.14 2025-11-01 15:10:06 +01:00
Lennart
a05baea472 sqlite_store: Mark write transactions with BEGIN IMMEDIATE
Hopefully addresses SQLITE_BUSY error, see #131
2025-11-01 15:09:42 +01:00
Lennart
f34f7e420e Dockerfile: Update Rust to 1.91 2025-11-01 15:08:36 +01:00
Lennart
24ab323aa0 clippy appeasement 2025-11-01 14:21:44 +01:00
Lennart
f34f56ca89 update dependencies 2025-11-01 14:17:13 +01:00
Lennart
8c2025b674 version 0.9.13 2025-10-27 21:14:31 +01:00
Lennart
77d8f5dacc add ping endpoint and healthcheck command 2025-10-27 21:12:43 +01:00
Lennart
5d142289b3 tokio: Use multi-threaded runtime 2025-10-27 20:34:20 +01:00
Lennart
255282893a update matchit 2025-10-27 20:15:38 +01:00
Lennart
86cf490fa9 Lots of clippy appeasement 2025-10-27 20:12:21 +01:00
Lennart K
0d071d3b92 run clippy fix 2025-10-27 19:01:04 +01:00
Lennart
8ed4db5824 work on new comp-filter implementation 2025-10-27 18:59:00 +01:00
Lennart K
08041c60be clippy: Enable more warnings 2025-10-27 11:39:24 +01:00
288 changed files with 13146 additions and 8070 deletions

View File

@@ -5,6 +5,7 @@ permissions:
pull-requests: write
env:
RUST_VERSION: "1.92"
CARGO_TERM_COLOR: always
jobs:
@@ -12,7 +13,9 @@ jobs:
name: Check
runs-on: ubuntu-latest
steps:
- run: rustup update
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: ${{ env.RUST_VERSION }}
- name: Checkout sources
uses: actions/checkout@v4
- run: cargo check
@@ -21,7 +24,9 @@ jobs:
name: Test Suite
runs-on: ubuntu-latest
steps:
- run: rustup update
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: ${{ env.RUST_VERSION }}
- name: Checkout sources
uses: actions/checkout@v4
- run: cargo test --all-features --verbose --workspace
@@ -30,7 +35,9 @@ jobs:
name: Test Coverage
runs-on: ubuntu-latest
steps:
- run: rustup update
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: ${{ env.RUST_VERSION }}
- name: Install tarpaulin
run: cargo install cargo-tarpaulin
@@ -44,8 +51,10 @@ jobs:
name: Lints
runs-on: ubuntu-latest
steps:
- run: rustup update
- run: rustup component add rustfmt clippy
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: ${{ env.RUST_VERSION }}
components: rustfmt, clippy
- name: Checkout sources
uses: actions/checkout@v4

View File

@@ -2,7 +2,10 @@ name: Docker
on:
push:
branches: ["main"]
branches:
- main
- dev
- feat/*
release:
types: ["published"]
@@ -26,12 +29,12 @@ jobs:
# https://github.com/docker/setup-buildx-action
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0
uses: docker/setup-buildx-action@v3
# https://github.com/docker/login-action
- name: Log into registry ${{ env.REGISTRY }}
if: github.event_name != 'pull_request'
uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -45,7 +48,8 @@ jobs:
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
${{ github.ref_name == 'main' && 'type=ref,event=branch' || '' }}
type=ref,event=branch,prefix=br-
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
@@ -54,7 +58,7 @@ jobs:
# https://github.com/docker/build-push-action
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
uses: docker/build-push-action@v5
with:
context: .
platforms: linux/arm64,linux/amd64

View File

@@ -17,6 +17,8 @@ jobs:
with:
python-version: 3.x
- run: rustup update
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
- name: Set up build cache

4
.gitignore vendored
View File

@@ -3,7 +3,7 @@ crates/*/target
# For libraries ignore Cargo.lock
crates/*/Cargo.lock
db.sqlite3*
**/*.sqlite3*
config.toml
principals.toml
@@ -16,3 +16,5 @@ site
# Frontend
**/node_modules
**/.vite
**/*.snap.new

View File

@@ -0,0 +1,38 @@
{
"db_name": "SQLite",
"query": "\n SELECT principal, cal_id, id, (deleted_at IS NOT NULL) AS \"deleted: bool\"\n FROM calendarobjects\n WHERE (principal, cal_id, id) NOT IN (\n SELECT DISTINCT principal, cal_id, object_id FROM calendarobjectchangelog\n )\n ;\n ",
"describe": {
"columns": [
{
"name": "principal",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "cal_id",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "id",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "deleted: bool",
"ordinal": 3,
"type_info": "Integer"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "053c17f3b54ae3e153137926115486eb19a801bd73a74230bcf72a9a7254824a"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM calendarobjectchangelog WHERE (principal, cal_id, object_id) = (?, ?, ?);",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "146e23ae4e0eaae4d65ac7563c67d4f295ccc2534dcc4b3bd710de773ed137f9"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE calendarobjects SET ics = ? WHERE (principal, cal_id, id) = (?, ?, ?);",
"describe": {
"columns": [],
"parameters": {
"Right": 4
},
"nullable": []
},
"hash": "354decac84758c88280f60fbf0f93dddc6c7ff92ac7b8ba44049d31df3c680e3"
}

View File

@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT id, uid, ics FROM calendarobjects\n WHERE principal = ? AND cal_id = ? AND deleted_at IS NULL\n AND (last_occurence IS NULL OR ? IS NULL OR last_occurence >= date(?))\n AND (first_occurence IS NULL OR ? IS NULL OR first_occurence <= date(?))\n ",
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "uid",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "ics",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 6
},
"nullable": [
false,
false,
false
]
},
"hash": "3a29efff3d3f6e1e05595d1a2d095af5fc963572c90bd10a6616af78757f8c39"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "REPLACE INTO calendarobjects (principal, cal_id, id, ics, first_occurence, last_occurence, etag, object_type) VALUES (?, ?, ?, ?, date(?), date(?), ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 8
},
"nullable": []
},
"hash": "3e1cca532372e891ab3e604ecb79311d8cd64108d4f238db4c79e9467a3b6d2e"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE birthday_calendars SET principal = ?, id = ?, displayname = ?, description = ?, \"order\" = ?, color = ?, timezone_id = ?, push_topic = ?\n WHERE (principal, id) = (?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 10
},
"nullable": []
},
"hash": "4a05eda4e23e8652312548b179a1cc16f43768074ab9e7ab7b7783395384984e"
}

View File

@@ -1,6 +1,6 @@
{
"db_name": "SQLite",
"query": "SELECT id, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
"query": "SELECT id, uid, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
"describe": {
"columns": [
{
@@ -9,18 +9,24 @@
"type_info": "Text"
},
{
"name": "ics",
"name": "uid",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "ics",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 4
},
"nullable": [
false,
false,
false
]
},
"hash": "543838c030550cb09d1af08adfeade8b7ce3575d92fddbc6e9582d141bc9e49d"
"hash": "505ebe8e64ac709b230dce7150240965e45442aca6c5f3b3115738ef508939ed"
}

View File

@@ -0,0 +1,74 @@
{
"db_name": "SQLite",
"query": "SELECT principal, id, displayname, description, \"order\", color, timezone_id, deleted_at, addr_synctoken, push_topic\n FROM birthday_calendars\n INNER JOIN (\n SELECT principal AS addr_principal,\n id AS addr_id,\n synctoken AS addr_synctoken\n FROM addressbooks\n ) ON (principal, id) = (addr_principal, addr_id)\n WHERE (principal, id) = (?, ?)\n AND ((deleted_at IS NULL) OR ?)\n ",
"describe": {
"columns": [
{
"name": "principal",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "id",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "displayname",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "description",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "order",
"ordinal": 4,
"type_info": "Integer"
},
{
"name": "color",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "timezone_id",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "deleted_at",
"ordinal": 7,
"type_info": "Datetime"
},
{
"name": "addr_synctoken",
"ordinal": 8,
"type_info": "Integer"
},
{
"name": "push_topic",
"ordinal": 9,
"type_info": "Text"
}
],
"parameters": {
"Right": 3
},
"nullable": [
false,
false,
true,
true,
false,
true,
true,
true,
false,
false
]
},
"hash": "525fc4eab8a0f3eacff7e3c78ce809943f817abf8c8f9ae50073924bccdea2dc"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "REPLACE INTO davpush_subscriptions (id, topic, expiration, push_resource, public_key, public_key_type, auth_secret) VALUES (?, ?, ?, ?, ?, ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 7
},
"nullable": []
},
"hash": "583069cbeba5285c63c2b95e989669d3faed66a75fbfc7cd93e5f64b778f45ab"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "INSERT INTO calendarobjects (principal, cal_id, id, ics, first_occurence, last_occurence, etag, object_type) VALUES (?, ?, ?, ?, date(?), date(?), ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 8
},
"nullable": []
},
"hash": "6327bee90e5df01536a0ddb15adcc37af3027f6902aa3786365c5ab2fbf06bda"
}

View File

@@ -0,0 +1,74 @@
{
"db_name": "SQLite",
"query": "SELECT principal, id, displayname, description, \"order\", color, timezone_id, deleted_at, addr_synctoken, push_topic\n FROM birthday_calendars\n INNER JOIN (\n SELECT principal AS addr_principal,\n id AS addr_id,\n synctoken AS addr_synctoken\n FROM addressbooks\n ) ON (principal, id) = (addr_principal, addr_id)\n WHERE principal = ?\n AND (\n (deleted_at IS NULL AND NOT ?) -- not deleted, want not deleted\n OR (deleted_at IS NOT NULL AND ?) -- deleted, want deleted\n )\n ",
"describe": {
"columns": [
{
"name": "principal",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "id",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "displayname",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "description",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "order",
"ordinal": 4,
"type_info": "Integer"
},
{
"name": "color",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "timezone_id",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "deleted_at",
"ordinal": 7,
"type_info": "Datetime"
},
{
"name": "addr_synctoken",
"ordinal": 8,
"type_info": "Integer"
},
{
"name": "push_topic",
"ordinal": 9,
"type_info": "Text"
}
],
"parameters": {
"Right": 3
},
"nullable": [
false,
false,
true,
true,
false,
true,
true,
true,
false,
false
]
},
"hash": "66d57f2c99ef37b383a478aff99110e1efbc7ce9332f10da4fa69f7594fb7455"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE birthday_calendars SET deleted_at = NULL WHERE (principal, id) = (?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "6c039308ad2ec29570ab492d7a0e85fb79c0a4d3b882b74ff1c2786c12324896"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "INSERT OR REPLACE INTO davpush_subscriptions (id, topic, expiration, push_resource, public_key, public_key_type, auth_secret) VALUES (?, ?, ?, ?, ?, ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 7
},
"nullable": []
},
"hash": "6d08d3a014743da9b445ab012437ec11f81fd86d3b02fc1df07a036c6b47ace2"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO birthday_calendars (principal, id, displayname, description, \"order\", color, push_topic)\n VALUES (?, ?, ?, ?, ?, ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 7
},
"nullable": []
},
"hash": "72c7c67f4952ad669ecd54d96bbcb717815081f74575f0a65987163faf9fe30a"
}

View File

@@ -1,6 +1,6 @@
{
"db_name": "SQLite",
"query": "SELECT id, ics FROM calendarobjects WHERE principal = ? AND cal_id = ? AND deleted_at IS NULL",
"query": "SELECT id, uid, ics FROM calendarobjects WHERE principal = ? AND cal_id = ? AND deleted_at IS NULL",
"describe": {
"columns": [
{
@@ -9,18 +9,24 @@
"type_info": "Text"
},
{
"name": "ics",
"name": "uid",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "ics",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 2
},
"nullable": [
false,
false,
false
]
},
"hash": "54c9c0e36a52e6963f11c6aa27f13aafb4204b8aa34b664fd825bd447db80e86"
"hash": "804ed2a4a7032e9605d1871297498f5a96de0fc816ce660c705fb28318be0d42"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE birthday_calendars SET deleted_at = datetime() WHERE (principal, id) = (?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "83f0aaf406785e323ac12019ac24f603c53125a1b2326f324c1e2d7b6c690adc"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "REPLACE INTO calendarobjects (principal, cal_id, id, uid, ics, first_occurence, last_occurence, etag, object_type) VALUES (?, ?, ?, ?, ?, date(?), date(?), ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 9
},
"nullable": []
},
"hash": "a68a1b96189b854a7ba2a3cd866ba583af5ad84bc1cd8b20cb805e9ce3bad820"
}

View File

@@ -0,0 +1,38 @@
{
"db_name": "SQLite",
"query": "SELECT principal, cal_id, id, ics FROM calendarobjects WHERE ics LIKE '%VERSION:4.0%';",
"describe": {
"columns": [
{
"name": "principal",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "cal_id",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "id",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "ics",
"ordinal": 3,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "bdaa4bee8b01d0e3773e34672ed4805d1e71d24888f2227045afd90bf080fc23"
}

View File

@@ -0,0 +1,38 @@
{
"db_name": "SQLite",
"query": "\n SELECT principal, addressbook_id, id, (deleted_at IS NOT NULL) AS \"deleted: bool\"\n FROM addressobjects\n WHERE (principal, addressbook_id, id) NOT IN (\n SELECT DISTINCT principal, addressbook_id, object_id FROM addressobjectchangelog\n )\n ;\n ",
"describe": {
"columns": [
{
"name": "principal",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "addressbook_id",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "id",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "deleted: bool",
"ordinal": 3,
"type_info": "Integer"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "c138b1143ac04af4930266ffae0990e82005911c11a683ad565e92335e085f4d"
}

View File

@@ -1,26 +0,0 @@
{
"db_name": "SQLite",
"query": "SELECT id, ics FROM calendarobjects\n WHERE principal = ? AND cal_id = ? AND deleted_at IS NULL\n AND (last_occurence IS NULL OR ? IS NULL OR last_occurence >= date(?))\n AND (first_occurence IS NULL OR ? IS NULL OR first_occurence <= date(?))\n ",
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "ics",
"ordinal": 1,
"type_info": "Text"
}
],
"parameters": {
"Right": 6
},
"nullable": [
false,
false
]
},
"hash": "c550dbf3d5ce7069f28d767ea9045e477ef8d29d6186851760757a06dec42339"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM birthday_calendars WHERE (principal, id) = (?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "cadc4ac16b7ac22b71c91ab36ad9dbb1dec943798d795fcbc811f4c651fea02a"
}

View File

@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO calendarobjects (principal, cal_id, id, uid, ics, first_occurence, last_occurence, etag, object_type) VALUES (?, ?, ?, ?, ?, date(?), date(?), ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 9
},
"nullable": []
},
"hash": "d498a758ed707408b00b7d2675250ea739a681ce1f009f05e97f2e101bd7e556"
}

1547
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,8 @@
members = ["crates/*"]
[workspace.package]
version = "0.9.12"
version = "0.12.3"
rust-version = "1.92"
edition = "2024"
description = "A CalDAV server"
documentation = "https://lennart-k.github.io/rustical/"
@@ -12,6 +13,7 @@ license = "AGPL-3.0-or-later"
[package]
name = "rustical"
version.workspace = true
rust-version.workspace = true
edition.workspace = true
description.workspace = true
repository.workspace = true
@@ -30,13 +32,29 @@ opentelemetry = [
"dep:tracing-opentelemetry",
]
[profile.dev]
debug = 0
[lib]
doc = true
name = "rustical"
path = "src/lib.rs"
test = true
[workspace.dependencies]
matchit = "0.8"
uuid = { version = "1.11", features = ["v4", "fast-rng"] }
rustical_dav = { path = "./crates/dav/", features = ["ical"] }
rustical_dav_push = { path = "./crates/dav_push/" }
rustical_store = { path = "./crates/store/" }
rustical_store_sqlite = { path = "./crates/store_sqlite/" }
rustical_caldav = { path = "./crates/caldav/" }
rustical_carddav = { path = "./crates/carddav/" }
rustical_frontend = { path = "./crates/frontend/" }
rustical_xml = { path = "./crates/xml/" }
rustical_oidc = { path = "./crates/oidc/" }
rustical_ical = { path = "./crates/ical/" }
matchit = "0.9"
uuid = { version = "1.19", features = ["v4", "fast-rng"] }
async-trait = "0.1"
axum = "0.8"
tracing = { version = "0.1", features = ["async-await"] }
@@ -47,12 +65,11 @@ password-auth = { version = "1.0", features = ["argon2", "pbkdf2"] }
pbkdf2 = { version = "0.12", features = ["simple"] }
rand_core = { version = "0.9", features = ["std"] }
chrono = { version = "0.4", features = ["serde"] }
regex = "1.10"
lazy_static = "1.5"
regex = "1.12"
rstest = "0.26"
rstest_reuse = "0.7"
sha2 = "0.10"
tokio = { version = "1", features = [
tokio = { version = "1.48", features = [
"net",
"tracing",
"macros",
@@ -62,15 +79,15 @@ tokio = { version = "1", features = [
url = "2.5"
base64 = "0.22"
thiserror = "2.0"
quick-xml = { version = "0.38" }
rust-embed = "8.5"
quick-xml = { version = "0.39" }
rust-embed = "8.9"
tower-sessions = "0.14"
futures-core = "0.3.31"
hex = { version = "0.4.3", features = ["serde"] }
futures-core = "0.3"
hex = { version = "0.4", features = ["serde"] }
mime_guess = "2.0"
itertools = "0.14"
log = "0.4"
derive_more = { version = "2.0", features = [
derive_more = { version = "2.1", features = [
"from",
"try_into",
"into",
@@ -78,8 +95,8 @@ derive_more = { version = "2.0", features = [
"constructor",
"display",
] }
askama = { version = "0.14", features = ["serde_json"] }
askama_web = { version = "0.14.0", features = ["axum-0.8"] }
askama = { version = "0.15", features = ["serde_json"] }
askama_web = { version = "0.15", features = ["axum-0.8"] }
sqlx = { version = "0.8", default-features = false, features = [
"sqlx-sqlite",
"uuid",
@@ -90,17 +107,13 @@ sqlx = { version = "0.8", default-features = false, features = [
"migrate",
"json",
] }
http = "1.3"
http = "1.4"
headers = "0.4"
strum = "0.27"
strum_macros = "0.27"
serde_json = { version = "1.0", features = ["raw_value"] }
sqlx-sqlite = { version = "0.8", features = ["bundled"] }
ical = { git = "https://github.com/lennart-k/ical-rs", features = [
"generator",
"serde",
"chrono-tz",
] }
caldata = { version = "0.14.0", features = ["chrono-tz", "vtimezones-rs"] }
toml = "0.9"
tower = "0.5"
tower-http = { version = "0.6", features = [
@@ -109,29 +122,19 @@ tower-http = { version = "0.6", features = [
"catch-panic",
] }
percent-encoding = "2.3"
rustical_dav = { path = "./crates/dav/" }
rustical_dav_push = { path = "./crates/dav_push/" }
rustical_store = { path = "./crates/store/" }
rustical_store_sqlite = { path = "./crates/store_sqlite/" }
rustical_caldav = { path = "./crates/caldav/" }
rustical_carddav = { path = "./crates/carddav/" }
rustical_frontend = { path = "./crates/frontend/" }
rustical_xml = { path = "./crates/xml/" }
rustical_oidc = { path = "./crates/oidc/" }
rustical_ical = { path = "./crates/ical/" }
chrono-tz = "0.10"
chrono-humanize = "0.2"
rand = "0.9"
axum-extra = { version = "0.10", features = ["typed-header"] }
axum-extra = { version = "0.12", features = ["typed-header"] }
rrule = "0.14"
argon2 = "0.5"
rpassword = "7.3"
rpassword = "7.4"
password-hash = { version = "0.5" }
syn = { version = "2.0", features = ["full"] }
quote = "1.0"
proc-macro2 = "1.0"
heck = "0.5"
darling = "0.21"
darling = "0.23"
reqwest = { version = "0.12", features = [
"rustls-tls",
"charset",
@@ -139,28 +142,38 @@ reqwest = { version = "0.12", features = [
], default-features = false }
openidconnect = "4.0"
clap = { version = "4.5", features = ["derive", "env"] }
matchit-serde = { git = "https://github.com/lennart-k/matchit-serde", rev = "f0591d13" }
vtimezones-rs = "0.2"
matchit-serde = { git = "https://github.com/lennart-k/matchit-serde", rev = "e18e65d7" }
vtimezones-rs = "0.3"
ece = { version = "2.3", default-features = false, features = [
"backend-openssl",
] }
openssl = { version = "0.10", features = ["vendored"] }
async-std = { version = "1.13", features = ["attributes"] }
similar-asserts = "1.7"
insta = { version = "1.44", features = ["filters"] }
criterion = { version = "0.8", features = ["async_tokio"] }
[dev-dependencies]
rstest.workspace = true
rustical_store_sqlite = { workspace = true, features = ["test"] }
insta.workspace = true
similar-asserts.workspace = true
[dependencies]
rustical_store = { workspace = true }
rustical_store_sqlite = { workspace = true }
rustical_caldav = { workspace = true }
rustical_store.workspace = true
rustical_store_sqlite.workspace = true
rustical_caldav.workspace = true
rustical_carddav.workspace = true
rustical_frontend = { workspace = true }
toml = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
anyhow = { workspace = true }
rustical_frontend.workspace = true
caldata.workspace = true
toml.workspace = true
serde.workspace = true
tokio.workspace = true
tracing.workspace = true
anyhow.workspace = true
clap.workspace = true
sqlx = { workspace = true }
async-trait = { workspace = true }
sqlx.workspace = true
async-trait.workspace = true
uuid.workspace = true
axum.workspace = true

View File

@@ -1,4 +1,4 @@
FROM --platform=$BUILDPLATFORM rust:1.90-alpine AS chef
FROM --platform=$BUILDPLATFORM rust:1.92-alpine AS chef
ARG TARGETPLATFORM
ARG BUILDPLATFORM
@@ -36,7 +36,7 @@ COPY --from=planner /rustical/recipe.json recipe.json
RUN cargo chef cook --release --target "$(cat /tmp/rust_target)"
COPY . .
RUN cargo install --target "$(cat /tmp/rust_target)" --path .
RUN cargo install --locked --target "$(cat /tmp/rust_target)" --path .
FROM scratch
COPY --from=builder /usr/local/cargo/bin/rustical /usr/local/bin/rustical
@@ -47,3 +47,5 @@ ENV RUSTICAL_DATA_STORE__SQLITE__DB_URL=/var/lib/rustical/db.sqlite3
LABEL org.opencontainers.image.authors="Lennart K github.com/lennart-k"
LABEL org.opencontainers.image.licenses="AGPL-3.0-or-later"
EXPOSE 4000
HEALTHCHECK --interval=30s --timeout=30s --start-period=3s --retries=3 CMD ["/usr/local/bin/rustical", "health"]

View File

@@ -1,3 +1,6 @@
[![license](https://img.shields.io/github/license/lennart-k/rustical)](https://raw.githubusercontent.com/lennart-k/rustical/main/LICENSE)
[![Coverage Status](https://coveralls.io/repos/github/lennart-k/rustical/badge.svg?branch=main)](https://coveralls.io/github/lennart-k/rustical?branch=main)
# RustiCal
a CalDAV/CardDAV server
@@ -21,6 +24,7 @@ a CalDAV/CardDAV server
- Apple configuration profiles (skip copy-pasting passwords and instead generate the configuration in the frontend)
- **OpenID Connect** support (with option to disable password login)
- Group-based **sharing**
- Partial [RFC 7809](https://datatracker.ietf.org/doc/html/rfc7809) support. RustiCal will accept timezones by reference and handle omitted timezones in objects.
## Getting Started

View File

@@ -9,5 +9,7 @@ accepted = [
"AGPL-3.0",
"GPL-3.0",
"MPL-2.0",
"AGPL-3.0-or-later",
"GPL-3.0-or-later",
]
workarounds = ["ring", "chrono", "rustls"]

View File

@@ -1,6 +1,7 @@
[package]
name = "rustical_caldav"
version.workspace = true
rust-version.workspace = true
edition.workspace = true
description.workspace = true
repository.workspace = true
@@ -12,27 +13,28 @@ rustical_store_sqlite = { workspace = true, features = ["test"] }
rstest.workspace = true
async-std.workspace = true
serde_json.workspace = true
insta.workspace = true
[dependencies]
axum.workspace = true
axum-extra.workspace = true
tower.workspace = true
async-trait = { workspace = true }
thiserror = { workspace = true }
quick-xml = { workspace = true }
tracing = { workspace = true }
futures-util = { workspace = true }
derive_more = { workspace = true }
base64 = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true }
url = { workspace = true }
rustical_dav = { workspace = true }
rustical_store = { workspace = true }
chrono = { workspace = true }
chrono-tz = { workspace = true }
sha2 = { workspace = true }
ical.workspace = true
async-trait.workspace = true
thiserror.workspace = true
quick-xml.workspace = true
tracing.workspace = true
futures-util.workspace = true
derive_more.workspace = true
base64.workspace = true
serde.workspace = true
tokio.workspace = true
url.workspace = true
rustical_dav = { workspace = true, features = ["ical"] }
rustical_store.workspace = true
chrono.workspace = true
chrono-tz.workspace = true
sha2.workspace = true
caldata.workspace = true
percent-encoding.workspace = true
rustical_xml.workspace = true
uuid.workspace = true
@@ -44,3 +46,4 @@ tower-http.workspace = true
strum.workspace = true
strum_macros.workspace = true
vtimezones-rs.workspace = true
similar-asserts.workspace = true

View File

@@ -3,14 +3,13 @@ use crate::calendar::CalendarResourceService;
use axum::body::Body;
use axum::extract::State;
use axum::{extract::Path, response::Response};
use caldata::component::IcalCalendar;
use caldata::generator::Emitter;
use caldata::parser::ContentLine;
use headers::{ContentType, HeaderMapExt};
use http::{HeaderValue, Method, StatusCode, header};
use ical::generator::{Emitter, IcalCalendarBuilder};
use ical::property::Property;
use percent_encoding::{CONTROLS, utf8_percent_encode};
use rustical_ical::{CalendarObjectComponent, EventObject};
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
use std::collections::HashMap;
use std::str::FromStr;
use tracing::instrument;
@@ -32,79 +31,49 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
return Err(crate::Error::Unauthorized);
}
let mut timezones = HashMap::new();
let mut vtimezones = HashMap::new();
let objects = cal_store.get_objects(&principal, &calendar_id).await?;
let objects = cal_store
.get_objects(&principal, &calendar_id)
.await?
.into_iter()
.map(|(_, object)| object.into())
.collect();
let mut props = vec![];
let mut ical_calendar_builder = IcalCalendarBuilder::version("4.0")
.gregorian()
.prodid("RustiCal");
if let Some(displayname) = calendar.meta.displayname {
ical_calendar_builder = ical_calendar_builder.set(Property {
props.push(ContentLine {
name: "X-WR-CALNAME".to_owned(),
value: Some(displayname),
params: None,
params: vec![].into(),
});
}
if let Some(description) = calendar.meta.description {
ical_calendar_builder = ical_calendar_builder.set(Property {
props.push(ContentLine {
name: "X-WR-CALDESC".to_owned(),
value: Some(description),
params: None,
params: vec![].into(),
});
}
if let Some(color) = calendar.meta.color {
props.push(ContentLine {
name: "X-WR-CALCOLOR".to_owned(),
value: Some(color),
params: vec![].into(),
});
}
if let Some(timezone_id) = calendar.timezone_id {
ical_calendar_builder = ical_calendar_builder.set(Property {
props.push(ContentLine {
name: "X-WR-TIMEZONE".to_owned(),
value: Some(timezone_id),
params: None,
params: vec![].into(),
});
}
for object in &objects {
vtimezones.extend(object.get_vtimezones());
match object.get_data() {
CalendarObjectComponent::Event(
EventObject {
event,
timezones: object_timezones,
..
},
overrides,
) => {
timezones.extend(object_timezones);
ical_calendar_builder = ical_calendar_builder.add_event(event.clone());
for _override in overrides {
ical_calendar_builder =
ical_calendar_builder.add_event(_override.event.clone());
}
}
CalendarObjectComponent::Todo(todo, overrides) => {
ical_calendar_builder = ical_calendar_builder.add_todo(todo.clone());
for _override in overrides {
ical_calendar_builder = ical_calendar_builder.add_todo(_override.clone());
}
}
CalendarObjectComponent::Journal(journal, overrides) => {
ical_calendar_builder = ical_calendar_builder.add_journal(journal.clone());
for _override in overrides {
ical_calendar_builder = ical_calendar_builder.add_journal(_override.clone());
}
}
}
}
for vtimezone in vtimezones.into_values() {
ical_calendar_builder = ical_calendar_builder.add_tz(vtimezone.to_owned());
}
let ical_calendar = ical_calendar_builder
.build()
.map_err(|parser_error| Error::IcalError(parser_error.into()))?;
let export_calendar = IcalCalendar::from_objects("RustiCal Export".to_owned(), objects, props);
let mut resp = Response::builder().status(StatusCode::OK);
let hdrs = resp.headers_mut().unwrap();
hdrs.typed_insert(ContentType::from_str("text/calendar").unwrap());
hdrs.typed_insert(ContentType::from_str("text/calendar; charset=utf-8").unwrap());
let filename = format!("{}_{}.ics", calendar.principal, calendar.id);
let filename = utf8_percent_encode(&filename, CONTROLS);
@@ -118,6 +87,6 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
if matches!(method, Method::HEAD) {
Ok(resp.body(Body::empty()).unwrap())
} else {
Ok(resp.body(Body::new(ical_calendar.generate())).unwrap())
Ok(resp.body(Body::new(export_calendar.generate())).unwrap())
}
}

View File

@@ -4,17 +4,14 @@ use axum::{
extract::{Path, State},
response::{IntoResponse, Response},
};
use caldata::component::{Component, ComponentMut};
use caldata::{IcalParser, parser::ParserOptions};
use http::StatusCode;
use ical::{
generator::Emitter,
parser::{Component, ComponentMut},
};
use rustical_dav::header::Overwrite;
use rustical_ical::{CalendarObject, CalendarObjectType};
use rustical_ical::CalendarObjectType;
use rustical_store::{
Calendar, CalendarMetadata, CalendarStore, SubscriptionStore, auth::Principal,
};
use std::io::BufReader;
use tracing::instrument;
#[instrument(skip(resource_service))]
@@ -29,34 +26,32 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
return Err(Error::Unauthorized);
}
let mut parser = ical::IcalParser::new(BufReader::new(body.as_bytes()));
let mut cal = parser
.next()
.expect("input must contain calendar")
.unwrap()
.mutable();
if parser.next().is_some() {
return Err(rustical_ical::Error::InvalidData(
"multiple calendars, only one allowed".to_owned(),
)
.into());
}
let parser = IcalParser::from_slice(body.as_bytes());
let mut cal = match parser.expect_one() {
Ok(cal) => cal.mutable(),
Err(err) => return Ok((StatusCode::BAD_REQUEST, err.to_string()).into_response()),
};
// Extract calendar metadata
let displayname = cal
.get_property("X-WR-CALNAME")
.and_then(|prop| prop.value.to_owned());
.and_then(|prop| prop.value.clone());
let description = cal
.get_property("X-WR-CALDESC")
.and_then(|prop| prop.value.to_owned());
.and_then(|prop| prop.value.clone());
let color = cal
.get_property("X-WR-CALCOLOR")
.and_then(|prop| prop.value.clone());
let timezone_id = cal
.get_property("X-WR-TIMEZONE")
.and_then(|prop| prop.value.to_owned());
.and_then(|prop| prop.value.clone());
// These properties should not appear in the expanded calendar objects
cal.remove_property("X-WR-CALNAME");
cal.remove_property("X-WR-CALDESC");
cal.remove_property("X-WR-CALCOLOR");
cal.remove_property("X-WR-TIMEZONE");
let cal = cal.verify().unwrap();
let cal = cal.build(&ParserOptions::default(), None).unwrap();
// Make sure timezone is valid
if let Some(timezone_id) = timezone_id.as_ref() {
assert!(
@@ -64,8 +59,7 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
"Invalid calendar timezone id"
);
}
// Extract necessary component types
// // Extract necessary component types
let mut cal_components = vec![];
if !cal.events.is_empty() {
cal_components.push(CalendarObjectType::Event);
@@ -77,13 +71,10 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
cal_components.push(CalendarObjectType::Todo);
}
let expanded_cals = cal.expand_calendar();
// Janky way to convert between IcalCalendar and CalendarObject
let objects = expanded_cals
.into_iter()
.map(|cal| cal.generate())
.map(CalendarObject::from_ics)
.collect::<Result<Vec<_>, _>>()?;
let objects = match cal.into_objects() {
Ok(objects) => objects.into_iter().map(Into::into).collect(),
Err(err) => return Ok((StatusCode::BAD_REQUEST, err.to_string()).into_response()),
};
let new_cal = Calendar {
principal,
id: cal_id,
@@ -91,7 +82,7 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
displayname,
order: 0,
description,
color: None,
color,
},
timezone_id,
deleted_at: None,

View File

@@ -1,10 +1,13 @@
use std::str::FromStr;
use crate::Error;
use crate::calendar::CalendarResourceService;
use crate::calendar::prop::SupportedCalendarComponentSet;
use crate::error::Precondition;
use axum::extract::{Path, State};
use axum::response::{IntoResponse, Response};
use caldata::IcalParser;
use http::{Method, StatusCode};
use ical::IcalParser;
use rustical_dav::xml::HrefElement;
use rustical_ical::CalendarObjectType;
use rustical_store::auth::Principal;
@@ -79,30 +82,38 @@ pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
_ => unreachable!("We never call with another method"),
};
if let Some("") = request.displayname.as_deref() {
request.displayname = None
if request.displayname.as_deref() == Some("") {
request.displayname = None;
}
let timezone_id = if let Some(tzid) = request.calendar_timezone_id {
if chrono_tz::Tz::from_str(&tzid).is_err() {
return Err(Error::PreconditionFailed(Precondition::CalendarTimezone(
"Invalid timezone ID in calendar-timezone-id",
)));
}
Some(tzid)
} else if let Some(tz) = request.calendar_timezone {
// TODO: Proper error (calendar-timezone precondition)
let calendar = IcalParser::new(tz.as_bytes())
let calendar = IcalParser::from_slice(tz.as_bytes())
.next()
.ok_or(rustical_dav::Error::BadRequest(
"No timezone data provided".to_owned(),
))?
.map_err(|_| rustical_dav::Error::BadRequest("No timezone data provided".to_owned()))?;
.ok_or(Error::PreconditionFailed(Precondition::CalendarTimezone(
"No timezone data provided",
)))?
.map_err(|_| {
Error::PreconditionFailed(Precondition::CalendarTimezone("Error parsing timezone"))
})?;
let timezone = calendar
.timezones
.first()
.ok_or(rustical_dav::Error::BadRequest(
"No timezone data provided".to_owned(),
.vtimezones
.values()
.next()
.ok_or(Error::PreconditionFailed(Precondition::CalendarTimezone(
"No timezone data provided",
)))?;
let timezone: Option<chrono_tz::Tz> = timezone.into();
let timezone = timezone.ok_or(Error::PreconditionFailed(
Precondition::CalendarTimezone("No timezone data provided"),
))?;
let timezone: chrono_tz::Tz = timezone
.try_into()
.map_err(|_| rustical_dav::Error::BadRequest("No timezone data provided".to_owned()))?;
Some(timezone.name().to_owned())
} else {
@@ -110,8 +121,8 @@ pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
};
let calendar = Calendar {
id: cal_id.to_owned(),
principal: principal.to_owned(),
id: cal_id.clone(),
principal: principal.clone(),
meta: CalendarMetadata {
order: request.calendar_order.unwrap_or(0),
displayname: request.displayname,
@@ -123,14 +134,16 @@ pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
synctoken: 0,
subscription_url: request.source.map(|href| href.href),
push_topic: uuid::Uuid::new_v4().to_string(),
components: request
.supported_calendar_component_set
.map(Into::into)
.unwrap_or(vec![
components: request.supported_calendar_component_set.map_or_else(
|| {
vec![
CalendarObjectType::Event,
CalendarObjectType::Todo,
CalendarObjectType::Journal,
]),
]
},
Into::into,
),
};
cal_store.insert_calendar(calendar).await?;

View File

@@ -49,12 +49,12 @@ pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
};
let subscription = Subscription {
id: sub_id.to_owned(),
id: sub_id.clone(),
push_resource: request
.subscription
.web_push_subscription
.push_resource
.to_owned(),
.clone(),
topic: calendar_resource.cal.push_topic,
expiration: expires.naive_local(),
public_key: request

View File

@@ -4,10 +4,10 @@ use rustical_ical::CalendarObject;
use rustical_store::CalendarStore;
use rustical_xml::XmlDeserialize;
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
// <!ELEMENT calendar-query ((DAV:allprop | DAV:propname | DAV:prop)?, href+)>
pub(crate) struct CalendarMultigetRequest {
pub struct CalendarMultigetRequest {
#[xml(ty = "untagged")]
pub(crate) prop: PropfindType<CalendarObjectPropWrapperName>,
#[xml(flatten)]
@@ -21,26 +21,26 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
principal: &str,
cal_id: &str,
store: &C,
) -> Result<(Vec<CalendarObject>, Vec<String>), Error> {
) -> Result<(Vec<(String, CalendarObject)>, Vec<String>), Error> {
let mut result = vec![];
let mut not_found = vec![];
for href in &cal_query.href {
if let Some(filename) = href.strip_prefix(path) {
let filename = filename.trim_start_matches("/");
if let Ok(href) = percent_encoding::percent_decode_str(href).decode_utf8()
&& let Some(filename) = href.strip_prefix(path)
{
let filename = filename.trim_start_matches('/');
if let Some(object_id) = filename.strip_suffix(".ics") {
match store.get_object(principal, cal_id, object_id, false).await {
Ok(object) => result.push(object),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
Ok(object) => result.push((object_id.to_owned(), object)),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_string()),
Err(err) => return Err(err.into()),
};
}
} else {
not_found.push(href.to_owned());
continue;
not_found.push(href.to_string());
}
} else {
not_found.push(href.to_owned());
continue;
}
}

View File

@@ -0,0 +1,424 @@
use crate::calendar::methods::report::calendar_query::{
TimeRangeElement,
prop_filter::{PropFilterElement, PropFilterable},
};
use caldata::{
component::{
CalendarInnerData, Component, IcalAlarm, IcalCalendarObject, IcalEvent, IcalTimeZone,
IcalTodo,
},
parser::ContentLine,
};
use rustical_xml::XmlDeserialize;
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[allow(dead_code)]
// https://datatracker.ietf.org/doc/html/rfc4791#section-9.7.1
pub struct CompFilterElement {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) is_not_defined: Option<()>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) time_range: Option<TimeRangeElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub(crate) prop_filter: Vec<PropFilterElement>,
#[allow(clippy::use_self)]
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub(crate) comp_filter: Vec<CompFilterElement>,
#[xml(ty = "attr")]
pub(crate) name: String,
}
pub trait CompFilterable: PropFilterable + Sized {
fn get_comp_name(&self) -> &'static str;
fn match_time_range(&self, time_range: &TimeRangeElement) -> bool;
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool;
// https://datatracker.ietf.org/doc/html/rfc4791#section-9.7.1
// The scope of the
// CALDAV:comp-filter XML element is the calendar object when used as
// a child of the CALDAV:filter XML element. The scope of the
// CALDAV:comp-filter XML element is the enclosing calendar component
// when used as a child of another CALDAV:comp-filter XML element
fn matches(&self, comp_filter: &CompFilterElement) -> bool {
let name_matches = self.get_comp_name() == comp_filter.name;
match (comp_filter.is_not_defined.is_some(), name_matches) {
// We are the component that's not supposed to be defined
(true, true)
// We don't match
| (false, false) => return false,
// We shall not be and indeed we aren't
(true, false) => return true,
_ => {}
}
if let Some(time_range) = comp_filter.time_range.as_ref()
&& !self.match_time_range(time_range)
{
return false;
}
for prop_filter in &comp_filter.prop_filter {
if !prop_filter.match_component(self) {
return false;
}
}
comp_filter
.comp_filter
.iter()
.all(|filter| self.match_subcomponents(filter))
}
}
impl CompFilterable for CalendarInnerData {
fn get_comp_name(&self) -> &'static str {
match self {
Self::Event(main, _) => main.get_comp_name(),
Self::Journal(main, _) => main.get_comp_name(),
Self::Todo(main, _) => main.get_comp_name(),
}
}
fn match_time_range(&self, time_range: &TimeRangeElement) -> bool {
if let Some(start) = &time_range.start
&& let Some(last_end) = self.get_last_occurence()
&& start.to_utc() > last_end.utc()
{
return false;
}
if let Some(end) = &time_range.end
&& let Some(first_start) = self.get_first_occurence()
&& end.to_utc() < first_start.utc()
{
return false;
}
true
}
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool {
match self {
Self::Event(main, overrides) => std::iter::once(main)
.chain(overrides.iter())
.flat_map(IcalEvent::get_alarms)
.any(|alarm| alarm.matches(comp_filter)),
Self::Todo(main, overrides) => std::iter::once(main)
.chain(overrides.iter())
.flat_map(IcalTodo::get_alarms)
.any(|alarm| alarm.matches(comp_filter)),
// VJOURNAL has no subcomponents
Self::Journal(_, _) => comp_filter.is_not_defined.is_some(),
}
}
}
impl PropFilterable for IcalAlarm {
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine> {
Component::get_named_properties(self, name)
}
}
impl CompFilterable for IcalAlarm {
fn get_comp_name(&self) -> &'static str {
Component::get_comp_name(self)
}
fn match_time_range(&self, _time_range: &TimeRangeElement) -> bool {
true
}
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool {
comp_filter.is_not_defined.is_some()
}
}
impl PropFilterable for CalendarInnerData {
#[allow(refining_impl_trait)]
fn get_named_properties<'a>(
&'a self,
name: &'a str,
) -> Box<dyn Iterator<Item = &'a ContentLine> + 'a> {
// TODO: If we were pedantic, we would have to do recurrence expansion first
// and take into account the overrides :(
match self {
Self::Event(main, _) => Box::new(main.get_named_properties(name)),
Self::Todo(main, _) => Box::new(main.get_named_properties(name)),
Self::Journal(main, _) => Box::new(main.get_named_properties(name)),
}
}
}
impl PropFilterable for IcalCalendarObject {
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine> {
Component::get_named_properties(self, name)
}
}
impl CompFilterable for IcalCalendarObject {
fn get_comp_name(&self) -> &'static str {
Component::get_comp_name(self)
}
fn match_time_range(&self, _time_range: &TimeRangeElement) -> bool {
// VCALENDAR has no concept of time range
false
}
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool {
let mut matches = self
.get_vtimezones()
.values()
.map(|tz| tz.matches(comp_filter))
.chain([self.get_inner().matches(comp_filter)]);
if comp_filter.is_not_defined.is_some() {
matches.all(|x| !x)
} else {
matches.any(|x| x)
}
}
}
impl PropFilterable for IcalTimeZone {
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine> {
Component::get_named_properties(self, name)
}
}
impl CompFilterable for IcalTimeZone {
fn get_comp_name(&self) -> &'static str {
Component::get_comp_name(self)
}
fn match_time_range(&self, _time_range: &TimeRangeElement) -> bool {
false
}
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool {
// VTIMEZONE has no subcomponents
comp_filter.is_not_defined.is_some()
}
}
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
use rustical_dav::xml::{MatchType, NegateCondition, TextCollation, TextMatchElement};
use rustical_ical::{CalendarObject, UtcDateTime};
use crate::calendar::methods::report::calendar_query::{
CompFilterElement, CompFilterable, PropFilterElement, TimeRangeElement,
};
const ICS: &str = r"BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:me
BEGIN:VTIMEZONE
TZID:Europe/Berlin
X-LIC-LOCATION:Europe/Berlin
END:VTIMEZONE
BEGIN:VEVENT
UID:318ec6503573d9576818daf93dac07317058d95c
DTSTAMP:20250502T132758Z
DTSTART;TZID=Europe/Berlin:20250506T090000
DTEND;TZID=Europe/Berlin:20250506T092500
SEQUENCE:2
SUMMARY:weekly stuff
TRANSP:OPAQUE
RRULE:FREQ=WEEKLY;COUNT=4;INTERVAL=2;BYDAY=TU,TH,SU
END:VEVENT
END:VCALENDAR";
#[test]
fn test_comp_filter_matching() {
let object = CalendarObject::from_ics(ICS.to_string()).unwrap();
let comp_filter = CompFilterElement {
is_not_defined: Some(()),
name: "VCALENDAR".to_string(),
time_range: None,
prop_filter: vec![],
comp_filter: vec![],
};
assert!(
!object.get_inner().matches(&comp_filter),
"filter: wants no VCALENDAR"
);
let comp_filter = CompFilterElement {
is_not_defined: None,
name: "VCALENDAR".to_string(),
time_range: None,
prop_filter: vec![],
comp_filter: vec![CompFilterElement {
name: "VTODO".to_string(),
is_not_defined: None,
time_range: None,
prop_filter: vec![],
comp_filter: vec![],
}],
};
assert!(
!object.get_inner().matches(&comp_filter),
"filter matches VTODO"
);
let comp_filter = CompFilterElement {
is_not_defined: None,
name: "VCALENDAR".to_string(),
time_range: None,
prop_filter: vec![],
comp_filter: vec![CompFilterElement {
name: "VEVENT".to_string(),
is_not_defined: None,
time_range: None,
prop_filter: vec![],
comp_filter: vec![],
}],
};
assert!(
object.get_inner().matches(&comp_filter),
"filter matches VEVENT"
);
let comp_filter = CompFilterElement {
is_not_defined: None,
name: "VCALENDAR".to_string(),
time_range: None,
prop_filter: vec![
PropFilterElement {
is_not_defined: None,
name: "VERSION".to_string(),
time_range: None,
text_match: Some(TextMatchElement {
match_type: MatchType::Contains,
needle: "2.0".to_string(),
collation: TextCollation::default(),
negate_condition: NegateCondition::default(),
}),
param_filter: vec![],
},
PropFilterElement {
is_not_defined: Some(()),
name: "STUFF".to_string(),
time_range: None,
text_match: None,
param_filter: vec![],
},
],
comp_filter: vec![CompFilterElement {
name: "VEVENT".to_string(),
is_not_defined: None,
time_range: None,
prop_filter: vec![PropFilterElement {
is_not_defined: None,
name: "SUMMARY".to_string(),
time_range: None,
text_match: Some(TextMatchElement {
match_type: MatchType::Contains,
collation: TextCollation::default(),
negate_condition: NegateCondition(false),
needle: "weekly".to_string(),
}),
param_filter: vec![],
}],
comp_filter: vec![],
}],
};
assert!(
object.get_inner().matches(&comp_filter),
"Some prop filters on VCALENDAR and VEVENT"
);
}
#[test]
fn test_comp_filter_time_range() {
let object = CalendarObject::from_ics(ICS.to_string()).unwrap();
let comp_filter = CompFilterElement {
is_not_defined: None,
name: "VCALENDAR".to_string(),
time_range: None,
prop_filter: vec![],
comp_filter: vec![CompFilterElement {
name: "VEVENT".to_string(),
is_not_defined: None,
time_range: Some(TimeRangeElement {
start: Some(UtcDateTime(
Utc.with_ymd_and_hms(2025, 4, 1, 0, 0, 0).unwrap(),
)),
end: Some(UtcDateTime(
Utc.with_ymd_and_hms(2025, 8, 1, 0, 0, 0).unwrap(),
)),
}),
prop_filter: vec![],
comp_filter: vec![],
}],
};
assert!(
object.get_inner().matches(&comp_filter),
"event should lie in time range"
);
let comp_filter = CompFilterElement {
is_not_defined: None,
name: "VCALENDAR".to_string(),
time_range: None,
prop_filter: vec![],
comp_filter: vec![CompFilterElement {
name: "VEVENT".to_string(),
is_not_defined: None,
time_range: Some(TimeRangeElement {
start: Some(UtcDateTime(
Utc.with_ymd_and_hms(2024, 4, 1, 0, 0, 0).unwrap(),
)),
end: Some(UtcDateTime(
Utc.with_ymd_and_hms(2024, 8, 1, 0, 0, 0).unwrap(),
)),
}),
prop_filter: vec![],
comp_filter: vec![],
}],
};
assert!(
!object.get_inner().matches(&comp_filter),
"event should not lie in time range"
);
}
#[test]
fn test_match_timezone() {
let object = CalendarObject::from_ics(ICS.to_string()).unwrap();
let comp_filter = CompFilterElement {
is_not_defined: None,
name: "VCALENDAR".to_string(),
time_range: None,
prop_filter: vec![],
comp_filter: vec![CompFilterElement {
name: "VTIMEZONE".to_string(),
is_not_defined: None,
time_range: None,
prop_filter: vec![PropFilterElement {
is_not_defined: None,
name: "TZID".to_string(),
time_range: None,
text_match: Some(TextMatchElement {
match_type: MatchType::Contains,
collation: TextCollation::AsciiCasemap,
negate_condition: NegateCondition::default(),
needle: "Europe/Berlin".to_string(),
}),
param_filter: vec![],
}],
comp_filter: vec![],
}],
};
assert!(
object.get_inner().matches(&comp_filter),
"Timezone should be Europe/Berlin"
);
}
}

View File

@@ -1,20 +1,21 @@
use super::comp_filter::{CompFilterElement, CompFilterable};
use crate::calendar_object::CalendarObjectPropWrapperName;
use rustical_dav::xml::PropfindType;
use rustical_ical::{CalendarObject, UtcDateTime};
use caldata::{component::IcalCalendarObject, parser::ContentLine};
use rustical_dav::xml::{PropfindType, TextMatchElement};
use rustical_ical::UtcDateTime;
use rustical_store::calendar_store::CalendarQuery;
use rustical_xml::XmlDeserialize;
use std::ops::Deref;
use rustical_xml::{XmlDeserialize, XmlRootTag};
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) struct TimeRangeElement {
pub struct TimeRangeElement {
#[xml(ty = "attr")]
pub(crate) start: Option<UtcDateTime>,
#[xml(ty = "attr")]
pub(crate) end: Option<UtcDateTime>,
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.3
pub struct ParamFilterElement {
@@ -27,131 +28,44 @@ pub struct ParamFilterElement {
pub(crate) name: String,
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[allow(dead_code)]
pub struct TextMatchElement {
#[xml(ty = "attr")]
pub(crate) collation: String,
#[xml(ty = "attr")]
// "yes" or "no", default: "no"
pub(crate) negate_condition: Option<String>,
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[allow(dead_code)]
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.2
pub(crate) struct PropFilterElement {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) is_not_defined: Option<()>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) time_range: Option<TimeRangeElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) text_match: Option<TextMatchElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub(crate) param_filter: Vec<ParamFilterElement>,
#[xml(ty = "attr")]
pub(crate) name: String,
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[allow(dead_code)]
// https://datatracker.ietf.org/doc/html/rfc4791#section-9.7.1
pub(crate) struct CompFilterElement {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) is_not_defined: Option<()>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) time_range: Option<TimeRangeElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub(crate) prop_filter: Vec<PropFilterElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub(crate) comp_filter: Vec<CompFilterElement>,
#[xml(ty = "attr")]
pub(crate) name: String,
}
impl CompFilterElement {
// match the VCALENDAR part
pub fn matches_root(&self, cal_object: &CalendarObject) -> bool {
let comp_vcal = self.name == "VCALENDAR";
match (self.is_not_defined, comp_vcal) {
// Client wants VCALENDAR to not exist but we are a VCALENDAR
(Some(()), true) => return false,
// Client is asking for something different than a vcalendar
(None, false) => return false,
_ => {}
impl ParamFilterElement {
#[must_use]
pub fn match_property(&self, prop: &ContentLine) -> bool {
let Some(param) = prop.params.get_param(&self.name) else {
return self.is_not_defined.is_some();
};
if self.time_range.is_some() {
// <time-range> should be applied on VEVENT/VTODO but not on VCALENDAR
if self.is_not_defined.is_some() {
return false;
}
// TODO: Implement prop-filter at some point
// Apply sub-comp-filters on VEVENT/VTODO/VJOURNAL component
if self
.comp_filter
.iter()
.all(|filter| filter.matches(cal_object))
{
let Some(text_match) = self.text_match.as_ref() else {
return true;
}
false
}
// match the VEVENT/VTODO/VJOURNAL part
pub fn matches(&self, cal_object: &CalendarObject) -> bool {
let comp_name_matches = self.name == cal_object.get_component_name();
match (self.is_not_defined, comp_name_matches) {
// Client wants VCALENDAR to not exist but we are a VCALENDAR
(Some(()), true) => return false,
// Client is asking for something different than a vcalendar
(None, false) => return false,
_ => {}
};
// TODO: Implement prop-filter (and comp-filter?) at some point
if let Some(time_range) = &self.time_range {
if let Some(start) = &time_range.start
&& let Some(last_occurence) = cal_object.get_last_occurence().unwrap_or(None)
&& start.deref() > &last_occurence.utc()
{
return false;
}
if let Some(end) = &time_range.end
&& let Some(first_occurence) = cal_object.get_first_occurence().unwrap_or(None)
&& end.deref() < &first_occurence.utc()
{
return false;
}
}
true
text_match.match_text(param)
}
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, XmlRootTag, Clone, Debug, PartialEq)]
#[xml(root = "filter", ns = "rustical_dav::namespace::NS_CALDAV")]
#[allow(dead_code)]
// https://datatracker.ietf.org/doc/html/rfc4791#section-9.7
pub(crate) struct FilterElement {
pub struct FilterElement {
// This comp-filter matches on VCALENDAR
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) comp_filter: CompFilterElement,
}
impl FilterElement {
pub fn matches(&self, cal_object: &CalendarObject) -> bool {
self.comp_filter.matches_root(cal_object)
#[must_use]
pub fn matches(&self, cal_object: &IcalCalendarObject) -> bool {
cal_object.matches(&self.comp_filter)
}
}
impl From<&FilterElement> for CalendarQuery {
fn from(value: &FilterElement) -> Self {
let comp_filter_vcalendar = &value.comp_filter;
for comp_filter in comp_filter_vcalendar.comp_filter.iter() {
for comp_filter in &comp_filter_vcalendar.comp_filter {
// A calendar object cannot contain both VEVENT and VTODO, so we only have to handle
// whatever we get first
if matches!(comp_filter.name.as_str(), "VEVENT" | "VTODO")
@@ -159,13 +73,13 @@ impl From<&FilterElement> for CalendarQuery {
{
let start = time_range.start.as_ref().map(|start| start.date_naive());
let end = time_range.end.as_ref().map(|end| end.date_naive());
return CalendarQuery {
return Self {
time_start: start,
time_end: end,
};
}
}
Default::default()
Self::default()
}
}
@@ -185,10 +99,48 @@ pub struct CalendarQueryRequest {
impl From<&CalendarQueryRequest> for CalendarQuery {
fn from(value: &CalendarQueryRequest) -> Self {
value
.filter
.as_ref()
.map(CalendarQuery::from)
.unwrap_or_default()
value.filter.as_ref().map(Self::from).unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use crate::calendar::methods::report::calendar_query::{
CompFilterElement, FilterElement, TimeRangeElement,
};
use chrono::{NaiveDate, TimeZone, Utc};
use rustical_ical::UtcDateTime;
use rustical_store::calendar_store::CalendarQuery;
#[test]
fn test_filter_element_calendar_query() {
let filter = FilterElement {
comp_filter: CompFilterElement {
name: "VCALENDAR".to_string(),
is_not_defined: None,
time_range: None,
prop_filter: vec![],
comp_filter: vec![CompFilterElement {
name: "VEVENT".to_string(),
is_not_defined: None,
time_range: Some(TimeRangeElement {
start: Some(UtcDateTime(
Utc.with_ymd_and_hms(2024, 4, 1, 0, 0, 0).unwrap(),
)),
end: Some(UtcDateTime(
Utc.with_ymd_and_hms(2024, 8, 1, 0, 0, 0).unwrap(),
)),
}),
prop_filter: vec![],
comp_filter: vec![],
}],
},
};
let derived_query: CalendarQuery = (&filter).into();
let query = CalendarQuery {
time_start: Some(NaiveDate::from_ymd_opt(2024, 4, 1).unwrap()),
time_end: Some(NaiveDate::from_ymd_opt(2024, 8, 1).unwrap()),
};
assert_eq!(derived_query, query);
}
}

View File

@@ -2,39 +2,46 @@ use crate::Error;
use rustical_ical::CalendarObject;
use rustical_store::CalendarStore;
mod comp_filter;
mod elements;
pub(crate) use elements::*;
mod prop_filter;
#[cfg(test)]
mod tests;
#[allow(unused_imports)]
pub use comp_filter::{CompFilterElement, CompFilterable};
pub use elements::*;
#[allow(unused_imports)]
pub use prop_filter::PropFilterElement;
pub async fn get_objects_calendar_query<C: CalendarStore>(
cal_query: &CalendarQueryRequest,
principal: &str,
cal_id: &str,
store: &C,
) -> Result<Vec<CalendarObject>, Error> {
) -> Result<Vec<(String, CalendarObject)>, Error> {
let mut objects = store
.calendar_query(principal, cal_id, cal_query.into())
.await?;
if let Some(filter) = &cal_query.filter {
objects.retain(|object| filter.matches(object));
objects.retain(|(_id, object)| filter.matches(object.get_inner()));
}
Ok(objects)
}
#[cfg(test)]
mod tests {
use rustical_dav::xml::PropElement;
use rustical_xml::XmlDocument;
use crate::{
calendar::methods::report::{
ReportRequest,
calendar_query::{
CalendarQueryRequest, CompFilterElement, FilterElement, ParamFilterElement,
PropFilterElement, TextMatchElement,
},
},
calendar_object::{CalendarObjectPropName, CalendarObjectPropWrapperName},
mod xml_tests {
use super::{
CalendarQueryRequest, FilterElement, ParamFilterElement, comp_filter::CompFilterElement,
prop_filter::PropFilterElement,
};
use crate::{
calendar::methods::report::ReportRequest,
calendar_object::{CalendarData, CalendarObjectPropName, CalendarObjectPropWrapperName},
};
use rustical_dav::xml::{
MatchType, NegateCondition, PropElement, TextCollation, TextMatchElement,
};
use rustical_xml::XmlDocument;
#[test]
fn calendar_query_7_8_7() {
@@ -76,7 +83,7 @@ mod tests {
CalendarObjectPropName::Getetag,
),
CalendarObjectPropWrapperName::CalendarObject(
CalendarObjectPropName::CalendarData(Default::default())
CalendarObjectPropName::CalendarData(CalendarData::default())
),
],
vec![]
@@ -90,16 +97,20 @@ mod tests {
prop_filter: vec![PropFilterElement {
name: "ATTENDEE".to_owned(),
text_match: Some(TextMatchElement {
collation: "i;ascii-casemap".to_owned(),
negate_condition: None
match_type: MatchType::Contains,
collation: TextCollation::AsciiCasemap,
negate_condition: NegateCondition(false),
needle: "mailto:lisa@example.com".to_string()
}),
is_not_defined: None,
param_filter: vec![ParamFilterElement {
is_not_defined: None,
name: "PARTSTAT".to_owned(),
text_match: Some(TextMatchElement {
collation: "i;ascii-casemap".to_owned(),
negate_condition: None
match_type: MatchType::Contains,
collation: TextCollation::AsciiCasemap,
negate_condition: NegateCondition(false),
needle: "NEEDS-ACTION".to_string()
}),
}],
time_range: None
@@ -115,6 +126,6 @@ mod tests {
timezone: None,
timezone_id: None
}
)
);
}
}

View File

@@ -0,0 +1,77 @@
use super::{ParamFilterElement, TimeRangeElement};
use caldata::{parser::ContentLine, types::CalDateTime};
use rustical_dav::xml::TextMatchElement;
use rustical_ical::UtcDateTime;
use rustical_xml::XmlDeserialize;
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.2
pub struct PropFilterElement {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) is_not_defined: Option<()>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) time_range: Option<TimeRangeElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) text_match: Option<TextMatchElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub(crate) param_filter: Vec<ParamFilterElement>,
#[xml(ty = "attr")]
pub(crate) name: String,
}
pub trait PropFilterable {
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine>;
}
impl PropFilterElement {
#[must_use]
pub fn match_property(&self, property: &ContentLine) -> bool {
if let Some(TimeRangeElement { start, end }) = &self.time_range {
// TODO: Respect timezones
let Ok(timestamp) = CalDateTime::parse_prop(property, None) else {
return false;
};
let timestamp = timestamp.utc();
if let Some(UtcDateTime(start)) = start
&& start > &timestamp
{
return false;
}
if let Some(UtcDateTime(end)) = end
&& end < &timestamp
{
return false;
}
return true;
}
if let Some(text_match) = &self.text_match
&& !text_match.match_property(property)
{
return false;
}
if !self
.param_filter
.iter()
.all(|param_filter| param_filter.match_property(property))
{
return false;
}
true
}
pub fn match_component(&self, comp: &impl PropFilterable) -> bool {
let mut properties = comp.get_named_properties(&self.name);
if self.is_not_defined.is_some() {
return properties.next().is_none();
}
// The filter matches when one property instance matches
// Example where this matters: We have multiple attendees and want to match one
properties.any(|prop| self.match_property(prop))
}
}

View File

@@ -0,0 +1,83 @@
use super::FilterElement;
use rstest::rstest;
use rustical_ical::CalendarObject;
use rustical_xml::XmlDocument;
const ICS_1: &str = r"BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTIMEZONE
LAST-MODIFIED:20040110T032845Z
TZID:US/Eastern
BEGIN:DAYLIGHT
DTSTART:20000404T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20001026T020000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:cyrus@example.com
ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:lisa@example.com
DTSTAMP:20060206T001220Z
DTSTART;TZID=US/Eastern:20060104T100000
DURATION:PT1H
LAST-MODIFIED:20060206T001330Z
ORGANIZER:mailto:cyrus@example.com
SEQUENCE:1
STATUS:TENTATIVE
SUMMARY:Event #3
UID:DC6C50A017428C5216A2F1CD@example.com
X-ABC-GUID:E1CX5Dr-0007ym-Hz@example.com
END:VEVENT
END:VCALENDAR
";
const FILTER_1: &str = r#"
<?xml version="1.0" encoding="utf-8" ?>
<C:filter xmlns:C="urn:ietf:params:xml:ns:caldav">
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="ATTENDEE">
<C:text-match collation="i;ascii-casemap">mailto:lisa@example.com</C:text-match>
<C:param-filter name="PARTSTAT">
<C:text-match collation="i;ascii-casemap">NEEDS-ACTION</C:text-match>
</C:param-filter>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>
</C:filter>
"#;
const FILTER_2: &str = r#"
<?xml version="1.0" encoding="utf-8" ?>
<C:filter xmlns:C="urn:ietf:params:xml:ns:caldav">
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="ATTENDEE">
<C:text-match collation="i;ascii-casemap">mailto:lisa@example.com</C:text-match>
<C:param-filter name="PARTSTAT">
<C:text-match collation="i;ascii-casemap">ACCEPTED</C:text-match>
</C:param-filter>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>
</C:filter>
"#;
#[rstest]
#[case(ICS_1, FILTER_1, true)]
#[case(ICS_1, FILTER_2, false)]
fn yeet(#[case] ics: &str, #[case] filter: &str, #[case] matches: bool) {
let obj = CalendarObject::from_ics(ics.to_owned()).unwrap();
let filter = FilterElement::parse_str(filter).unwrap();
assert_eq!(matches, filter.matches(obj.get_inner()));
}

View File

@@ -27,7 +27,7 @@ use sync_collection::handle_sync_collection;
use tracing::instrument;
mod calendar_multiget;
mod calendar_query;
pub mod calendar_query;
mod sync_collection;
#[derive(XmlDeserialize, XmlDocument, Clone, Debug, PartialEq)]
@@ -41,17 +41,17 @@ pub(crate) enum ReportRequest {
}
impl ReportRequest {
fn props(&self) -> &PropfindType<CalendarObjectPropWrapperName> {
const fn props(&self) -> &PropfindType<CalendarObjectPropWrapperName> {
match &self {
ReportRequest::CalendarMultiget(CalendarMultigetRequest { prop, .. }) => prop,
ReportRequest::CalendarQuery(CalendarQueryRequest { prop, .. }) => prop,
ReportRequest::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
Self::CalendarMultiget(CalendarMultigetRequest { prop, .. })
| Self::CalendarQuery(CalendarQueryRequest { prop, .. })
| Self::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
}
}
}
fn objects_response(
objects: Vec<CalendarObject>,
objects: Vec<(String, CalendarObject)>,
not_found: Vec<String>,
path: &str,
principal: &str,
@@ -60,11 +60,12 @@ fn objects_response(
prop: &PropfindType<CalendarObjectPropWrapperName>,
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
let mut responses = Vec::new();
for object in objects {
let path = format!("{}/{}.ics", path, object.get_id());
for (object_id, object) in objects {
let path = format!("{path}/{object_id}.ics");
responses.push(
CalendarObjectResource {
object,
object_id,
principal: principal.to_owned(),
}
.propfind(&path, prop, None, puri, user)?,
@@ -174,7 +175,7 @@ mod tests {
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::Getetag),
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::CalendarData(
CalendarData { comp: None, expand: Some(ExpandElement {
CalendarData { comp: None, prop: None, expand: Some(ExpandElement {
start: <UtcDateTime as ValueDeserialize>::deserialize("20250426T220000Z").unwrap(),
end: <UtcDateTime as ValueDeserialize>::deserialize("20250503T220000Z").unwrap(),
}), limit_recurrence_set: None, limit_freebusy_set: None }
@@ -184,7 +185,7 @@ mod tests {
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
]
})
)
);
}
#[test]
@@ -241,7 +242,7 @@ mod tests {
timezone: None,
timezone_id: None,
})
)
);
}
#[test]
@@ -269,6 +270,6 @@ mod tests {
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
]
})
)
);
}
}

View File

@@ -32,11 +32,12 @@ pub async fn handle_sync_collection<C: CalendarStore>(
.await?;
let mut responses = Vec::new();
for object in new_objects {
let path = format!("{}/{}.ics", path, object.get_id());
for (object_id, object) in new_objects {
let path = format!("{}/{}.ics", path, &object_id);
responses.push(
CalendarObjectResource {
object,
object_id,
principal: principal.to_owned(),
}
.propfind(&path, &sync_collection.prop, None, puri, user)?,

View File

@@ -1,15 +1,16 @@
use derive_more::derive::{From, Into};
use rustical_dav::xml::TextCollation;
use rustical_ical::CalendarObjectType;
use rustical_xml::{XmlDeserialize, XmlSerialize};
use strum_macros::VariantArray;
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, From, Into)]
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq, From, Into)]
pub struct SupportedCalendarComponent {
#[xml(ty = "attr")]
pub name: CalendarObjectType,
}
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq)]
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq)]
pub struct SupportedCalendarComponentSet {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub comp: Vec<SupportedCalendarComponent>,
@@ -36,7 +37,30 @@ impl From<SupportedCalendarComponentSet> for Vec<CalendarObjectType> {
}
}
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq, From, Into)]
pub struct SupportedCollation(#[xml(ty = "text")] pub TextCollation);
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq)]
pub struct SupportedCollationSet(
#[xml(
ns = "rustical_dav::namespace::NS_CALDAV",
flatten,
rename = "supported-collation"
)]
pub Vec<SupportedCollation>,
);
impl Default for SupportedCollationSet {
fn default() -> Self {
Self(vec![
SupportedCollation(TextCollation::AsciiCasemap),
SupportedCollation(TextCollation::UnicodeCasemap),
SupportedCollation(TextCollation::Octet),
])
}
}
#[derive(Debug, Clone, XmlSerialize, PartialEq, Eq)]
pub struct CalendarData {
#[xml(ty = "attr")]
content_type: String,
@@ -53,13 +77,13 @@ impl Default for CalendarData {
}
}
#[derive(Debug, Clone, XmlSerialize, Default, PartialEq)]
#[derive(Debug, Clone, XmlSerialize, Default, PartialEq, Eq)]
pub struct SupportedCalendarData {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
calendar_data: CalendarData,
}
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
#[derive(Debug, Clone, XmlSerialize, PartialEq, Eq, VariantArray)]
pub enum ReportMethod {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
CalendarQuery,

View File

@@ -1,9 +1,10 @@
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData};
use crate::Error;
use crate::calendar::prop::ReportMethod;
use crate::calendar::prop::{ReportMethod, SupportedCollationSet};
use caldata::IcalParser;
use caldata::types::CalDateTime;
use chrono::{DateTime, Utc};
use derive_more::derive::{From, Into};
use ical::IcalParser;
use rustical_dav::extensions::{
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
};
@@ -11,14 +12,14 @@ use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner, SupportedReportSet};
use rustical_dav_push::{DavPushExtension, DavPushExtensionProp};
use rustical_ical::CalDateTime;
use rustical_store::Calendar;
use rustical_store::auth::Principal;
use rustical_xml::{EnumVariants, PropName};
use rustical_xml::{XmlDeserialize, XmlSerialize};
use serde::Deserialize;
use std::borrow::Cow;
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
#[xml(unit_variants_ident = "CalendarPropName")]
pub enum CalendarProp {
// CalDAV (RFC 4791)
@@ -39,7 +40,9 @@ pub enum CalendarProp {
SupportedCalendarComponentSet(SupportedCalendarComponentSet),
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
SupportedCalendarData(SupportedCalendarData),
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
SupportedCollationSet(SupportedCollationSet),
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
MaxResourceSize(i64),
#[xml(skip_deserializing)]
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
@@ -54,7 +57,7 @@ pub enum CalendarProp {
MaxDateTime(String),
}
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
#[xml(unit_variants_ident = "CalendarPropWrapperName", untagged)]
pub enum CalendarPropWrapper {
Calendar(CalendarProp),
@@ -70,8 +73,8 @@ pub struct CalendarResource {
}
impl ResourceName for CalendarResource {
fn get_name(&self) -> String {
self.cal.id.to_owned()
fn get_name(&self) -> Cow<'_, str> {
Cow::from(&self.cal.id)
}
}
@@ -89,7 +92,7 @@ impl SyncTokenExtension for CalendarResource {
impl DavPushExtension for CalendarResource {
fn get_topic(&self) -> String {
self.cal.push_topic.to_owned()
self.cal.push_topic.clone()
}
}
@@ -135,7 +138,9 @@ impl Resource for CalendarResource {
}
CalendarPropName::CalendarTimezone => {
CalendarProp::CalendarTimezone(self.cal.timezone_id.as_ref().and_then(|tzid| {
vtimezones_rs::VTIMEZONES.get(tzid).map(|tz| tz.to_string())
vtimezones_rs::VTIMEZONES
.get(tzid)
.map(|tz| (*tz).to_string())
}))
}
// chrono_tz uses the IANA database
@@ -154,13 +159,16 @@ impl Resource for CalendarResource {
CalendarPropName::SupportedCalendarData => {
CalendarProp::SupportedCalendarData(SupportedCalendarData::default())
}
CalendarPropName::MaxResourceSize => CalendarProp::MaxResourceSize(10000000),
CalendarPropName::SupportedCollationSet => {
CalendarProp::SupportedCollationSet(SupportedCollationSet::default())
}
CalendarPropName::MaxResourceSize => CalendarProp::MaxResourceSize(10_000_000),
CalendarPropName::SupportedReportSet => {
CalendarProp::SupportedReportSet(SupportedReportSet::all())
}
CalendarPropName::Source => CalendarProp::Source(
self.cal.subscription_url.to_owned().map(HrefElement::from),
),
CalendarPropName::Source => {
CalendarProp::Source(self.cal.subscription_url.clone().map(HrefElement::from))
}
CalendarPropName::MinDateTime => {
CalendarProp::MinDateTime(CalDateTime::from(DateTime::<Utc>::MIN_UTC).format())
}
@@ -181,9 +189,6 @@ impl Resource for CalendarResource {
}
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
if self.read_only {
return Err(rustical_dav::Error::PropReadOnly);
}
match prop {
CalendarPropWrapper::Calendar(prop) => match prop {
CalendarProp::CalendarColor(color) => {
@@ -197,33 +202,30 @@ impl Resource for CalendarResource {
CalendarProp::CalendarTimezone(timezone) => {
if let Some(tz) = timezone {
// TODO: Proper error (calendar-timezone precondition)
let calendar = IcalParser::new(tz.as_bytes())
let calendar = IcalParser::from_slice(tz.as_bytes())
.next()
.ok_or(rustical_dav::Error::BadRequest(
.ok_or_else(|| {
rustical_dav::Error::BadRequest(
"No timezone data provided".to_owned(),
))?
)
})?
.map_err(|_| {
rustical_dav::Error::BadRequest(
"No timezone data provided".to_owned(),
)
})?;
let timezone =
calendar
.timezones
.first()
.ok_or(rustical_dav::Error::BadRequest(
"No timezone data provided".to_owned(),
))?;
let timezone: chrono_tz::Tz = timezone.try_into().map_err(|_| {
let timezone = calendar.vtimezones.values().next().ok_or_else(|| {
rustical_dav::Error::BadRequest("No timezone data provided".to_owned())
})?;
let timezone: Option<chrono_tz::Tz> = timezone.into();
let timezone = timezone.ok_or_else(|| {
rustical_dav::Error::BadRequest("No timezone data provided".to_owned())
})?;
self.cal.timezone_id = Some(timezone.name().to_owned());
}
Ok(())
}
CalendarProp::TimezoneServiceSet(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::CalendarTimezoneId(timezone_id) => {
if let Some(tzid) = &timezone_id
&& !vtimezones_rs::VTIMEZONES.contains_key(tzid)
@@ -243,13 +245,14 @@ impl Resource for CalendarResource {
self.cal.components = comp_set.into();
Ok(())
}
CalendarProp::SupportedCalendarData(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::MaxResourceSize(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::SupportedReportSet(_) => Err(rustical_dav::Error::PropReadOnly),
// Converting between a calendar subscription calendar and a normal one would be weird
CalendarProp::Source(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::MinDateTime(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::MaxDateTime(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::TimezoneServiceSet(_)
| CalendarProp::SupportedCalendarData(_)
| CalendarProp::SupportedCollationSet(_)
| CalendarProp::MaxResourceSize(_)
| CalendarProp::SupportedReportSet(_)
| CalendarProp::Source(_)
| CalendarProp::MinDateTime(_)
| CalendarProp::MaxDateTime(_) => Err(rustical_dav::Error::PropReadOnly),
},
CalendarPropWrapper::SyncToken(prop) => SyncTokenExtension::set_prop(self, prop),
CalendarPropWrapper::DavPush(prop) => DavPushExtension::set_prop(self, prop),
@@ -258,9 +261,6 @@ impl Resource for CalendarResource {
}
fn remove_prop(&mut self, prop: &CalendarPropWrapperName) -> Result<(), rustical_dav::Error> {
if self.read_only {
return Err(rustical_dav::Error::PropReadOnly);
}
match prop {
CalendarPropWrapperName::Calendar(prop) => match prop {
CalendarPropName::CalendarColor => {
@@ -275,7 +275,6 @@ impl Resource for CalendarResource {
self.cal.timezone_id = None;
Ok(())
}
CalendarPropName::TimezoneServiceSet => Err(rustical_dav::Error::PropReadOnly),
CalendarPropName::CalendarOrder => {
self.cal.meta.order = 0;
Ok(())
@@ -283,13 +282,14 @@ impl Resource for CalendarResource {
CalendarPropName::SupportedCalendarComponentSet => {
Err(rustical_dav::Error::PropReadOnly)
}
CalendarPropName::SupportedCalendarData => Err(rustical_dav::Error::PropReadOnly),
CalendarPropName::MaxResourceSize => Err(rustical_dav::Error::PropReadOnly),
CalendarPropName::SupportedReportSet => Err(rustical_dav::Error::PropReadOnly),
// Converting a calendar subscription calendar into a normal one would be weird
CalendarPropName::Source => Err(rustical_dav::Error::PropReadOnly),
CalendarPropName::MinDateTime => Err(rustical_dav::Error::PropReadOnly),
CalendarPropName::MaxDateTime => Err(rustical_dav::Error::PropReadOnly),
CalendarPropName::TimezoneServiceSet
| CalendarPropName::SupportedCalendarData
| CalendarPropName::SupportedCollationSet
| CalendarPropName::MaxResourceSize
| CalendarPropName::SupportedReportSet
| CalendarPropName::Source
| CalendarPropName::MinDateTime
| CalendarPropName::MaxDateTime => Err(rustical_dav::Error::PropReadOnly),
},
CalendarPropWrapperName::SyncToken(prop) => SyncTokenExtension::remove_prop(self, prop),
CalendarPropWrapperName::DavPush(prop) => DavPushExtension::remove_prop(self, prop),
@@ -312,16 +312,11 @@ impl Resource for CalendarResource {
}
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
if self.cal.subscription_url.is_some() {
if self.cal.subscription_url.is_some() || self.read_only {
return Ok(UserPrivilegeSet::owner_write_properties(
user.is_principal(&self.cal.principal),
));
}
if self.read_only {
return Ok(UserPrivilegeSet::owner_read(
user.is_principal(&self.cal.principal),
));
}
Ok(UserPrivilegeSet::owner_only(
user.is_principal(&self.cal.principal),

View File

@@ -6,7 +6,7 @@ use crate::calendar::methods::report::route_report_calendar;
use crate::calendar::resource::CalendarResource;
use crate::calendar_object::CalendarObjectResourceService;
use crate::calendar_object::resource::CalendarObjectResource;
use crate::{CalDavPrincipalUri, Error};
use crate::{CalDavConfig, CalDavPrincipalUri, Error};
use async_trait::async_trait;
use axum::Router;
use axum::extract::Request;
@@ -23,6 +23,7 @@ use tower::Service;
pub struct CalendarResourceService<C: CalendarStore, S: SubscriptionStore> {
pub(crate) cal_store: Arc<C>,
pub(crate) sub_store: Arc<S>,
pub(crate) config: Arc<CalDavConfig>,
}
impl<C: CalendarStore, S: SubscriptionStore> Clone for CalendarResourceService<C, S> {
@@ -30,15 +31,17 @@ impl<C: CalendarStore, S: SubscriptionStore> Clone for CalendarResourceService<C
Self {
cal_store: self.cal_store.clone(),
sub_store: self.sub_store.clone(),
config: self.config.clone(),
}
}
}
impl<C: CalendarStore, S: SubscriptionStore> CalendarResourceService<C, S> {
pub fn new(cal_store: Arc<C>, sub_store: Arc<S>) -> Self {
pub const fn new(cal_store: Arc<C>, sub_store: Arc<S>, config: Arc<CalDavConfig>) -> Self {
Self {
cal_store,
sub_store,
config,
}
}
}
@@ -78,8 +81,9 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
.get_objects(principal, cal_id)
.await?
.into_iter()
.map(|object| CalendarObjectResource {
.map(|(object_id, object)| CalendarObjectResource {
object,
object_id,
principal: principal.to_owned(),
})
.collect())
@@ -91,7 +95,7 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
file: Self::Resource,
) -> Result<(), Self::Error> {
self.cal_store
.update_calendar(principal.to_owned(), cal_id.to_owned(), file.into())
.update_calendar(principal, cal_id, file.into())
.await?;
Ok(())
}
@@ -111,7 +115,8 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
Router::new()
.nest(
"/{object_id}",
CalendarObjectResourceService::new(self.cal_store.clone()).axum_router(),
CalendarObjectResourceService::new(self.cal_store.clone(), self.config.clone())
.axum_router(),
)
.route_service("/", self.axum_service())
}

View File

@@ -0,0 +1,200 @@
---
source: crates/caldav/src/calendar/tests.rs
expression: output
---
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="DAV:">
<href>/caldav/principal/user/calendar/</href>
<propstat>
<prop xmlns="DAV:">
<calendar-timezone xmlns="urn:ietf:params:xml:ns:caldav">BEGIN:VCALENDAR
PRODID:-//github.com/lennart-k/vzic-rs//RustiCal Calendar server//EN
VERSION:2.0
BEGIN:VTIMEZONE
TZID:Europe/Berlin
LAST-MODIFIED:20260124T185655Z
X-LIC-LOCATION:Europe/Berlin
X-PROLEPTIC-TZNAME:LMT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+005328
TZOFFSETTO:+0100
DTSTART:18930401T000000
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19160430T230000
RDATE:19400401T020000
RDATE:19430329T020000
RDATE:19460414T020000
RDATE:19470406T030000
RDATE:19480418T020000
RDATE:19490410T020000
RDATE:19800406T020000
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19161001T010000
RDATE:19421102T030000
RDATE:19431004T030000
RDATE:19441002T030000
RDATE:19451118T030000
RDATE:19461007T030000
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19170416T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=3MO;UNTIL=19180415T010000Z
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19170917T030000
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=3MO;UNTIL=19180916T010000Z
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19440403T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1MO;UNTIL=19450402T010000Z
END:DAYLIGHT
BEGIN:DAYLIGHT
TZNAME:CEMT
TZOFFSETFROM:+0200
TZOFFSETTO:+0300
DTSTART:19450524T020000
RDATE:19470511T030000
END:DAYLIGHT
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0300
TZOFFSETTO:+0200
DTSTART:19450924T030000
RDATE:19470629T030000
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0100
TZOFFSETTO:+0100
DTSTART:19460101T000000
RDATE:19800101T000000
END:STANDARD
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19471005T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=1SU;UNTIL=19491002T010000Z
END:STANDARD
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19800928T030000
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=-1SU;UNTIL=19950924T010000Z
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19810329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19961027T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
END:VCALENDAR
</calendar-timezone>
<timezone-service-set xmlns="urn:ietf:params:xml:ns:caldav">
<href xmlns="DAV:">https://www.iana.org/time-zones</href>
</timezone-service-set>
<calendar-timezone-id xmlns="urn:ietf:params:xml:ns:caldav">Europe/Berlin</calendar-timezone-id>
<calendar-order xmlns="http://apple.com/ns/ical/">0</calendar-order>
<supported-calendar-component-set xmlns="urn:ietf:params:xml:ns:caldav">
<comp xmlns="urn:ietf:params:xml:ns:caldav" name="VEVENT"/>
<comp xmlns="urn:ietf:params:xml:ns:caldav" name="VTODO"/>
</supported-calendar-component-set>
<supported-calendar-data xmlns="urn:ietf:params:xml:ns:caldav">
<calendar-data xmlns="urn:ietf:params:xml:ns:caldav" content-type="text/calendar" version="2.0"/>
</supported-calendar-data>
<supported-collation-set xmlns="urn:ietf:params:xml:ns:caldav">
<supported-collation xmlns="urn:ietf:params:xml:ns:caldav">i;ascii-casemap</supported-collation>
<supported-collation xmlns="urn:ietf:params:xml:ns:caldav">i;unicode-casemap</supported-collation>
<supported-collation xmlns="urn:ietf:params:xml:ns:caldav">i;octet</supported-collation>
</supported-collation-set>
<max-resource-size xmlns="urn:ietf:params:xml:ns:caldav">10000000</max-resource-size>
<supported-report-set xmlns="DAV:">
<supported-report xmlns="DAV:">
<report xmlns="DAV:">
<calendar-query xmlns="urn:ietf:params:xml:ns:caldav"/>
</report>
</supported-report>
<supported-report xmlns="DAV:">
<report xmlns="DAV:">
<calendar-multiget xmlns="urn:ietf:params:xml:ns:caldav"/>
</report>
</supported-report>
<supported-report xmlns="DAV:">
<report xmlns="DAV:">
<sync-collection xmlns="DAV:"/>
</report>
</supported-report>
</supported-report-set>
<min-date-time xmlns="urn:ietf:params:xml:ns:caldav">-2621430101T000000Z</min-date-time>
<max-date-time xmlns="urn:ietf:params:xml:ns:caldav">+2621421231T235959Z</max-date-time>
<sync-token xmlns="DAV:">github.com/lennart-k/rustical/ns/12</sync-token>
<getctag xmlns="http://calendarserver.org/ns/">github.com/lennart-k/rustical/ns/12</getctag>
<transports xmlns="https://bitfire.at/webdav-push">
<web-push xmlns="https://bitfire.at/webdav-push"/>
</transports>
<topic xmlns="https://bitfire.at/webdav-push">b28b41e9-8801-4fc5-ae29-8efb5fadeb36</topic>
<supported-triggers xmlns="https://bitfire.at/webdav-push">
<content-update xmlns="https://bitfire.at/webdav-push">
<depth xmlns="DAV:">1</depth>
</content-update>
<property-update xmlns="https://bitfire.at/webdav-push">
<depth xmlns="DAV:">1</depth>
</property-update>
</supported-triggers>
<resourcetype xmlns="DAV:">
<collection xmlns="DAV:"/>
<calendar xmlns="urn:ietf:params:xml:ns:caldav"/>
</resourcetype>
<displayname xmlns="DAV:">Calendar</displayname>
<current-user-principal xmlns="DAV:">
<href xmlns="DAV:">/caldav/principal/user/</href>
</current-user-principal>
<current-user-privilege-set xmlns="DAV:">
<privilege>
<read/>
</privilege>
<privilege>
<write-properties/>
</privilege>
<privilege>
<read-acl/>
</privilege>
<privilege>
<read-current-user-privilege-set/>
</privilege>
</current-user-privilege-set>
<owner xmlns="DAV:">
<href xmlns="DAV:">/caldav/principal/user/</href>
</owner>
</prop>
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
</propstat>
</response>

View File

@@ -0,0 +1,37 @@
---
source: crates/caldav/src/calendar/tests.rs
expression: output
---
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="DAV:">
<href>/caldav/principal/user/calendar/</href>
<propstat>
<prop xmlns="DAV:">
<calendar-color xmlns="http://apple.com/ns/ical/"/>
<calendar-description xmlns="urn:ietf:params:xml:ns:caldav"/>
<calendar-timezone xmlns="urn:ietf:params:xml:ns:caldav"/>
<timezone-service-set xmlns="urn:ietf:params:xml:ns:caldav"/>
<calendar-timezone-id xmlns="urn:ietf:params:xml:ns:caldav"/>
<calendar-order xmlns="http://apple.com/ns/ical/"/>
<supported-calendar-component-set xmlns="urn:ietf:params:xml:ns:caldav"/>
<supported-calendar-data xmlns="urn:ietf:params:xml:ns:caldav"/>
<supported-collation-set xmlns="urn:ietf:params:xml:ns:caldav"/>
<max-resource-size xmlns="urn:ietf:params:xml:ns:caldav"/>
<supported-report-set xmlns="DAV:"/>
<source xmlns="http://calendarserver.org/ns/"/>
<min-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
<max-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
<sync-token xmlns="DAV:"/>
<getctag xmlns="http://calendarserver.org/ns/"/>
<transports xmlns="https://bitfire.at/webdav-push"/>
<topic xmlns="https://bitfire.at/webdav-push"/>
<supported-triggers xmlns="https://bitfire.at/webdav-push"/>
<resourcetype xmlns="DAV:"/>
<displayname xmlns="DAV:"/>
<current-user-principal xmlns="DAV:"/>
<current-user-privilege-set xmlns="DAV:"/>
<owner xmlns="DAV:"/>
</prop>
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
</propstat>
</response>

View File

@@ -1,222 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CARD="urn:ietf:params:xml:ns:carddav" xmlns:CS="http://calendarserver.org/ns/" xmlns:PUSH="https://bitfire.at/webdav-push">
<href>/caldav/principal/user/calendar/</href>
<propstat>
<prop>
<calendar-color xmlns="http://apple.com/ns/ical/"/>
<calendar-description xmlns="urn:ietf:params:xml:ns:caldav"/>
<calendar-timezone xmlns="urn:ietf:params:xml:ns:caldav"/>
<timezone-service-set xmlns="urn:ietf:params:xml:ns:caldav"/>
<calendar-timezone-id xmlns="urn:ietf:params:xml:ns:caldav"/>
<calendar-order xmlns="http://apple.com/ns/ical/"/>
<supported-calendar-component-set xmlns="urn:ietf:params:xml:ns:caldav"/>
<supported-calendar-data xmlns="urn:ietf:params:xml:ns:caldav"/>
<max-resource-size xmlns="DAV:"/>
<supported-report-set xmlns="DAV:"/>
<source xmlns="http://calendarserver.org/ns/"/>
<min-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
<max-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
<sync-token xmlns="DAV:"/>
<getctag xmlns="http://calendarserver.org/ns/"/>
<transports xmlns="https://bitfire.at/webdav-push"/>
<topic xmlns="https://bitfire.at/webdav-push"/>
<supported-triggers xmlns="https://bitfire.at/webdav-push"/>
<resourcetype xmlns="DAV:"/>
<displayname xmlns="DAV:"/>
<current-user-principal xmlns="DAV:"/>
<current-user-privilege-set xmlns="DAV:"/>
<owner xmlns="DAV:"/>
</prop>
<status>HTTP/1.1 200 OK</status>
</propstat>
</response>
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CARD="urn:ietf:params:xml:ns:carddav" xmlns:CS="http://calendarserver.org/ns/" xmlns:PUSH="https://bitfire.at/webdav-push">
<href>/caldav/principal/user/calendar/</href>
<propstat>
<prop>
<CAL:calendar-timezone>BEGIN:VCALENDAR
PRODID:-//github.com/lennart-k/vzic-rs//RustiCal Calendar server//EN
VERSION:2.0
BEGIN:VTIMEZONE
TZID:Europe/Berlin
LAST-MODIFIED:20250723T190331Z
X-LIC-LOCATION:Europe/Berlin
X-PROLEPTIC-TZNAME:LMT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+005328
TZOFFSETTO:+0100
DTSTART:18930401T000000
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19160430T230000
RDATE:19400401T020000
RDATE:19430329T020000
RDATE:19460414T020000
RDATE:19470406T030000
RDATE:19480418T020000
RDATE:19490410T020000
RDATE:19800406T020000
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19161001T010000
RDATE:19421102T030000
RDATE:19431004T030000
RDATE:19441002T030000
RDATE:19451118T030000
RDATE:19461007T030000
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19170416T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=3MO;UNTIL=19180415T010000Z
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19170917T030000
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=3MO;UNTIL=19180916T010000Z
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19440403T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1MO;UNTIL=19450402T010000Z
END:DAYLIGHT
BEGIN:DAYLIGHT
TZNAME:CEMT
TZOFFSETFROM:+0200
TZOFFSETTO:+0300
DTSTART:19450524T020000
RDATE:19470511T030000
END:DAYLIGHT
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0300
TZOFFSETTO:+0200
DTSTART:19450924T030000
RDATE:19470629T030000
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0100
TZOFFSETTO:+0100
DTSTART:19460101T000000
RDATE:19800101T000000
END:STANDARD
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19471005T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=1SU;UNTIL=19491002T010000Z
END:STANDARD
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19800928T030000
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=-1SU;UNTIL=19950924T010000Z
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19810329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19961027T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
END:VCALENDAR
</CAL:calendar-timezone>
<CAL:timezone-service-set>
<href>https://www.iana.org/time-zones</href>
</CAL:timezone-service-set>
<CAL:calendar-timezone-id>Europe/Berlin</CAL:calendar-timezone-id>
<calendar-order xmlns="http://apple.com/ns/ical/">0</calendar-order>
<CAL:supported-calendar-component-set>
<CAL:comp name="VEVENT"/>
<CAL:comp name="VTODO"/>
</CAL:supported-calendar-component-set>
<CAL:supported-calendar-data>
<CAL:calendar-data content-type="text/calendar" version="2.0"/>
</CAL:supported-calendar-data>
<max-resource-size>10000000</max-resource-size>
<supported-report-set>
<supported-report>
<report>
<CAL:calendar-query/>
</report>
</supported-report>
<supported-report>
<report>
<CAL:calendar-multiget/>
</report>
</supported-report>
<supported-report>
<report>
<sync-collection/>
</report>
</supported-report>
</supported-report-set>
<CAL:min-date-time>-2621430101T000000Z</CAL:min-date-time>
<CAL:max-date-time>+2621421231T235959Z</CAL:max-date-time>
<sync-token>github.com/lennart-k/rustical/ns/12</sync-token>
<CS:getctag>github.com/lennart-k/rustical/ns/12</CS:getctag>
<PUSH:transports>
<PUSH:web-push/>
</PUSH:transports>
<PUSH:topic>b28b41e9-8801-4fc5-ae29-8efb5fadeb36</PUSH:topic>
<PUSH:supported-triggers>
<PUSH:content-update>
<depth>1</depth>
</PUSH:content-update>
<PUSH:property-update>
<depth>1</depth>
</PUSH:property-update>
</PUSH:supported-triggers>
<resourcetype>
<collection/>
<CAL:calendar/>
</resourcetype>
<displayname>Calendar</displayname>
<current-user-principal>
<href>/caldav/principal/user/</href>
</current-user-principal>
<current-user-privilege-set>
<privilege>
<read/>
</privilege>
<privilege>
<read-acl/>
</privilege>
<privilege>
<read-current-user-privilege-set/>
</privilege>
</current-user-privilege-set>
<owner>
<href>/caldav/principal/user/</href>
</owner>
</prop>
<status>HTTP/1.1 200 OK</status>
</propstat>
</response>

View File

@@ -14,14 +14,9 @@ async fn test_propfind() {
from_str(include_str!("./test_files/propfind.principals.json")).unwrap();
let resources: Vec<CalendarResource> =
from_str(include_str!("./test_files/propfind.resources.json")).unwrap();
let outputs: Vec<_> = include_str!("./test_files/propfind.outputs")
.trim()
.split("\n\n")
.collect();
for principal in principals {
for ((request, resource), &expected_output) in requests.iter().zip(&resources).zip(&outputs)
{
for (request, resource) in requests.iter().zip(&resources) {
let propfind = CalendarResource::parse_propfind(request).unwrap();
let response = resource
@@ -33,15 +28,12 @@ async fn test_propfind() {
&principal,
)
.unwrap();
let expected_output = expected_output.trim();
let output = response
.serialize_to_string()
.unwrap()
.trim()
.replace("\r\n", "\n");
println!("{output}");
println!("{}, {} \n\n\n", output.len(), expected_output.len());
assert_eq!(output, expected_output);
insta::assert_snapshot!(output);
}
}
}

View File

@@ -5,13 +5,14 @@ use axum::body::Body;
use axum::extract::{Path, State};
use axum::response::{IntoResponse, Response};
use axum_extra::TypedHeader;
use caldata::parser::ParserOptions;
use headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
use http::{HeaderMap, Method, StatusCode};
use http::{HeaderMap, HeaderValue, Method, StatusCode};
use rustical_ical::CalendarObject;
use rustical_store::CalendarStore;
use rustical_store::auth::Principal;
use std::str::FromStr;
use tracing::{debug, error, instrument};
use tracing::{instrument, warn};
#[instrument(skip(cal_store))]
pub async fn get_event<C: CalendarStore>(
@@ -20,7 +21,10 @@ pub async fn get_event<C: CalendarStore>(
calendar_id,
object_id,
}): Path<CalendarObjectPathComponents>,
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
State(CalendarObjectResourceService {
cal_store,
config: _,
}): State<CalendarObjectResourceService<C>>,
user: Principal,
method: Method,
) -> Result<Response, Error> {
@@ -42,7 +46,7 @@ pub async fn get_event<C: CalendarStore>(
let mut resp = Response::builder().status(StatusCode::OK);
let hdrs = resp.headers_mut().unwrap();
hdrs.typed_insert(ETag::from_str(&event.get_etag()).unwrap());
hdrs.typed_insert(ContentType::from_str("text/calendar").unwrap());
hdrs.typed_insert(ContentType::from_str("text/calendar; charset=utf-8").unwrap());
if matches!(method, Method::HEAD) {
Ok(resp.body(Body::empty()).unwrap())
} else {
@@ -57,7 +61,9 @@ pub async fn put_event<C: CalendarStore>(
calendar_id,
object_id,
}): Path<CalendarObjectPathComponents>,
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
State(CalendarObjectResourceService { cal_store, config }): State<
CalendarObjectResourceService<C>,
>,
user: Principal,
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
header_map: HeaderMap,
@@ -73,29 +79,49 @@ pub async fn put_event<C: CalendarStore>(
}
let overwrite = if let Some(TypedHeader(if_none_match)) = if_none_match {
if_none_match == IfNoneMatch::any()
// TODO: Put into transaction?
let existing = match cal_store
.get_object(&principal, &calendar_id, &object_id, false)
.await
{
Ok(existing) => Some(existing),
Err(rustical_store::Error::NotFound) => None,
Err(err) => Err(err)?,
};
existing.is_none_or(|existing| {
if_none_match.precondition_passes(
&existing
.get_etag()
.parse()
.expect("We only generate valid ETags"),
)
})
} else {
true
};
let object = match CalendarObject::from_ics(body.clone()) {
Ok(obj) => obj,
Err(_) => {
debug!("invalid calendar data:\n{body}");
let object = match CalendarObject::import(
&body,
Some(ParserOptions {
rfc7809: config.rfc7809,
}),
) {
Ok(object) => object,
Err(err) => {
warn!("invalid calendar data:\n{body}");
warn!("{err}");
return Err(Error::PreconditionFailed(Precondition::ValidCalendarData));
}
};
if object.get_id() != object_id {
error!(
"Calendar object UID and file name not matching: UID={}, filename={}",
object.get_id(),
object_id
);
return Err(Error::PreconditionFailed(Precondition::MatchingUid));
}
let etag = object.get_etag();
cal_store
.put_object(principal, calendar_id, object, overwrite)
.put_object(&principal, &calendar_id, &object_id, object, overwrite)
.await?;
Ok(StatusCode::CREATED.into_response())
let mut headers = HeaderMap::new();
headers.insert(
"ETag",
HeaderValue::from_str(&etag).expect("Contains no invalid characters"),
);
Ok((StatusCode::CREATED, headers).into_response())
}

View File

@@ -1,8 +1,8 @@
use rustical_dav::extensions::CommonPropertiesProp;
use rustical_ical::UtcDateTime;
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
use rustical_xml::{EnumVariants, PropName, Unparsed, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
#[xml(unit_variants_ident = "CalendarObjectPropName")]
pub enum CalendarObjectProp {
// WebDAV (RFC 2518)
@@ -17,7 +17,7 @@ pub enum CalendarObjectProp {
CalendarData(String),
}
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
#[xml(unit_variants_ident = "CalendarObjectPropWrapperName", untagged)]
pub enum CalendarObjectPropWrapper {
CalendarObject(CalendarObjectProp),
@@ -25,7 +25,7 @@ pub enum CalendarObjectPropWrapper {
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ExpandElement {
pub struct ExpandElement {
#[xml(ty = "attr")]
pub(crate) start: UtcDateTime,
#[xml(ty = "attr")]
@@ -35,7 +35,9 @@ pub(crate) struct ExpandElement {
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Default, Eq, Hash)]
pub struct CalendarData {
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) comp: Option<()>,
pub(crate) comp: Option<Unparsed>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) prop: Option<Unparsed>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
pub(crate) expand: Option<ExpandElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]

View File

@@ -1,5 +1,9 @@
use super::prop::*;
use super::prop::{
CalendarData, CalendarObjectProp, CalendarObjectPropName, CalendarObjectPropWrapper,
CalendarObjectPropWrapperName,
};
use crate::Error;
use caldata::generator::Emitter;
use derive_more::derive::{From, Into};
use rustical_dav::{
extensions::CommonPropertiesExtension,
@@ -9,16 +13,18 @@ use rustical_dav::{
};
use rustical_ical::CalendarObject;
use rustical_store::auth::Principal;
use std::borrow::Cow;
#[derive(Clone, From, Into)]
pub struct CalendarObjectResource {
pub object: CalendarObject,
pub object_id: String,
pub principal: String,
}
impl ResourceName for CalendarObjectResource {
fn get_name(&self) -> String {
format!("{}.ics", self.object.get_id())
fn get_name(&self) -> Cow<'_, str> {
Cow::from(format!("{}.ics", self.object_id))
}
}
@@ -48,14 +54,18 @@ impl Resource for CalendarObjectResource {
CalendarObjectProp::Getetag(self.object.get_etag())
}
CalendarObjectPropName::CalendarData(CalendarData { expand, .. }) => {
CalendarObjectProp::CalendarData(if let Some(expand) = expand.as_ref() {
self.object.expand_recurrence(
CalendarObjectProp::CalendarData(expand.as_ref().map_or_else(
|| self.object.get_ics().to_owned(),
|expand| {
self.object
.get_inner()
.expand_recurrence(
Some(expand.start.to_utc()),
Some(expand.end.to_utc()),
)?
} else {
self.object.get_ics().to_owned()
})
)
.generate()
},
))
}
CalendarObjectPropName::Getcontenttype => {
CalendarObjectProp::Getcontenttype("text/calendar;charset=utf-8")

View File

@@ -1,5 +1,5 @@
use crate::{
CalDavPrincipalUri, Error,
CalDavConfig, CalDavPrincipalUri, Error,
calendar_object::{
methods::{get_event, put_event},
resource::CalendarObjectResource,
@@ -24,19 +24,21 @@ pub struct CalendarObjectPathComponents {
pub struct CalendarObjectResourceService<C: CalendarStore> {
pub(crate) cal_store: Arc<C>,
pub(crate) config: Arc<CalDavConfig>,
}
impl<C: CalendarStore> Clone for CalendarObjectResourceService<C> {
fn clone(&self) -> Self {
Self {
cal_store: self.cal_store.clone(),
config: self.config.clone(),
}
}
}
impl<C: CalendarStore> CalendarObjectResourceService<C> {
pub fn new(cal_store: Arc<C>) -> Self {
Self { cal_store }
pub const fn new(cal_store: Arc<C>, config: Arc<CalDavConfig>) -> Self {
Self { cal_store, config }
}
}
@@ -66,6 +68,7 @@ impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
.await?;
Ok(CalendarObjectResource {
object,
object_id: object_id.to_owned(),
principal: principal.to_owned(),
})
}
@@ -106,9 +109,8 @@ where
D: Deserializer<'de>,
{
let name: String = Deserialize::deserialize(deserializer)?;
if let Some(object_id) = name.strip_suffix(".ics") {
Ok(object_id.to_owned())
} else {
Err(serde::de::Error::custom("Missing .ics extension"))
}
name.strip_suffix(".ics").map_or_else(
|| Err(serde::de::Error::custom("Missing .ics extension")),
|object_id| Ok(object_id.to_owned()),
)
}

View File

@@ -12,8 +12,9 @@ pub enum Precondition {
#[error("valid-calendar-data")]
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
ValidCalendarData,
#[error("matching-uid")]
MatchingUid,
#[error("calendar-timezone")]
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
CalendarTimezone(&'static str),
}
impl IntoResponse for Precondition {
@@ -25,7 +26,7 @@ impl IntoResponse for Precondition {
if let Err(err) = error.serialize_root(&mut writer) {
return rustical_dav::Error::from(err).into_response();
}
let mut res = Response::builder().status(StatusCode::PRECONDITION_FAILED);
let mut res = Response::builder().status(StatusCode::FORBIDDEN);
res.headers_mut().unwrap().typed_insert(ContentType::xml());
res.body(Body::from(output)).unwrap()
}
@@ -54,41 +55,40 @@ pub enum Error {
#[error(transparent)]
XmlDecodeError(#[from] rustical_xml::XmlError),
#[error(transparent)]
IcalError(#[from] rustical_ical::Error),
#[error(transparent)]
PreconditionFailed(Precondition),
}
impl Error {
#[must_use]
pub fn status_code(&self) -> StatusCode {
match self {
Error::StoreError(err) => match err {
Self::StoreError(err) => match err {
rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
rustical_store::Error::AlreadyExists => StatusCode::CONFLICT,
rustical_store::Error::ReadOnly => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR,
},
Error::ChronoParseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
Error::DavError(err) => StatusCode::try_from(err.status_code().as_u16())
Self::DavError(err) => StatusCode::try_from(err.status_code().as_u16())
.expect("Just converting between versions"),
Error::Unauthorized => StatusCode::UNAUTHORIZED,
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
Error::NotFound => StatusCode::NOT_FOUND,
Error::IcalError(err) => err.status_code(),
Error::PreconditionFailed(_err) => StatusCode::PRECONDITION_FAILED,
Self::Unauthorized => StatusCode::UNAUTHORIZED,
Self::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
Self::ChronoParseError(_) | Self::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
Self::NotFound => StatusCode::NOT_FOUND,
// The correct status code for a failed precondition is not PreconditionFailed but
// Forbidden (or Conflict):
// https://datatracker.ietf.org/doc/html/rfc4791#section-1.3
Self::PreconditionFailed(_err) => StatusCode::FORBIDDEN,
}
}
}
impl IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
if matches!(
self.status_code(),
StatusCode::INTERNAL_SERVER_ERROR | StatusCode::PRECONDITION_FAILED
) {
if let Self::PreconditionFailed(precondition) = self {
return precondition.into_response();
}
if matches!(self.status_code(), StatusCode::INTERNAL_SERVER_ERROR) {
error!("{self}");
}
(self.status_code(), self.to_string()).into_response()

View File

@@ -1,3 +1,5 @@
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]
use axum::{Extension, Router};
use derive_more::Constructor;
use principal::PrincipalResourceService;
@@ -6,6 +8,7 @@ use rustical_dav::resources::RootResourceService;
use rustical_store::auth::middleware::AuthenticationLayer;
use rustical_store::auth::{AuthenticationProvider, Principal};
use rustical_store::{CalendarStore, SubscriptionStore};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
pub mod calendar;
@@ -32,17 +35,36 @@ pub fn caldav_router<AP: AuthenticationProvider, C: CalendarStore, S: Subscripti
store: Arc<C>,
subscription_store: Arc<S>,
simplified_home_set: bool,
config: Arc<CalDavConfig>,
) -> Router {
Router::new().nest(
prefix,
RootResourceService::<_, Principal, CalDavPrincipalUri>::new(PrincipalResourceService {
auth_provider: auth_provider.clone(),
sub_store: subscription_store.clone(),
cal_store: store.clone(),
sub_store: subscription_store,
cal_store: store,
simplified_home_set,
config,
})
.axum_router()
.layer(AuthenticationLayer::new(auth_provider))
.layer(Extension(CalDavPrincipalUri(prefix))),
)
}
const fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct CalDavConfig {
#[serde(default = "default_true")]
rfc7809: bool,
}
impl Default for CalDavConfig {
fn default() -> Self {
Self { rfc7809: true }
}
}

View File

@@ -6,6 +6,7 @@ use rustical_dav::xml::{
GroupMemberSet, GroupMembership, Resourcetype, ResourcetypeInner, SupportedReportSet,
};
use rustical_store::auth::Principal;
use std::borrow::Cow;
mod service;
pub use service::*;
@@ -23,8 +24,8 @@ pub struct PrincipalResource {
}
impl ResourceName for PrincipalResource {
fn get_name(&self) -> String {
self.principal.id.to_owned()
fn get_name(&self) -> Cow<'_, str> {
Cow::from(&self.principal.id)
}
}
@@ -56,7 +57,7 @@ impl Resource for PrincipalResource {
PrincipalPropWrapperName::Principal(prop) => {
PrincipalPropWrapper::Principal(match prop {
PrincipalPropName::CalendarUserType => {
PrincipalProp::CalendarUserType(self.principal.principal_type.to_owned())
PrincipalProp::CalendarUserType(self.principal.principal_type.clone())
}
PrincipalPropName::PrincipalUrl => {
PrincipalProp::PrincipalUrl(principal_url.into())

View File

@@ -6,7 +6,7 @@ use rustical_store::auth::PrincipalType;
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
use strum_macros::VariantArray;
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "PrincipalPropName")]
pub enum PrincipalProp {
// Scheduling Extensions to CalDAV (RFC 6638)
@@ -34,17 +34,17 @@ pub enum PrincipalProp {
CalendarHomeSet(CalendarHomeSet),
}
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, Debug)]
pub struct CalendarHomeSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
pub enum PrincipalPropWrapper {
Principal(PrincipalProp),
Common(CommonPropertiesProp),
}
#[derive(XmlSerialize, PartialEq, Clone, VariantArray)]
#[derive(XmlSerialize, PartialEq, Eq, Debug, Clone, VariantArray)]
pub enum ReportMethod {
// We don't actually support principal-match
#[xml(ns = "rustical_dav::namespace::NS_DAV")]

View File

@@ -1,7 +1,7 @@
use crate::calendar::CalendarResourceService;
use crate::calendar::resource::CalendarResource;
use crate::principal::PrincipalResource;
use crate::{CalDavPrincipalUri, Error};
use crate::{CalDavConfig, CalDavPrincipalUri, Error};
use async_trait::async_trait;
use axum::Router;
use rustical_dav::resource::{AxumMethods, ResourceService};
@@ -20,6 +20,7 @@ pub struct PrincipalResourceService<
pub(crate) cal_store: Arc<CS>,
// If true only return the principal as the calendar home set, otherwise also groups
pub(crate) simplified_home_set: bool,
pub(crate) config: Arc<CalDavConfig>,
}
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> Clone
@@ -31,6 +32,7 @@ impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> Clone
sub_store: self.sub_store.clone(),
cal_store: self.cal_store.clone(),
simplified_home_set: self.simplified_home_set,
config: self.config.clone(),
}
}
}
@@ -84,7 +86,11 @@ impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> Resour
Router::new()
.nest(
"/{calendar_id}",
CalendarResourceService::new(self.cal_store.clone(), self.sub_store.clone())
CalendarResourceService::new(
self.cal_store.clone(),
self.sub_store.clone(),
self.config.clone(),
)
.axum_router(),
)
.route_service("/", self.axum_service())

View File

@@ -0,0 +1,136 @@
---
source: crates/caldav/src/principal/tests.rs
expression: response
---
ResponseElement {
href: "/caldav/principal/user/",
status: None,
propstat: [
Normal(
PropstatElement {
prop: PropTagWrapper(
[
Principal(
CalendarUserType(
Individual,
),
),
Principal(
CalendarUserAddressSet(
HrefElement {
href: "/caldav/principal/user/",
},
),
),
Principal(
PrincipalUrl(
HrefElement {
href: "/caldav/principal/user/",
},
),
),
Principal(
GroupMembership(
GroupMembership(
[
HrefElement {
href: "/caldav/principal/group/",
},
],
),
),
),
Principal(
GroupMemberSet(
GroupMemberSet(
[],
),
),
),
Principal(
AlternateUriSet,
),
Principal(
SupportedReportSet(
SupportedReportSet {
supported_report: [
ReportWrapper {
report: PrincipalMatch,
},
],
},
),
),
Principal(
CalendarHomeSet(
CalendarHomeSet(
[
HrefElement {
href: "/caldav/principal/group/",
},
HrefElement {
href: "/caldav/principal/user/",
},
],
),
),
),
Common(
Resourcetype(
Resourcetype(
[
ResourcetypeInner(
Some(
Namespace("DAV:"),
),
"collection",
),
ResourcetypeInner(
Some(
Namespace("DAV:"),
),
"principal",
),
],
),
),
),
Common(
Displayname(
Some(
"user",
),
),
),
Common(
CurrentUserPrincipal(
HrefElement {
href: "/caldav/principal/user/",
},
),
),
Common(
CurrentUserPrivilegeSet(
UserPrivilegeSet {
privileges: {
All,
},
},
),
),
Common(
Owner(
Some(
HrefElement {
href: "/caldav/principal/user/",
},
),
),
),
],
),
status: 200,
},
),
],
}

View File

@@ -0,0 +1,53 @@
---
source: crates/caldav/src/principal/tests.rs
expression: response.serialize_to_string().unwrap()
---
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="DAV:">
<href>/caldav/principal/user/</href>
<propstat>
<prop xmlns="DAV:">
<calendar-user-type xmlns="urn:ietf:params:xml:ns:caldav">INDIVIDUAL</calendar-user-type>
<calendar-user-address-set xmlns="urn:ietf:params:xml:ns:caldav">
<href xmlns="DAV:">/caldav/principal/user/</href>
</calendar-user-address-set>
<principal-URL xmlns="DAV:">
<href xmlns="DAV:">/caldav/principal/user/</href>
</principal-URL>
<group-membership xmlns="DAV:">
<href xmlns="DAV:">/caldav/principal/group/</href>
</group-membership>
<group-member-set xmlns="DAV:">
</group-member-set>
<alternate-URI-set xmlns="DAV:"/>
<supported-report-set xmlns="DAV:">
<supported-report xmlns="DAV:">
<report xmlns="DAV:">
<principal-match xmlns="DAV:"/>
</report>
</supported-report>
</supported-report-set>
<calendar-home-set xmlns="urn:ietf:params:xml:ns:caldav">
<href xmlns="DAV:">/caldav/principal/group/</href>
<href xmlns="DAV:">/caldav/principal/user/</href>
</calendar-home-set>
<resourcetype xmlns="DAV:">
<collection xmlns="DAV:"/>
<principal xmlns="DAV:"/>
</resourcetype>
<displayname xmlns="DAV:">user</displayname>
<current-user-principal xmlns="DAV:">
<href xmlns="DAV:">/caldav/principal/user/</href>
</current-user-principal>
<current-user-privilege-set xmlns="DAV:">
<privilege>
<all/>
</privilege>
</current-user-privilege-set>
<owner xmlns="DAV:">
<href xmlns="DAV:">/caldav/principal/user/</href>
</owner>
</prop>
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
</propstat>
</response>

View File

@@ -0,0 +1,8 @@
---
source: crates/caldav/src/principal/tests.rs
expression: propfind
---
PropfindElement {
prop: Allprop,
include: None,
}

View File

@@ -1,5 +1,3 @@
use std::sync::Arc;
use crate::{
CalDavPrincipalUri,
principal::{PrincipalResource, PrincipalResourceService},
@@ -7,32 +5,29 @@ use crate::{
use rstest::rstest;
use rustical_dav::resource::{Resource, ResourceService};
use rustical_store::auth::{Principal, PrincipalType::Individual};
use rustical_store_sqlite::{
SqliteStore,
calendar_store::SqliteCalendarStore,
principal_store::SqlitePrincipalStore,
tests::{get_test_calendar_store, get_test_principal_store, get_test_subscription_store},
};
use rustical_store_sqlite::tests::{TestStoreContext, test_store_context};
use rustical_xml::XmlSerializeRoot;
use std::sync::Arc;
#[rstest]
#[tokio::test]
async fn test_principal_resource(
#[from(get_test_calendar_store)]
#[future]
cal_store: SqliteCalendarStore,
#[from(get_test_principal_store)]
#[future]
auth_provider: SqlitePrincipalStore,
#[from(get_test_subscription_store)]
#[future]
sub_store: SqliteStore,
#[from(test_store_context)]
context: TestStoreContext,
) {
let TestStoreContext {
cal_store,
sub_store,
principal_store: auth_provider,
..
} = context.await;
let service = PrincipalResourceService {
cal_store: Arc::new(cal_store.await),
sub_store: Arc::new(sub_store.await),
auth_provider: Arc::new(auth_provider.await),
cal_store: Arc::new(cal_store),
sub_store: Arc::new(sub_store),
auth_provider: Arc::new(auth_provider),
simplified_home_set: false,
config: Default::default(),
};
// We don't have any calendars here
@@ -64,6 +59,8 @@ async fn test_propfind() {
)
.unwrap();
insta::assert_debug_snapshot!(propfind);
let principal = Principal {
id: "user".to_string(),
displayname: None,
@@ -88,5 +85,6 @@ async fn test_propfind() {
)
.unwrap();
let _output = response.serialize_to_string().unwrap();
insta::assert_debug_snapshot!(response);
insta::assert_snapshot!(response.serialize_to_string().unwrap());
}

View File

@@ -1,6 +1,7 @@
[package]
name = "rustical_carddav"
version.workspace = true
rust-version.workspace = true
edition.workspace = true
description.workspace = true
repository.workspace = true
@@ -11,19 +12,19 @@ publish = false
axum.workspace = true
axum-extra.workspace = true
tower.workspace = true
async-trait = { workspace = true }
thiserror = { workspace = true }
quick-xml = { workspace = true }
tracing = { workspace = true }
futures-util = { workspace = true }
derive_more = { workspace = true }
base64 = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true }
url = { workspace = true }
rustical_dav = { workspace = true }
rustical_store = { workspace = true }
chrono = { workspace = true }
async-trait.workspace = true
thiserror.workspace = true
quick-xml.workspace = true
tracing.workspace = true
futures-util.workspace = true
derive_more.workspace = true
base64.workspace = true
serde.workspace = true
tokio.workspace = true
url.workspace = true
rustical_dav = { workspace = true, features = ["ical"] }
rustical_store.workspace = true
chrono.workspace = true
rustical_xml.workspace = true
uuid.workspace = true
rustical_dav_push.workspace = true
@@ -31,6 +32,10 @@ rustical_ical.workspace = true
http.workspace = true
tower-http.workspace = true
percent-encoding.workspace = true
ical.workspace = true
caldata.workspace = true
strum.workspace = true
strum_macros.workspace = true
rstest.workspace = true
[dev-dependencies]
insta.workspace = true

View File

@@ -7,6 +7,7 @@ use axum::extract::{Path, State};
use axum::response::{IntoResponse, Response};
use axum_extra::TypedHeader;
use axum_extra::headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
use http::HeaderValue;
use http::Method;
use http::{HeaderMap, StatusCode};
use rustical_dav::privileges::UserPrivilege;
@@ -50,7 +51,7 @@ pub async fn get_object<AS: AddressbookStore>(
let mut resp = Response::builder().status(StatusCode::OK);
let hdrs = resp.headers_mut().unwrap();
hdrs.typed_insert(ETag::from_str(&object.get_etag()).unwrap());
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
hdrs.typed_insert(ContentType::from_str("text/vcard; charset=utf-8").unwrap());
if matches!(method, Method::HEAD) {
Ok(resp.body(Body::empty()).unwrap())
} else {
@@ -81,15 +82,40 @@ pub async fn put_object<AS: AddressbookStore>(
}
let overwrite = if let Some(TypedHeader(if_none_match)) = if_none_match {
if_none_match == IfNoneMatch::any()
// TODO: Put into transaction?
let existing = match addr_store
.get_object(&principal, &addressbook_id, &object_id, false)
.await
{
Ok(existing) => Some(existing),
Err(rustical_store::Error::NotFound) => None,
Err(err) => Err(err)?,
};
existing.is_none_or(|existing| {
if_none_match.precondition_passes(
&existing
.get_etag()
.parse()
.expect("We only generate valid ETags"),
)
})
} else {
true
};
let object = AddressObject::from_vcf(object_id, body)?;
let object = match AddressObject::from_vcf(body) {
Ok(object) => object,
Err(err) => return Ok((StatusCode::BAD_REQUEST, err.to_string()).into_response()),
};
let etag = object.get_etag();
addr_store
.put_object(principal, addressbook_id, object, overwrite)
.put_object(&principal, &addressbook_id, &object_id, object, overwrite)
.await?;
Ok(StatusCode::CREATED.into_response())
let mut headers = HeaderMap::new();
headers.insert(
"ETag",
HeaderValue::from_str(&etag).expect("Contains no invalid characters"),
);
Ok((StatusCode::CREATED, headers).into_response())
}

View File

@@ -1,7 +1,7 @@
use rustical_dav::extensions::CommonPropertiesProp;
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
#[xml(unit_variants_ident = "AddressObjectPropName")]
pub enum AddressObjectProp {
// WebDAV (RFC 2518)
@@ -15,7 +15,7 @@ pub enum AddressObjectProp {
AddressData(String),
}
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
#[xml(unit_variants_ident = "AddressObjectPropWrapperName", untagged)]
pub enum AddressObjectPropWrapper {
AddressObject(AddressObjectProp),

View File

@@ -1,3 +1,5 @@
use std::borrow::Cow;
use crate::{
Error,
address_object::{
@@ -5,6 +7,7 @@ use crate::{
AddressObjectPropWrapperName,
},
};
use caldata::property::VcardFNProperty;
use derive_more::derive::{From, Into};
use rustical_dav::{
extensions::CommonPropertiesExtension,
@@ -19,11 +22,12 @@ use rustical_store::auth::Principal;
pub struct AddressObjectResource {
pub object: AddressObject,
pub principal: String,
pub object_id: String,
}
impl ResourceName for AddressObjectResource {
fn get_name(&self) -> String {
format!("{}.vcf", self.object.get_id())
fn get_name(&self) -> Cow<'_, str> {
Cow::from(format!("{}.vcf", self.object_id))
}
}
@@ -67,7 +71,11 @@ impl Resource for AddressObjectResource {
}
fn get_displayname(&self) -> Option<&str> {
self.object.get_full_name()
self.object
.get_vcard()
.full_name
.first()
.map(|VcardFNProperty(name, _)| name.as_str())
}
fn get_owner(&self) -> Option<&str> {

View File

@@ -57,6 +57,7 @@ impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS>
.await?;
Ok(AddressObjectResource {
object,
object_id: object_id.to_owned(),
principal: principal.to_owned(),
})
}
@@ -98,9 +99,8 @@ where
D: Deserializer<'de>,
{
let name: String = Deserialize::deserialize(deserializer)?;
if let Some(object_id) = name.strip_suffix(".vcf") {
Ok(object_id.to_owned())
} else {
Err(serde::de::Error::custom("Missing .vcf extension"))
}
name.strip_suffix(".vcf").map_or_else(
|| Err(serde::de::Error::custom("Missing .vcf extension")),
|object_id| Ok(object_id.to_owned()),
)
}

View File

@@ -9,7 +9,6 @@ use http::{HeaderValue, Method, StatusCode, header};
use percent_encoding::{CONTROLS, utf8_percent_encode};
use rustical_dav::privileges::UserPrivilege;
use rustical_dav::resource::Resource;
use rustical_ical::AddressObject;
use rustical_store::auth::Principal;
use rustical_store::{AddressbookStore, SubscriptionStore};
use std::str::FromStr;
@@ -40,13 +39,13 @@ pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
let objects = addr_store.get_objects(&principal, &addressbook_id).await?;
let vcf = objects
.iter()
.map(AddressObject::get_vcf)
.map(|(_id, obj)| obj.get_vcf())
.collect::<Vec<_>>()
.join("\r\n");
let mut resp = Response::builder().status(StatusCode::OK);
let hdrs = resp.headers_mut().unwrap();
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
hdrs.typed_insert(ContentType::from_str("text/vcard; charset=utf-8").unwrap());
let filename = format!("{principal}_{addressbook_id}.vcf");
let filename = utf8_percent_encode(&filename, CONTROLS);
hdrs.insert(

View File

@@ -1,16 +1,15 @@
use std::io::BufReader;
use crate::Error;
use crate::addressbook::AddressbookResourceService;
use axum::{
extract::{Path, State},
response::{IntoResponse, Response},
};
use http::StatusCode;
use ical::{
parser::{Component, ComponentMut, vcard},
property::Property,
use caldata::{
VcardParser,
component::{Component, ComponentMut},
parser::{ContentLine, ParserOptions},
};
use http::StatusCode;
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::Principal};
use tracing::instrument;
@@ -25,7 +24,7 @@ pub async fn route_import<AS: AddressbookStore, S: SubscriptionStore>(
return Err(Error::Unauthorized);
}
let parser = vcard::VcardParser::new(BufReader::new(body.as_bytes()));
let parser = VcardParser::from_slice(body.as_bytes());
let mut objects = vec![];
for res in parser {
@@ -33,15 +32,16 @@ pub async fn route_import<AS: AddressbookStore, S: SubscriptionStore>(
let uid = card.get_uid();
if uid.is_none() {
let mut card_mut = card.mutable();
card_mut.set_property(Property {
card_mut.add_content_line(ContentLine {
name: "UID".to_owned(),
value: Some(uuid::Uuid::new_v4().to_string()),
params: None,
params: vec![].into(),
});
card = card_mut.verify().unwrap();
card = card_mut.build(&ParserOptions::default(), None).unwrap();
}
objects.push(card.try_into().unwrap());
// TODO: Make nicer
let uid = card.get_uid().unwrap();
objects.push((uid.to_owned(), card.into()));
}
if objects.is_empty() {

View File

@@ -8,7 +8,7 @@ use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::Pri
use rustical_xml::{XmlDeserialize, XmlDocument, XmlRootTag};
use tracing::instrument;
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
pub struct Resourcetype {
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
addressbook: Option<()>,
@@ -16,7 +16,7 @@ pub struct Resourcetype {
collection: Option<()>,
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
pub struct MkcolAddressbookProp {
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
resourcetype: Option<Resourcetype>,
@@ -27,7 +27,7 @@ pub struct MkcolAddressbookProp {
description: Option<String>,
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
pub struct PropElement<T: XmlDeserialize> {
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
prop: T,
@@ -53,13 +53,13 @@ pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
}
let mut request = MkcolRequest::parse_str(&body)?.set.prop;
if let Some("") = request.displayname.as_deref() {
request.displayname = None
if request.displayname.as_deref() == Some("") {
request.displayname = None;
}
let addressbook = Addressbook {
id: addressbook_id.to_owned(),
principal: principal.to_owned(),
id: addressbook_id.clone(),
principal: principal.clone(),
displayname: request.displayname,
description: request.description,
deleted_at: None,
@@ -127,6 +127,6 @@ mod tests {
}
}
}
)
);
}
}

View File

@@ -45,12 +45,12 @@ pub async fn route_post<AS: AddressbookStore, S: SubscriptionStore>(
};
let subscription = Subscription {
id: sub_id.to_owned(),
id: sub_id.clone(),
push_resource: request
.subscription
.web_push_subscription
.push_resource
.to_owned(),
.clone(),
topic: addressbook_resource.0.push_topic,
expiration: expires.naive_local(),
public_key: request

View File

@@ -13,7 +13,7 @@ use rustical_ical::AddressObject;
use rustical_store::{AddressbookStore, auth::Principal};
use rustical_xml::XmlDeserialize;
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
pub struct AddressbookMultigetRequest {
@@ -29,29 +29,29 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
principal: &str,
addressbook_id: &str,
store: &AS,
) -> Result<(Vec<AddressObject>, Vec<String>), Error> {
) -> Result<(Vec<(String, AddressObject)>, Vec<String>), Error> {
let mut result = vec![];
let mut not_found = vec![];
for href in &addressbook_multiget.href {
if let Some(filename) = href.strip_prefix(path) {
let filename = filename.trim_start_matches("/");
if let Ok(href) = percent_encoding::percent_decode_str(href).decode_utf8()
&& let Some(filename) = href.strip_prefix(path)
{
let filename = filename.trim_start_matches('/');
if let Some(object_id) = filename.strip_suffix(".vcf") {
match store
.get_object(principal, addressbook_id, object_id, false)
.await
{
Ok(object) => result.push(object),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
Ok(object) => result.push((object_id.to_owned(), object)),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_string()),
Err(err) => return Err(err.into()),
};
}
} else {
not_found.push(href.to_owned());
continue;
not_found.push(href.to_string());
}
} else {
not_found.push(href.to_owned());
continue;
}
}
@@ -74,11 +74,12 @@ pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
.await?;
let mut responses = Vec::new();
for object in objects {
let path = format!("{}/{}.vcf", path, object.get_id());
for (object_id, object) in objects {
let path = format!("{path}/{object_id}.vcf");
responses.push(
AddressObjectResource {
object,
object_id,
principal: principal.to_owned(),
}
.propfind(&path, prop, None, puri, user)?,

View File

@@ -0,0 +1,139 @@
use crate::{
address_object::AddressObjectPropWrapperName,
addressbook::methods::report::addressbook_query::PropFilterElement,
};
use caldata::parser::ContentLine;
use derive_more::{From, Into};
use rustical_dav::xml::{PropfindType, TextMatchElement};
use rustical_ical::{AddressObject, UtcDateTime};
use rustical_xml::{ValueDeserialize, XmlDeserialize, XmlRootTag};
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
pub struct TimeRangeElement {
#[xml(ty = "attr")]
pub(crate) start: Option<UtcDateTime>,
#[xml(ty = "attr")]
pub(crate) end: Option<UtcDateTime>,
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.3
pub struct ParamFilterElement {
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
pub(crate) is_not_defined: Option<()>,
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
pub(crate) text_match: Option<TextMatchElement>,
#[xml(ty = "attr")]
pub(crate) name: String,
}
impl ParamFilterElement {
#[must_use]
pub fn match_property(&self, prop: &ContentLine) -> bool {
let Some(param) = prop.params.get_param(&self.name) else {
return self.is_not_defined.is_some();
};
if self.is_not_defined.is_some() {
return false;
}
let Some(text_match) = self.text_match.as_ref() else {
return true;
};
text_match.match_text(param)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Default, From, Into)]
pub struct Allof(pub bool);
impl ValueDeserialize for Allof {
fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
Ok(Self(match val {
"allof" => true,
"anyof" => false,
_ => {
return Err(rustical_xml::XmlError::InvalidVariant(format!(
"Invalid test parameter: {val}"
)));
}
}))
}
}
// <!ELEMENT filter (prop-filter*)>
// <!ATTLIST filter test (anyof | allof) "anyof">
// <!-- test value:
// anyof logical OR for prop-filter matches
// allof logical AND for prop-filter matches -->
#[derive(XmlDeserialize, XmlRootTag, Clone, Debug, PartialEq, Eq)]
#[xml(root = "filter", ns = "rustical_dav::namespace::NS_CARDDAV")]
#[allow(dead_code)]
pub struct FilterElement {
#[xml(ty = "attr", default = "Default::default")]
pub test: Allof,
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
pub(crate) prop_filter: Vec<PropFilterElement>,
}
impl FilterElement {
#[must_use]
pub fn matches(&self, addr_object: &AddressObject) -> bool {
if self.prop_filter.is_empty() {
// Filter empty
return true;
}
let Allof(allof) = self.test;
let mut results = self
.prop_filter
.iter()
.map(|prop_filter| prop_filter.match_component(addr_object));
if allof {
results.all(|x| x)
} else {
results.any(|x| x)
}
}
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
// <!ELEMENT addressbook-query ((DAV:allprop |
// DAV:propname |
// DAV:prop)?, filter, limit?)>
pub struct AddressbookQueryRequest {
#[xml(ty = "untagged")]
pub prop: PropfindType<AddressObjectPropWrapperName>,
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
pub(crate) filter: FilterElement,
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
pub(crate) limit: Option<LimitElement>,
}
// https://datatracker.ietf.org/doc/html/rfc5323#section-5.17
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
pub struct LimitElement {
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
pub nresults: NresultsElement,
}
impl From<u64> for LimitElement {
fn from(value: u64) -> Self {
Self {
nresults: NresultsElement(value),
}
}
}
impl From<LimitElement> for u64 {
fn from(value: LimitElement) -> Self {
value.nresults.0
}
}
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
pub struct NresultsElement(#[xml(ty = "text")] pub u64);

View File

@@ -0,0 +1,22 @@
use crate::Error;
mod elements;
mod prop_filter;
pub use elements::*;
#[allow(unused_imports)]
pub use prop_filter::{PropFilterElement, PropFilterable};
use rustical_ical::AddressObject;
use rustical_store::AddressbookStore;
#[cfg(test)]
mod tests;
pub async fn get_objects_addressbook_query<AS: AddressbookStore>(
addr_query: &AddressbookQueryRequest,
principal: &str,
addressbook_id: &str,
store: &AS,
) -> Result<Vec<(String, AddressObject)>, Error> {
let mut objects = store.get_objects(principal, addressbook_id).await?;
objects.retain(|(_id, object)| addr_query.filter.matches(object));
Ok(objects)
}

View File

@@ -0,0 +1,77 @@
use super::{Allof, ParamFilterElement};
use caldata::{component::Component, parser::ContentLine};
use rustical_dav::xml::TextMatchElement;
use rustical_ical::AddressObject;
use rustical_xml::XmlDeserialize;
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
// <!ELEMENT prop-filter (is-not-defined |
// (text-match*, param-filter*))>
//
// <!ATTLIST prop-filter name CDATA #REQUIRED
// test (anyof | allof) "anyof">
// <!-- name value: a vCard property name (e.g., "NICKNAME")
// test value:
// anyof logical OR for text-match/param-filter matches
// allof logical AND for text-match/param-filter matches -->
pub struct PropFilterElement {
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
pub(crate) is_not_defined: Option<()>,
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
pub(crate) text_match: Vec<TextMatchElement>,
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
pub(crate) param_filter: Vec<ParamFilterElement>,
#[xml(ty = "attr", default = "Default::default")]
pub test: Allof,
#[xml(ty = "attr")]
pub(crate) name: String,
}
impl PropFilterElement {
#[must_use]
pub fn match_property(&self, property: &ContentLine) -> bool {
if self.param_filter.is_empty() && self.text_match.is_empty() {
// Filter empty
return true;
}
let Allof(allof) = self.test;
let text_matches = self
.text_match
.iter()
.map(|text_match| text_match.match_property(property));
let param_matches = self
.param_filter
.iter()
.map(|param_filter| param_filter.match_property(property));
let mut matches = text_matches.chain(param_matches);
if allof {
matches.all(|a| a)
} else {
matches.any(|a| a)
}
}
pub fn match_component(&self, comp: &impl PropFilterable) -> bool {
let mut properties = comp.get_named_properties(&self.name);
if self.is_not_defined.is_some() {
return properties.next().is_none();
}
// The filter matches when one property instance matches
properties.any(|prop| self.match_property(prop))
}
}
pub trait PropFilterable {
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine>;
}
impl PropFilterable for AddressObject {
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine> {
self.get_vcard().get_named_properties(name)
}
}

View File

@@ -0,0 +1,70 @@
use super::FilterElement;
use rstest::rstest;
use rustical_ical::AddressObject;
use rustical_xml::XmlDocument;
const VCF_1: &str = r"BEGIN:VCARD
VERSION:4.0
FN:Simon Perreault
N:Perreault;Simon;;;ing. jr,M.Sc.
BDAY:--0203
GENDER:M
EMAIL;TYPE=work:simon.perreault@viagenie.ca
END:VCARD";
const VCF_2: &str = r"BEGIN:VCARD
VERSION:4.0
N:Gump;Forrest;;Mr.;
FN:Forrest Gump
ORG:Bubba Gump Shrimp Co.
TITLE:Shrimp Man
PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif
TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212
TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212
ADR;TYPE=WORK;PREF=1;LABEL=100 Waters Edge\\nBaytown\\, LA 30314\\nUnited S
tates of America:;;100 Waters Edge;Baytown;LA;30314;United States of Ameri
ca
ADR;TYPE=HOME;LABEL=42 Plantation St.\\nBaytown\\, LA 30314\\nUnited States
of America:;;42 Plantation St.;Baytown;LA;30314;United States of America
EMAIL:forrestgump@example.com
REV:20080424T195243Z
x-qq:21588891
UID:890a9da4-bb6d-4afb-9f32-b5eff6494a53
END:VCARD
";
const FILTER_1: &str = r#"
<?xml version="1.0" encoding="utf-8" ?>
<C:filter xmlns:C="urn:ietf:params:xml:ns:carddav">
<C:prop-filter name="EMAIL" test="allof">
<C:text-match collation="i;ascii-casemap">simon.perreault@viagenie.ca</C:text-match>
<C:param-filter name="TYPE">
<C:text-match match-type="equals" collation="i;unicode-casemap">WORK</C:text-match>
</C:param-filter>
</C:prop-filter>
</C:filter>
"#;
const FILTER_2: &str = r#"
<?xml version="1.0" encoding="utf-8" ?>
<C:filter xmlns:C="urn:ietf:params:xml:ns:carddav">
<C:prop-filter name="EMAIL" test="anyof">
<C:text-match collation="i;ascii-casemap">forrestgump@example.com</C:text-match>
<C:param-filter name="TYPE">
<C:text-match match-type="equals" collation="i;ascii-casemap">WORK</C:text-match>
</C:param-filter>
</C:prop-filter>
</C:filter>
"#;
#[rstest]
#[case(VCF_1, FILTER_1, true)]
#[case(VCF_2, FILTER_1, false)]
#[case(VCF_1, FILTER_2, true)]
#[case(VCF_2, FILTER_2, true)]
fn test_filter(#[case] vcf: &str, #[case] filter: &str, #[case] matches: bool) {
dbg!(vcf);
let obj = AddressObject::from_vcf(vcf.to_owned()).unwrap();
let filter = FilterElement::parse_str(filter).unwrap();
assert_eq!(matches, filter.matches(&obj));
}

View File

@@ -1,6 +1,14 @@
use crate::{
CardDavPrincipalUri, Error, address_object::AddressObjectPropWrapperName,
addressbook::AddressbookResourceService,
CardDavPrincipalUri, Error,
address_object::{
AddressObjectPropWrapper, AddressObjectPropWrapperName, resource::AddressObjectResource,
},
addressbook::{
AddressbookResourceService,
methods::report::addressbook_query::{
AddressbookQueryRequest, get_objects_addressbook_query,
},
},
};
use addressbook_multiget::{AddressbookMultigetRequest, handle_addressbook_multiget};
use axum::{
@@ -8,32 +16,82 @@ use axum::{
extract::{OriginalUri, Path, State},
response::IntoResponse,
};
use rustical_dav::xml::{PropfindType, sync_collection::SyncCollectionRequest};
use http::StatusCode;
use rustical_dav::{
resource::{PrincipalUri, Resource},
xml::{
MultistatusElement, PropfindType, multistatus::ResponseElement,
sync_collection::SyncCollectionRequest,
},
};
use rustical_ical::AddressObject;
use rustical_store::{AddressbookStore, SubscriptionStore, auth::Principal};
use rustical_xml::{XmlDeserialize, XmlDocument};
use sync_collection::handle_sync_collection;
use tracing::instrument;
mod addressbook_multiget;
mod addressbook_query;
mod sync_collection;
#[derive(XmlDeserialize, XmlDocument, Clone, Debug, PartialEq)]
pub(crate) enum ReportRequest {
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
AddressbookMultiget(AddressbookMultigetRequest),
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
AddressbookQuery(AddressbookQueryRequest),
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
SyncCollection(SyncCollectionRequest<AddressObjectPropWrapperName>),
}
impl ReportRequest {
fn props(&self) -> &PropfindType<AddressObjectPropWrapperName> {
const fn props(&self) -> &PropfindType<AddressObjectPropWrapperName> {
match self {
ReportRequest::AddressbookMultiget(AddressbookMultigetRequest { prop, .. }) => prop,
ReportRequest::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
Self::AddressbookMultiget(AddressbookMultigetRequest { prop, .. })
| Self::SyncCollection(SyncCollectionRequest { prop, .. })
| Self::AddressbookQuery(AddressbookQueryRequest { prop, .. }) => prop,
}
}
}
fn objects_response(
objects: Vec<(String, AddressObject)>,
not_found: Vec<String>,
path: &str,
principal: &str,
puri: &impl PrincipalUri,
user: &Principal,
prop: &PropfindType<AddressObjectPropWrapperName>,
) -> Result<MultistatusElement<AddressObjectPropWrapper, String>, Error> {
let mut responses = Vec::new();
for (object_id, object) in objects {
let path = format!("{}/{}.vcf", path, &object_id);
responses.push(
AddressObjectResource {
object,
object_id,
principal: principal.to_owned(),
}
.propfind(&path, prop, None, puri, user)?,
);
}
let not_found_responses = not_found
.into_iter()
.map(|path| ResponseElement {
href: path,
status: Some(StatusCode::NOT_FOUND),
..Default::default()
})
.collect();
Ok(MultistatusElement {
responses,
member_responses: not_found_responses,
..Default::default()
})
}
#[instrument(skip(addr_store))]
pub async fn route_report_addressbook<AS: AddressbookStore, S: SubscriptionStore>(
Path((principal, addressbook_id)): Path<(String, String)>,
@@ -75,13 +133,36 @@ pub async fn route_report_addressbook<AS: AddressbookStore, S: SubscriptionStore
)
.await?
}
ReportRequest::AddressbookQuery(addr_query) => {
let objects = get_objects_addressbook_query(
addr_query,
&principal,
&addressbook_id,
addr_store.as_ref(),
)
.await?;
objects_response(
objects,
vec![],
uri.path(),
&principal,
&puri,
&user,
&addr_query.prop,
)?
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::address_object::AddressObjectPropName;
use crate::{
address_object::AddressObjectPropName,
addressbook::methods::report::addressbook_query::{
Allof, FilterElement, LimitElement, NresultsElement, PropFilterElement,
},
};
use rustical_dav::xml::{PropElement, sync_collection::SyncLevel};
#[test]
@@ -101,7 +182,7 @@ mod tests {
assert_eq!(
report_request,
ReportRequest::SyncCollection(SyncCollectionRequest {
sync_token: "".to_owned(),
sync_token: String::new(),
sync_level: SyncLevel::One,
prop: rustical_dav::xml::PropfindType::Prop(PropElement(
vec![AddressObjectPropWrapperName::AddressObject(
@@ -111,7 +192,7 @@ mod tests {
)),
limit: None
})
)
);
}
#[test]
@@ -142,6 +223,52 @@ mod tests {
"/carddav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
]
})
);
}
#[test]
fn test_xml_addressbook_query() {
let report_request = ReportRequest::parse_str(
r#"
<?xml version="1.0" encoding="utf-8"?>
<card:addressbook-query xmlns:card="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:">
<d:prop>
<d:getetag/>
</d:prop>
<card:filter>
<card:prop-filter name="FN"/>
</card:filter>
<card:limit>
<card:nresults>100</card:nresults>
</card:limit>
</card:addressbook-query>
"#,
)
.unwrap();
assert_eq!(
report_request,
ReportRequest::AddressbookQuery(AddressbookQueryRequest {
prop: rustical_dav::xml::PropfindType::Prop(PropElement(
vec![AddressObjectPropWrapperName::AddressObject(
AddressObjectPropName::Getetag
),],
vec![]
)),
filter: FilterElement {
test: Allof::default(),
prop_filter: vec![PropFilterElement {
name: "FN".to_owned(),
is_not_defined: None,
text_match: vec![],
param_filter: vec![],
test: Allof::default()
}],
},
limit: Some(LimitElement {
nresults: NresultsElement(100)
})
})
);
}
}

View File

@@ -32,11 +32,12 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
.await?;
let mut responses = Vec::new();
for object in new_objects {
let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object.get_id());
for (object_id, object) in new_objects {
let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object_id);
responses.push(
AddressObjectResource {
object,
object_id,
principal: principal.to_owned(),
}
.propfind(&path, &sync_collection.prop, None, puri, user)?,

View File

@@ -3,3 +3,5 @@ pub mod prop;
pub mod resource;
mod service;
pub use service::*;
#[cfg(test)]
pub mod tests;

View File

@@ -1,12 +1,13 @@
use derive_more::{From, Into};
use rustical_dav::{
extensions::{CommonPropertiesProp, SyncTokenExtensionProp},
xml::SupportedReportSet,
xml::{SupportedReportSet, TextCollation},
};
use rustical_dav_push::DavPushExtensionProp;
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
use strum_macros::VariantArray;
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "AddressbookPropName")]
pub enum AddressbookProp {
// CardDAV (RFC 6352)
@@ -14,13 +15,15 @@ pub enum AddressbookProp {
AddressbookDescription(Option<String>),
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
SupportedAddressData(SupportedAddressData),
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
SupportedCollationSet(SupportedCollationSet),
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
SupportedReportSet(SupportedReportSet<ReportMethod>),
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
MaxResourceSize(i64),
}
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "AddressbookPropWrapperName", untagged)]
pub enum AddressbookPropWrapper {
Addressbook(AddressbookProp),
@@ -29,7 +32,7 @@ pub enum AddressbookPropWrapper {
Common(CommonPropertiesProp),
}
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
#[derive(Debug, Clone, XmlSerialize, PartialEq, Eq)]
pub struct AddressDataType {
#[xml(ty = "attr")]
pub content_type: &'static str,
@@ -37,7 +40,7 @@ pub struct AddressDataType {
pub version: &'static str,
}
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
#[derive(Debug, Clone, XmlSerialize, PartialEq, Eq)]
pub struct SupportedAddressData {
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
address_data_type: &'static [AddressDataType],
@@ -60,7 +63,30 @@ impl Default for SupportedAddressData {
}
}
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq, From, Into)]
pub struct SupportedCollation(#[xml(ty = "text")] pub TextCollation);
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq)]
pub struct SupportedCollationSet(
#[xml(
ns = "rustical_dav::namespace::NS_CARDDAV",
flatten,
rename = "supported-collation"
)]
pub Vec<SupportedCollation>,
);
impl Default for SupportedCollationSet {
fn default() -> Self {
Self(vec![
SupportedCollation(TextCollation::AsciiCasemap),
SupportedCollation(TextCollation::UnicodeCasemap),
SupportedCollation(TextCollation::Octet),
])
}
}
#[derive(Debug, Clone, XmlSerialize, PartialEq, Eq, VariantArray)]
pub enum ReportMethod {
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
AddressbookMultiget,

View File

@@ -2,6 +2,7 @@ use super::prop::SupportedAddressData;
use crate::Error;
use crate::addressbook::prop::{
AddressbookProp, AddressbookPropName, AddressbookPropWrapper, AddressbookPropWrapperName,
SupportedCollationSet,
};
use derive_more::derive::{From, Into};
use rustical_dav::extensions::{CommonPropertiesExtension, SyncTokenExtension};
@@ -11,13 +12,14 @@ use rustical_dav::xml::{Resourcetype, ResourcetypeInner, SupportedReportSet};
use rustical_dav_push::DavPushExtension;
use rustical_store::Addressbook;
use rustical_store::auth::Principal;
use std::borrow::Cow;
#[derive(Clone, Debug, From, Into)]
pub struct AddressbookResource(pub(crate) Addressbook);
impl ResourceName for AddressbookResource {
fn get_name(&self) -> String {
self.0.id.to_owned()
fn get_name(&self) -> Cow<'_, str> {
Cow::from(&self.0.id)
}
}
@@ -29,7 +31,7 @@ impl SyncTokenExtension for AddressbookResource {
impl DavPushExtension for AddressbookResource {
fn get_topic(&self) -> String {
self.0.push_topic.to_owned()
self.0.push_topic.clone()
}
}
@@ -59,13 +61,16 @@ impl Resource for AddressbookResource {
AddressbookPropWrapperName::Addressbook(prop) => {
AddressbookPropWrapper::Addressbook(match prop {
AddressbookPropName::MaxResourceSize => {
AddressbookProp::MaxResourceSize(10000000)
AddressbookProp::MaxResourceSize(10_000_000)
}
AddressbookPropName::SupportedCollationSet => {
AddressbookProp::SupportedCollationSet(SupportedCollationSet::default())
}
AddressbookPropName::SupportedReportSet => {
AddressbookProp::SupportedReportSet(SupportedReportSet::all())
}
AddressbookPropName::AddressbookDescription => {
AddressbookProp::AddressbookDescription(self.0.description.to_owned())
AddressbookProp::AddressbookDescription(self.0.description.clone())
}
AddressbookPropName::SupportedAddressData => {
AddressbookProp::SupportedAddressData(SupportedAddressData::default())
@@ -92,9 +97,12 @@ impl Resource for AddressbookResource {
self.0.description = description;
Ok(())
}
AddressbookProp::MaxResourceSize(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::SupportedReportSet(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::SupportedAddressData(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::MaxResourceSize(_)
| AddressbookProp::SupportedCollationSet(_)
| AddressbookProp::SupportedReportSet(_)
| AddressbookProp::SupportedAddressData(_) => {
Err(rustical_dav::Error::PropReadOnly)
}
},
AddressbookPropWrapper::SyncToken(prop) => SyncTokenExtension::set_prop(self, prop),
AddressbookPropWrapper::DavPush(prop) => DavPushExtension::set_prop(self, prop),
@@ -112,9 +120,12 @@ impl Resource for AddressbookResource {
self.0.description = None;
Ok(())
}
AddressbookPropName::MaxResourceSize => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::SupportedReportSet => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::SupportedAddressData => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::MaxResourceSize
| AddressbookPropName::SupportedCollationSet
| AddressbookPropName::SupportedReportSet
| AddressbookPropName::SupportedAddressData => {
Err(rustical_dav::Error::PropReadOnly)
}
},
AddressbookPropWrapperName::SyncToken(prop) => {
SyncTokenExtension::remove_prop(self, prop)

View File

@@ -26,7 +26,7 @@ pub struct AddressbookResourceService<AS: AddressbookStore, S: SubscriptionStore
}
impl<A: AddressbookStore, S: SubscriptionStore> AddressbookResourceService<A, S> {
pub fn new(addr_store: Arc<A>, sub_store: Arc<S>) -> Self {
pub const fn new(addr_store: Arc<A>, sub_store: Arc<S>) -> Self {
Self {
addr_store,
sub_store,
@@ -78,7 +78,8 @@ impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
.get_objects(principal, addressbook_id)
.await?
.into_iter()
.map(|object| AddressObjectResource {
.map(|(object_id, object)| AddressObjectResource {
object_id,
object,
principal: principal.to_owned(),
})
@@ -91,7 +92,7 @@ impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
file: Self::Resource,
) -> Result<(), Self::Error> {
self.addr_store
.update_addressbook(principal.to_owned(), addressbook_id.to_owned(), file.into())
.update_addressbook(principal, addressbook_id, file.into())
.await?;
Ok(())
}

View File

@@ -0,0 +1,168 @@
---
source: crates/carddav/src/addressbook/tests.rs
expression: response
---
ResponseElement {
href: "/carddav/principal/user/yeet/",
status: None,
propstat: [
Normal(
PropstatElement {
prop: PropTagWrapper(
[
Addressbook(
AddressbookDescription(
None,
),
),
Addressbook(
SupportedAddressData(
SupportedAddressData {
address_data_type: [
AddressDataType {
content_type: "text/vcard",
version: "3.0",
},
AddressDataType {
content_type: "text/vcard",
version: "4.0",
},
],
},
),
),
Addressbook(
SupportedCollationSet(
SupportedCollationSet(
[
SupportedCollation(
AsciiCasemap,
),
SupportedCollation(
UnicodeCasemap,
),
SupportedCollation(
Octet,
),
],
),
),
),
Addressbook(
SupportedReportSet(
SupportedReportSet {
supported_report: [
ReportWrapper {
report: AddressbookMultiget,
},
ReportWrapper {
report: SyncCollection,
},
],
},
),
),
Addressbook(
MaxResourceSize(
10000000,
),
),
SyncToken(
SyncToken(
"github.com/lennart-k/rustical/ns/0",
),
),
SyncToken(
Getctag(
"github.com/lennart-k/rustical/ns/0",
),
),
DavPush(
Transports(
Transports {
transports: [
WebPush,
],
},
),
),
DavPush(
Topic(
"asdasd",
),
),
DavPush(
SupportedTriggers(
SupportedTriggers(
[
ContentUpdate(
ContentUpdate(
One,
),
),
PropertyUpdate(
PropertyUpdate(
One,
),
),
],
),
),
),
Common(
Resourcetype(
Resourcetype(
[
ResourcetypeInner(
Some(
Namespace("DAV:"),
),
"collection",
),
ResourcetypeInner(
Some(
Namespace("urn:ietf:params:xml:ns:carddav"),
),
"addressbook",
),
],
),
),
),
Common(
Displayname(
None,
),
),
Common(
CurrentUserPrincipal(
HrefElement {
href: "/carddav/principal/user/",
},
),
),
Common(
CurrentUserPrivilegeSet(
UserPrivilegeSet {
privileges: {
All,
},
},
),
),
Common(
Owner(
Some(
HrefElement {
href: "/carddav/principal/user/",
},
),
),
),
],
),
status: 200,
},
),
],
}

View File

@@ -0,0 +1,64 @@
---
source: crates/carddav/src/addressbook/tests.rs
expression: response.serialize_to_string().unwrap()
---
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="DAV:">
<href>/carddav/principal/user/yeet/</href>
<propstat>
<prop xmlns="DAV:">
<supported-address-data xmlns="urn:ietf:params:xml:ns:carddav">
<address-data-type xmlns="urn:ietf:params:xml:ns:carddav" content-type="text/vcard" version="3.0"/>
<address-data-type xmlns="urn:ietf:params:xml:ns:carddav" content-type="text/vcard" version="4.0"/>
</supported-address-data>
<supported-collation-set xmlns="urn:ietf:params:xml:ns:carddav">
<supported-collation xmlns="urn:ietf:params:xml:ns:carddav">i;ascii-casemap</supported-collation>
<supported-collation xmlns="urn:ietf:params:xml:ns:carddav">i;unicode-casemap</supported-collation>
<supported-collation xmlns="urn:ietf:params:xml:ns:carddav">i;octet</supported-collation>
</supported-collation-set>
<supported-report-set xmlns="DAV:">
<supported-report xmlns="DAV:">
<report xmlns="DAV:">
<addressbook-multiget xmlns="urn:ietf:params:xml:ns:carddav"/>
</report>
</supported-report>
<supported-report xmlns="DAV:">
<report xmlns="DAV:">
<sync-collection xmlns="DAV:"/>
</report>
</supported-report>
</supported-report-set>
<max-resource-size xmlns="urn:ietf:params:xml:ns:carddav">10000000</max-resource-size>
<sync-token xmlns="DAV:">github.com/lennart-k/rustical/ns/0</sync-token>
<getctag xmlns="http://calendarserver.org/ns/">github.com/lennart-k/rustical/ns/0</getctag>
<transports xmlns="https://bitfire.at/webdav-push">
<web-push xmlns="https://bitfire.at/webdav-push"/>
</transports>
<topic xmlns="https://bitfire.at/webdav-push">asdasd</topic>
<supported-triggers xmlns="https://bitfire.at/webdav-push">
<content-update xmlns="https://bitfire.at/webdav-push">
<depth xmlns="DAV:">1</depth>
</content-update>
<property-update xmlns="https://bitfire.at/webdav-push">
<depth xmlns="DAV:">1</depth>
</property-update>
</supported-triggers>
<resourcetype xmlns="DAV:">
<collection xmlns="DAV:"/>
<addressbook xmlns="urn:ietf:params:xml:ns:carddav"/>
</resourcetype>
<current-user-principal xmlns="DAV:">
<href xmlns="DAV:">/carddav/principal/user/</href>
</current-user-principal>
<current-user-privilege-set xmlns="DAV:">
<privilege>
<all/>
</privilege>
</current-user-privilege-set>
<owner xmlns="DAV:">
<href xmlns="DAV:">/carddav/principal/user/</href>
</owner>
</prop>
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
</propstat>
</response>

View File

@@ -0,0 +1,8 @@
---
source: crates/carddav/src/addressbook/tests.rs
expression: propfind
---
PropfindElement {
prop: Allprop,
include: None,
}

View File

@@ -0,0 +1,49 @@
use crate::{CardDavPrincipalUri, addressbook::resource::AddressbookResource};
use rustical_dav::resource::Resource;
use rustical_store::{Addressbook, auth::Principal};
use rustical_xml::XmlSerializeRoot;
#[test]
fn test_propfind() {
let propfind = AddressbookResource::parse_propfind(
r#"<?xml version="1.0" encoding="UTF-8"?><propfind xmlns="DAV:"><allprop/></propfind>"#,
)
.unwrap();
insta::assert_debug_snapshot!(propfind);
let principal = Principal {
id: "user".to_string(),
displayname: None,
principal_type: rustical_store::auth::PrincipalType::Individual,
password: None,
memberships: vec!["group".to_string()],
};
let addressbook = Addressbook {
id: "yeet".to_string(),
principal: "user".to_string(),
displayname: None,
description: None,
deleted_at: None,
synctoken: 0,
push_topic: "asdasd".to_string(),
};
let resource = AddressbookResource(addressbook.clone());
let response = resource
.propfind(
&format!(
"/carddav/principal/{}/{}",
addressbook.principal, addressbook.id
),
&propfind.prop,
propfind.include.as_ref(),
&CardDavPrincipalUri("/carddav"),
&principal,
)
.unwrap();
insta::assert_debug_snapshot!(response);
insta::assert_snapshot!(response.serialize_to_string().unwrap());
}

View File

@@ -1,6 +1,5 @@
use axum::response::IntoResponse;
use http::StatusCode;
use tracing::error;
#[derive(Debug, thiserror::Error)]
pub enum Error {
@@ -24,27 +23,23 @@ pub enum Error {
#[error(transparent)]
XmlDecodeError(#[from] rustical_xml::XmlError),
#[error(transparent)]
IcalError(#[from] rustical_ical::Error),
}
impl Error {
pub fn status_code(&self) -> StatusCode {
#[must_use]
pub const fn status_code(&self) -> StatusCode {
match self {
Error::StoreError(err) => match err {
Self::StoreError(err) => match err {
rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
rustical_store::Error::AlreadyExists => StatusCode::CONFLICT,
rustical_store::Error::ReadOnly => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR,
},
Error::ChronoParseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
Error::DavError(err) => err.status_code(),
Error::Unauthorized => StatusCode::UNAUTHORIZED,
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
Error::NotFound => StatusCode::NOT_FOUND,
Self::IcalError(err) => err.status_code(),
Self::DavError(err) => err.status_code(),
Self::Unauthorized => StatusCode::UNAUTHORIZED,
Self::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
Self::ChronoParseError(_) | Self::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
Self::NotFound => StatusCode::NOT_FOUND,
}
}
}

View File

@@ -1,3 +1,5 @@
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]
use axum::response::Redirect;
use axum::routing::any;
use axum::{Extension, Router};
@@ -36,17 +38,12 @@ pub fn carddav_router<AP: AuthenticationProvider, A: AddressbookStore, S: Subscr
store: Arc<A>,
subscription_store: Arc<S>,
) -> Router {
let principal_service = PrincipalResourceService::new(
store.clone(),
auth_provider.clone(),
subscription_store.clone(),
);
let principal_service =
PrincipalResourceService::new(store, auth_provider.clone(), subscription_store);
Router::new()
.nest(
prefix,
RootResourceService::<_, Principal, CardDavPrincipalUri>::new(
principal_service.clone(),
)
RootResourceService::<_, Principal, CardDavPrincipalUri>::new(principal_service)
.axum_router()
.layer(AuthenticationLayer::new(auth_provider))
.layer(Extension(CardDavPrincipalUri(prefix))),

View File

@@ -1,3 +1,5 @@
use std::borrow::Cow;
use crate::Error;
use rustical_dav::extensions::CommonPropertiesExtension;
use rustical_dav::privileges::UserPrivilegeSet;
@@ -11,16 +13,18 @@ mod service;
pub use service::*;
mod prop;
pub use prop::*;
#[cfg(test)]
pub mod tests;
#[derive(Debug, Clone)]
pub struct PrincipalResource {
principal: Principal,
members: Vec<String>,
pub principal: Principal,
pub members: Vec<String>,
}
impl ResourceName for PrincipalResource {
fn get_name(&self) -> String {
self.principal.id.to_owned()
fn get_name(&self) -> Cow<'_, str> {
Cow::from(&self.principal.id)
}
}

View File

@@ -4,7 +4,7 @@ use rustical_dav::{
};
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "PrincipalPropName")]
pub enum PrincipalProp {
// WebDAV Access Control (RFC 3744)
@@ -27,10 +27,10 @@ pub enum PrincipalProp {
PrincipalAddress(Option<HrefElement>),
}
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, Debug)]
pub struct AddressbookHomeSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
pub enum PrincipalPropWrapper {
Principal(PrincipalProp),

View File

@@ -34,7 +34,7 @@ impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> Clon
impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore>
PrincipalResourceService<A, AP, S>
{
pub fn new(addr_store: Arc<A>, auth_provider: Arc<AP>, sub_store: Arc<S>) -> Self {
pub const fn new(addr_store: Arc<A>, auth_provider: Arc<AP>, sub_store: Arc<S>) -> Self {
Self {
addr_store,
auth_provider,

View File

@@ -0,0 +1,125 @@
---
source: crates/carddav/src/principal/tests.rs
expression: response
---
ResponseElement {
href: "/carddav/principal/user/",
status: None,
propstat: [
Normal(
PropstatElement {
prop: PropTagWrapper(
[
Principal(
PrincipalUrl(
HrefElement {
href: "/carddav/principal/user/",
},
),
),
Principal(
GroupMembership(
GroupMembership(
[
HrefElement {
href: "/carddav/principal/group/",
},
],
),
),
),
Principal(
GroupMemberSet(
GroupMemberSet(
[],
),
),
),
Principal(
AlternateUriSet,
),
Principal(
PrincipalCollectionSet(
HrefElement {
href: "/carddav/principal/",
},
),
),
Principal(
AddressbookHomeSet(
AddressbookHomeSet(
[
HrefElement {
href: "/carddav/principal/group/",
},
HrefElement {
href: "/carddav/principal/user/",
},
],
),
),
),
Principal(
PrincipalAddress(
None,
),
),
Common(
Resourcetype(
Resourcetype(
[
ResourcetypeInner(
Some(
Namespace("DAV:"),
),
"collection",
),
ResourcetypeInner(
Some(
Namespace("DAV:"),
),
"principal",
),
],
),
),
),
Common(
Displayname(
Some(
"user",
),
),
),
Common(
CurrentUserPrincipal(
HrefElement {
href: "/carddav/principal/user/",
},
),
),
Common(
CurrentUserPrivilegeSet(
UserPrivilegeSet {
privileges: {
All,
},
},
),
),
Common(
Owner(
Some(
HrefElement {
href: "/carddav/principal/user/",
},
),
),
),
],
),
status: 200,
},
),
],
}

View File

@@ -0,0 +1,45 @@
---
source: crates/carddav/src/principal/tests.rs
expression: response.serialize_to_string().unwrap()
---
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="DAV:">
<href>/carddav/principal/user/</href>
<propstat>
<prop xmlns="DAV:">
<principal-URL xmlns="DAV:">
<href xmlns="DAV:">/carddav/principal/user/</href>
</principal-URL>
<group-membership xmlns="DAV:">
<href xmlns="DAV:">/carddav/principal/group/</href>
</group-membership>
<group-member-set xmlns="DAV:">
</group-member-set>
<alternate-URI-set xmlns="DAV:"/>
<principal-collection-set xmlns="DAV:">
<href xmlns="DAV:">/carddav/principal/</href>
</principal-collection-set>
<addressbook-home-set xmlns="urn:ietf:params:xml:ns:carddav">
<href xmlns="DAV:">/carddav/principal/group/</href>
<href xmlns="DAV:">/carddav/principal/user/</href>
</addressbook-home-set>
<resourcetype xmlns="DAV:">
<collection xmlns="DAV:"/>
<principal xmlns="DAV:"/>
</resourcetype>
<displayname xmlns="DAV:">user</displayname>
<current-user-principal xmlns="DAV:">
<href xmlns="DAV:">/carddav/principal/user/</href>
</current-user-principal>
<current-user-privilege-set xmlns="DAV:">
<privilege>
<all/>
</privilege>
</current-user-privilege-set>
<owner xmlns="DAV:">
<href xmlns="DAV:">/carddav/principal/user/</href>
</owner>
</prop>
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
</propstat>
</response>

View File

@@ -0,0 +1,8 @@
---
source: crates/carddav/src/principal/tests.rs
expression: propfind
---
PropfindElement {
prop: Allprop,
include: None,
}

View File

@@ -0,0 +1,41 @@
use rustical_dav::resource::Resource;
use rustical_store::auth::Principal;
use rustical_xml::XmlSerializeRoot;
use crate::{CardDavPrincipalUri, principal::PrincipalResource};
#[test]
fn test_propfind() {
let propfind = PrincipalResource::parse_propfind(
r#"<?xml version="1.0" encoding="UTF-8"?><propfind xmlns="DAV:"><allprop/></propfind>"#,
)
.unwrap();
insta::assert_debug_snapshot!(propfind);
let principal = Principal {
id: "user".to_string(),
displayname: None,
principal_type: rustical_store::auth::PrincipalType::Individual,
password: None,
memberships: vec!["group".to_string()],
};
let resource = PrincipalResource {
principal: principal.clone(),
members: vec![],
};
let response = resource
.propfind(
&format!("/carddav/principal/{}", principal.id),
&propfind.prop,
propfind.include.as_ref(),
&CardDavPrincipalUri("/carddav"),
&principal,
)
.unwrap();
insta::assert_debug_snapshot!(response);
insta::assert_snapshot!(response.serialize_to_string().unwrap());
}

View File

@@ -1,6 +1,7 @@
[package]
name = "rustical_dav"
version.workspace = true
rust-version.workspace = true
edition.workspace = true
description.workspace = true
repository.workspace = true
@@ -11,7 +12,6 @@ publish = false
axum.workspace = true
tower.workspace = true
axum-extra.workspace = true
rustical_xml.workspace = true
async-trait.workspace = true
futures-util.workspace = true
@@ -28,3 +28,7 @@ headers.workspace = true
strum.workspace = true
matchit.workspace = true
matchit-serde.workspace = true
caldata = { workspace = true, optional = true }
[features]
ical = ["dep:caldata"]

View File

@@ -35,9 +35,9 @@ pub enum Error {
}
impl Error {
pub fn status_code(&self) -> StatusCode {
#[must_use]
pub const fn status_code(&self) -> StatusCode {
match self {
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
Self::NotFound => StatusCode::NOT_FOUND,
Self::BadRequest(_) => StatusCode::BAD_REQUEST,
Self::Unauthorized => StatusCode::UNAUTHORIZED,
@@ -50,25 +50,24 @@ impl Error {
| XmlError::InvalidValue(_) => StatusCode::UNPROCESSABLE_ENTITY,
_ => StatusCode::BAD_REQUEST,
},
Error::PropReadOnly => StatusCode::CONFLICT,
Error::PreconditionFailed => StatusCode::PRECONDITION_FAILED,
Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
Self::Forbidden => StatusCode::FORBIDDEN,
Self::PropReadOnly => StatusCode::CONFLICT,
Self::InternalError | Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
// The correct status code for a failed precondition is not PreconditionFailed but
// Forbidden (or Conflict):
// https://datatracker.ietf.org/doc/html/rfc4791#section-1.3
Self::PreconditionFailed | Self::Forbidden => StatusCode::FORBIDDEN,
}
}
}
impl axum::response::IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
if matches!(
self.status_code(),
StatusCode::INTERNAL_SERVER_ERROR | StatusCode::PRECONDITION_FAILED
) {
if matches!(self.status_code(), StatusCode::INTERNAL_SERVER_ERROR) {
error!("{self}");
}
let mut resp = axum::response::Response::builder().status(self.status_code());
if matches!(&self, &Error::Unauthorized) {
if matches!(&self, &Self::Unauthorized) {
resp.headers_mut()
.expect("This must always work")
.insert("WWW-Authenticate", "Basic".parse().unwrap());

View File

@@ -6,7 +6,7 @@ use crate::{
};
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, PropName, EnumVariants)]
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Debug, Clone, PropName, EnumVariants)]
#[xml(unit_variants_ident = "CommonPropertiesPropName")]
pub enum CommonPropertiesProp {
// WebDAV (RFC 2518)
@@ -39,9 +39,9 @@ pub trait CommonPropertiesExtension: Resource {
CommonPropertiesPropName::Resourcetype => {
CommonPropertiesProp::Resourcetype(self.get_resourcetype())
}
CommonPropertiesPropName::Displayname => {
CommonPropertiesProp::Displayname(self.get_displayname().map(|s| s.to_string()))
}
CommonPropertiesPropName::Displayname => CommonPropertiesProp::Displayname(
self.get_displayname().map(std::string::ToString::to_string),
),
CommonPropertiesPropName::CurrentUserPrincipal => {
CommonPropertiesProp::CurrentUserPrincipal(
principal_uri.principal_uri(principal.get_id()).into(),

Some files were not shown because too many files have changed in this diff Show More