mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-13 13:32:16 +00:00
Compare commits
203 Commits
feature/ca
...
v0.8.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61d226dada | ||
|
|
ce0ce43418 | ||
|
|
038942ff16 | ||
|
|
90c38e7703 | ||
|
|
0159a8d9c9 | ||
|
|
aa8db47f57 | ||
|
|
78f7a7e155 | ||
|
|
e1a7a188f5 | ||
|
|
a42004501b | ||
|
|
89ce14ee86 | ||
|
|
7fc64d219c | ||
|
|
03294ec106 | ||
|
|
a22235d976 | ||
|
|
1ba9a97b3f | ||
|
|
51036ec6d5 | ||
|
|
e1a10338e0 | ||
|
|
918f27e8c2 | ||
|
|
dd34dd23d1 | ||
|
|
9910e4ee31 | ||
|
|
c22469dea6 | ||
|
|
f2899aec6b | ||
|
|
f9380ca7e4 | ||
|
|
e7138b5f8c | ||
|
|
84af24a2b7 | ||
|
|
4bd6271e33 | ||
|
|
d817c1384c | ||
|
|
f8abc22e63 | ||
|
|
b7b5ca4f91 | ||
|
|
caca2d28ed | ||
|
|
3db2f13c1b | ||
|
|
db01024682 | ||
|
|
b2f15f2d77 | ||
|
|
89dd94904b | ||
|
|
5d0263abc1 | ||
|
|
0ef3e19bd3 | ||
|
|
44912057fc | ||
|
|
c4f613a803 | ||
|
|
eb8f301e45 | ||
|
|
d59ae25eba | ||
|
|
d4daa35df6 | ||
|
|
ea43876410 | ||
|
|
18af1b9aa2 | ||
|
|
e69c75102c | ||
|
|
09f1bd20ae | ||
|
|
72f970a857 | ||
|
|
08c250657e | ||
|
|
b8ef2f1ba2 | ||
|
|
c8adf60f48 | ||
|
|
507cb77e85 | ||
|
|
8881ea2a05 | ||
|
|
119e17a8e1 | ||
|
|
8b01c5388b | ||
|
|
35f423d4ca | ||
|
|
a827b40b47 | ||
|
|
16f9ce6f38 | ||
|
|
34839aa2ed | ||
|
|
2724154ed3 | ||
|
|
c490c413ec | ||
|
|
994864c6ef | ||
|
|
92fd28cdbb | ||
|
|
d7e871f0e6 | ||
|
|
a0fc073bd2 | ||
|
|
c8dffb4f9e | ||
|
|
b6d1899636 | ||
|
|
81f1767efa | ||
|
|
54eb9ddfcc | ||
|
|
60a0f16557 | ||
|
|
e4f188d299 | ||
|
|
69163404a1 | ||
|
|
0b7cfea79c | ||
|
|
455b4c405f | ||
|
|
2774d092ac | ||
|
|
32b616fd75 | ||
|
|
b02f7c427a | ||
|
|
eae8e7d768 | ||
|
|
105718a4ca | ||
|
|
0e68f1bdce | ||
|
|
aa744fcea2 | ||
|
|
4a51a669cd | ||
|
|
07fca05e50 | ||
|
|
509cc8d7a1 | ||
|
|
4134ab0520 | ||
|
|
d8803a38a2 | ||
|
|
b5bff08b08 | ||
|
|
3ca02d9792 | ||
|
|
ee2cc2174c | ||
|
|
caf10912e5 | ||
|
|
ec89cd6fa5 | ||
|
|
ae20573670 | ||
|
|
71cee2d20c | ||
|
|
83c6bf247e | ||
|
|
6bcc03d659 | ||
|
|
32f5c01716 | ||
|
|
40938cba02 | ||
|
|
a5663bf006 | ||
|
|
26306fd661 | ||
|
|
d8e4bd1cc4 | ||
|
|
a18ff2b400 | ||
|
|
bf13d95b97 | ||
|
|
ee1faa4c20 | ||
|
|
1e999ca0cc | ||
|
|
f27245f996 | ||
|
|
734455b5ab | ||
|
|
8c6a616015 | ||
|
|
828e7399c8 | ||
|
|
891ef6a9f3 | ||
|
|
7b27ac22a4 | ||
|
|
15668bf399 | ||
|
|
d2de87072f | ||
|
|
ff1e38477b | ||
|
|
f4fbb7c964 | ||
|
|
e8e60d4aac | ||
|
|
283be0a26c | ||
|
|
1060625b9d | ||
|
|
86ae31e94c | ||
|
|
e2f5773e3c | ||
|
|
b54fbebe7c | ||
|
|
fe78a82806 | ||
|
|
22544b8c2f | ||
|
|
340b99e491 | ||
|
|
787ea90376 | ||
|
|
973a86f21a | ||
|
|
39fc2fb55d | ||
|
|
ab4d763304 | ||
|
|
9cf74f7198 | ||
|
|
2c2a6006c7 | ||
|
|
4600f03b45 | ||
|
|
41fc1e6ea5 | ||
|
|
b56591c482 | ||
|
|
d639b18005 | ||
|
|
6046439fc7 | ||
|
|
f9de8a4687 | ||
|
|
8dfb47b28f | ||
|
|
eb720ded99 | ||
|
|
89ef7b2ced | ||
|
|
6e0129130e | ||
|
|
c646986c56 | ||
|
|
503cbe3699 | ||
|
|
79c66a0b46 | ||
|
|
e5687c6e43 | ||
|
|
79b67a17c3 | ||
|
|
7d18faff69 | ||
|
|
753f8e90d3 | ||
|
|
701fa9dd9c | ||
|
|
31b17cfe7f | ||
|
|
d802a0085a | ||
|
|
786b15f5b9 | ||
|
|
f5d097ac55 | ||
|
|
668fa86e3c | ||
|
|
23d2024644 | ||
|
|
15aadcf1be | ||
|
|
4a3b7d7ce6 | ||
|
|
1a2f3b8f8a | ||
|
|
9e8c218308 | ||
|
|
f2adce739b | ||
|
|
0415664ff3 | ||
|
|
677e0082fa | ||
|
|
a387885b0a | ||
|
|
990b953055 | ||
|
|
36b47a645d | ||
|
|
aa02d11f58 | ||
|
|
1c31323512 | ||
|
|
03ae492483 | ||
|
|
0c48507f0c | ||
|
|
829d4a4385 | ||
|
|
4fe28c5b0f | ||
|
|
529f36ad99 | ||
|
|
ca5891314c | ||
|
|
e653c68cae | ||
|
|
26941c621b | ||
|
|
86ab6ef75e | ||
|
|
0669d4e683 | ||
|
|
0c432d70f9 | ||
|
|
54997ef865 | ||
|
|
1a1deeb5a2 | ||
|
|
87899738f6 | ||
|
|
ab90e5129c | ||
|
|
a9cb397f57 | ||
|
|
35e78bfb44 | ||
|
|
b6ef2b4c05 | ||
|
|
32bc8c707d | ||
|
|
1757bbee13 | ||
|
|
4dbc316e64 | ||
|
|
4705170dbc | ||
|
|
0e2f08d7f2 | ||
|
|
feb8b3ff09 | ||
|
|
41d5c72e4e | ||
|
|
89adbcf13f | ||
|
|
5a3a2c0909 | ||
|
|
3e8fffa316 | ||
|
|
40e7bc0f66 | ||
|
|
f857d68760 | ||
|
|
9e5eaa5e1c | ||
|
|
7c73223877 | ||
|
|
0c1c04d1cd | ||
|
|
72961f44e0 | ||
|
|
49ac6abf35 | ||
|
|
c855e3d6b6 | ||
|
|
6ecdc6125e | ||
|
|
4eb35d6c0d | ||
|
|
bd0684dcbc | ||
|
|
dac49f853a | ||
|
|
f1c61ecefa |
@@ -2,3 +2,5 @@
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
|
||||
[docs/**/*.md]
|
||||
indent_size = 4
|
||||
|
||||
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Otherwise GitHub thinks this is an HTML project
|
||||
crates/frontend/public/assets/licenses.html linguist-detectable=false
|
||||
crates/frontend/public/assets/js/* linguist-detectable=false
|
||||
8
.github/workflows/docker-publish.yml
vendored
8
.github/workflows/docker-publish.yml
vendored
@@ -3,6 +3,9 @@ name: Docker
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
release:
|
||||
types: ["published"]
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
@@ -38,13 +41,10 @@ jobs:
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
# As long as we don't have releases everything on the main branch shall be tagged as latest
|
||||
# TODO: Before first release correctly configure this
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -12,3 +12,7 @@ principals.toml
|
||||
.env
|
||||
|
||||
site
|
||||
|
||||
# Frontend
|
||||
**/node_modules
|
||||
**/.vite
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT id, vcf FROM addressobjects WHERE (principal, addressbook_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) or ?)",
|
||||
"query": "SELECT id, vcf FROM addressobjects WHERE (principal, addressbook_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -22,5 +22,5 @@
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "395e40a7b3333b79bc2ad50a123d99f74bc2712a16257ee2119dd211fdb61f7e"
|
||||
"hash": "246ec675667992c1297c29348d46496a884c59adb8b64b569d36f4ce10f88f47"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT *\n FROM calendars\n WHERE principal = ? AND deleted_at IS NOT NULL",
|
||||
"query": "SELECT principal, id, displayname, \"order\", description, color, timezone_id, deleted_at, synctoken, subscription_url, push_topic, comp_event, comp_todo, comp_journal\n FROM calendars\n WHERE principal = ? AND deleted_at IS NOT NULL",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -14,68 +14,63 @@
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "synctoken",
|
||||
"name": "displayname",
|
||||
"ordinal": 2,
|
||||
"type_info": "Integer"
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "displayname",
|
||||
"name": "order",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "description",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "order",
|
||||
"ordinal": 5,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "color",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "timezone",
|
||||
"ordinal": 7,
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "timezone_id",
|
||||
"ordinal": 8,
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "deleted_at",
|
||||
"ordinal": 9,
|
||||
"ordinal": 7,
|
||||
"type_info": "Datetime"
|
||||
},
|
||||
{
|
||||
"name": "synctoken",
|
||||
"ordinal": 8,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "subscription_url",
|
||||
"ordinal": 10,
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "push_topic",
|
||||
"ordinal": 11,
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "comp_event",
|
||||
"ordinal": 12,
|
||||
"ordinal": 11,
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"name": "comp_todo",
|
||||
"ordinal": 13,
|
||||
"ordinal": 12,
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"name": "comp_journal",
|
||||
"ordinal": 14,
|
||||
"ordinal": 13,
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
@@ -85,14 +80,13 @@
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
@@ -100,5 +94,5 @@
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "cce62f7829bd688cd8c7928b587bc31f0e50865c214b1df113350bea2c254237"
|
||||
"hash": "27ac68a4eea40c1cac663cad034028cf6c373354b29e3a5290c18f58101913cd"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "\n REPLACE INTO principals\n (id, displayname, principal_type, password_hash)\n VALUES (?, ?, ?, ?)\n ",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 4
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "2f043f62a7c0eae1023e319f0bc8f35dfdcf6a8247e03b1de3e2cabb2d3ab8ae"
|
||||
}
|
||||
20
.sqlx/query-3b00b59f047e534a7f7f654984dc880f4aa9281aae5974722d2f22ec6d15cb32.json
generated
Normal file
20
.sqlx/query-3b00b59f047e534a7f7f654984dc880f4aa9281aae5974722d2f22ec6d15cb32.json
generated
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT principal FROM memberships WHERE member_of = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "principal",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "3b00b59f047e534a7f7f654984dc880f4aa9281aae5974722d2f22ec6d15cb32"
|
||||
}
|
||||
12
.sqlx/query-46ae176a06e314492f661c28436d6370883052c854da43475d7ced60cf8326e3.json
generated
Normal file
12
.sqlx/query-46ae176a06e314492f661c28436d6370883052c854da43475d7ced60cf8326e3.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "UPDATE calendars SET principal = ?, id = ?, displayname = ?, description = ?, \"order\" = ?, color = ?, timezone_id = ?, push_topic = ?, comp_event = ?, comp_todo = ?, comp_journal = ?\n WHERE (principal, id) = (?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 13
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "46ae176a06e314492f661c28436d6370883052c854da43475d7ced60cf8326e3"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT id, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?)",
|
||||
"query": "SELECT id, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -15,12 +15,12 @@
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
"Right": 4
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "d2f7423e2e8f97607f6664200990dcadb927445880ec6edffba3b5aedf4e199b"
|
||||
"hash": "543838c030550cb09d1af08adfeade8b7ce3575d92fddbc6e9582d141bc9e49d"
|
||||
}
|
||||
12
.sqlx/query-5c09c2a3c052188435409d4ff076575394e625dd19f00dea2d4c71a9f34a5952.json
generated
Normal file
12
.sqlx/query-5c09c2a3c052188435409d4ff076575394e625dd19f00dea2d4c71a9f34a5952.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "\n INSERT INTO principals\n (id, displayname, principal_type, password_hash) VALUES (?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n (displayname, principal_type, password_hash)\n = (excluded.displayname, excluded.principal_type, excluded.password_hash)\n ",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 4
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "5c09c2a3c052188435409d4ff076575394e625dd19f00dea2d4c71a9f34a5952"
|
||||
}
|
||||
12
.sqlx/query-60b940ff493e7c0fcb2ffe8ae97172c6444525ffeec21b194bd7443d11d06113.json
generated
Normal file
12
.sqlx/query-60b940ff493e7c0fcb2ffe8ae97172c6444525ffeec21b194bd7443d11d06113.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO calendars (principal, id, displayname, description, \"order\", color, subscription_url, timezone_id, push_topic, comp_event, comp_todo, comp_journal)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 12
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "60b940ff493e7c0fcb2ffe8ae97172c6444525ffeec21b194bd7443d11d06113"
|
||||
}
|
||||
26
.sqlx/query-660833e0505d3bbcd6dd736cce06b1bf14263d0e0e87b27d89d376d422e4e474.json
generated
Normal file
26
.sqlx/query-660833e0505d3bbcd6dd736cce06b1bf14263d0e0e87b27d89d376d422e4e474.json
generated
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT length(vcf) AS 'length!: u64', deleted_at AS 'deleted!: bool' FROM addressobjects WHERE principal = ? AND addressbook_id = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "length!: u64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Null"
|
||||
},
|
||||
{
|
||||
"name": "deleted!: bool",
|
||||
"ordinal": 1,
|
||||
"type_info": "Datetime"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
null,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "660833e0505d3bbcd6dd736cce06b1bf14263d0e0e87b27d89d376d422e4e474"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT *\n FROM calendars\n WHERE (principal, id) = (?, ?)",
|
||||
"query": "SELECT *\n FROM calendars\n WHERE (principal, id) = (?, ?)\n AND ((deleted_at IS NULL) OR ?) ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -39,48 +39,43 @@
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "timezone",
|
||||
"name": "timezone_id",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "timezone_id",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "deleted_at",
|
||||
"ordinal": 9,
|
||||
"ordinal": 8,
|
||||
"type_info": "Datetime"
|
||||
},
|
||||
{
|
||||
"name": "subscription_url",
|
||||
"ordinal": 10,
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "push_topic",
|
||||
"ordinal": 11,
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "comp_event",
|
||||
"ordinal": 12,
|
||||
"ordinal": 11,
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"name": "comp_todo",
|
||||
"ordinal": 13,
|
||||
"ordinal": 12,
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"name": "comp_journal",
|
||||
"ordinal": 14,
|
||||
"ordinal": 13,
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
@@ -93,12 +88,11 @@
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "9f930775043a6d4571a8ffd5a981cadf7c51f3f11a189f8461505abec31076e6"
|
||||
"hash": "bb2fa030f2e7c7afdb38c5c54cb31de5293be332d86cf643977d479999542553"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO calendars (principal, id, displayname, description, \"order\", color, timezone, timezone_id, push_topic, comp_event, comp_todo, comp_journal)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 12
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "c4134652b1efb1dda36fb59827bf9cfee6be5bddfd352f1da4e37c6b6aa0fa7a"
|
||||
}
|
||||
@@ -39,43 +39,38 @@
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "timezone",
|
||||
"name": "timezone_id",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "timezone_id",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "deleted_at",
|
||||
"ordinal": 9,
|
||||
"ordinal": 8,
|
||||
"type_info": "Datetime"
|
||||
},
|
||||
{
|
||||
"name": "subscription_url",
|
||||
"ordinal": 10,
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "push_topic",
|
||||
"ordinal": 11,
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "comp_event",
|
||||
"ordinal": 12,
|
||||
"ordinal": 11,
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"name": "comp_todo",
|
||||
"ordinal": 13,
|
||||
"ordinal": 12,
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"name": "comp_journal",
|
||||
"ordinal": 14,
|
||||
"ordinal": 13,
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
@@ -93,7 +88,6 @@
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "UPDATE calendars SET principal = ?, id = ?, displayname = ?, description = ?, \"order\" = ?, color = ?, timezone = ?, timezone_id = ?, push_topic = ?, comp_event = ?, comp_todo = ?, comp_journal = ?\n WHERE (principal, id) = (?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 14
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "d65c9c40606e59dd816a51b9b9ac60fd2ff81aaa358fcc038134e9a68ba45ad7"
|
||||
}
|
||||
26
.sqlx/query-d9f14260a46a7ccd137d462c35d350a7fe338a074131776596c5d803fcda1f48.json
generated
Normal file
26
.sqlx/query-d9f14260a46a7ccd137d462c35d350a7fe338a074131776596c5d803fcda1f48.json
generated
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT length(ics) AS 'length!: u64', deleted_at AS 'deleted!: bool' FROM calendarobjects WHERE principal = ? AND cal_id = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "length!: u64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Null"
|
||||
},
|
||||
{
|
||||
"name": "deleted!: bool",
|
||||
"ordinal": 1,
|
||||
"type_info": "Datetime"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
null,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "d9f14260a46a7ccd137d462c35d350a7fe338a074131776596c5d803fcda1f48"
|
||||
}
|
||||
1133
Cargo.lock
generated
1133
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
24
Cargo.toml
24
Cargo.toml
@@ -2,10 +2,11 @@
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
version = "0.8.1"
|
||||
edition = "2024"
|
||||
description = "A CalDAV server"
|
||||
repository = "https://github.com/lennart-k/rustical"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
[package]
|
||||
name = "rustical"
|
||||
@@ -13,11 +14,13 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
resolver = "2"
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
debug = ["opentelemetry"]
|
||||
frontend-dev = ["rustical_frontend/dev"]
|
||||
opentelemetry = [
|
||||
"dep:opentelemetry",
|
||||
"dep:opentelemetry-otlp",
|
||||
@@ -26,10 +29,12 @@ opentelemetry = [
|
||||
"dep:tracing-opentelemetry",
|
||||
]
|
||||
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
|
||||
[workspace.dependencies]
|
||||
matchit = "0.8"
|
||||
uuid = { version = "1.11", features = ["v4", "fast-rng"] }
|
||||
async-trait = "0.1"
|
||||
axum = "0.8"
|
||||
@@ -90,8 +95,12 @@ strum = "0.27"
|
||||
strum_macros = "0.27"
|
||||
serde_json = { version = "1.0", features = ["raw_value"] }
|
||||
sqlx-sqlite = { version = "0.8", features = ["bundled"] }
|
||||
ical = { version = "0.11", features = ["generator", "serde"] }
|
||||
toml = "0.8"
|
||||
ical = { git = "https://github.com/lennart-k/ical-rs", features = [
|
||||
"generator",
|
||||
"serde",
|
||||
"chrono-tz",
|
||||
] }
|
||||
toml = "0.9"
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.6", features = [
|
||||
"trace",
|
||||
@@ -121,7 +130,7 @@ syn = { version = "2.0", features = ["full"] }
|
||||
quote = "1.0"
|
||||
proc-macro2 = "1.0"
|
||||
heck = "0.5"
|
||||
darling = "0.20"
|
||||
darling = "0.21"
|
||||
reqwest = { version = "0.12", features = [
|
||||
"rustls-tls",
|
||||
"charset",
|
||||
@@ -129,6 +138,13 @@ 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"
|
||||
ece = { version = "2.3", default-features = false, features = [
|
||||
"backend-openssl",
|
||||
] }
|
||||
openssl = { version = "0.10", features = ["vendored"] }
|
||||
async-std = { version = "1.13", features = ["attributes"] }
|
||||
|
||||
[dependencies]
|
||||
rustical_store = { workspace = true }
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
FROM --platform=$BUILDPLATFORM rust:1.86-alpine AS chef
|
||||
FROM --platform=$BUILDPLATFORM rust:1.88-alpine AS chef
|
||||
|
||||
ARG TARGETPLATFORM
|
||||
ARG BUILDPLATFORM
|
||||
|
||||
# the compiler will otherwise ask for aarch64-linux-musl-gcc
|
||||
ENV CC_aarch64_unknown_linux_musl="clang"
|
||||
ENV AR_aarch64_unknown_linux_musl="llvm-ar"
|
||||
ENV AR_aarch64_unknown_linux_musl="llvm20-ar"
|
||||
ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS="-Clink-self-contained=yes -Clinker=rust-lld"
|
||||
|
||||
# Stupid workaound with tempfiles since environment variables
|
||||
@@ -16,7 +16,7 @@ RUN case $TARGETPLATFORM in \
|
||||
*) echo "Unsupported platform ${TARGETPLATFORM}"; exit 1;; \
|
||||
esac
|
||||
|
||||
RUN apk add --no-cache musl-dev llvm19 clang \
|
||||
RUN apk add --no-cache musl-dev llvm20 clang perl pkgconf make \
|
||||
&& rustup target add "$(cat /tmp/rust_target)" \
|
||||
&& cargo install cargo-chef --locked \
|
||||
&& rm -rf "$CARGO_HOME/registry"
|
||||
|
||||
12
Justfile
12
Justfile
@@ -1,2 +1,14 @@
|
||||
licenses:
|
||||
cargo about generate about.hbs > crates/frontend/public/assets/licenses.html
|
||||
|
||||
frontend-dev:
|
||||
cd crates/frontend/js-components && deno task dev
|
||||
|
||||
frontend-build:
|
||||
cd crates/frontend/js-components && deno task build
|
||||
|
||||
docs:
|
||||
mkdocs build
|
||||
|
||||
docs-dev:
|
||||
mkdocs serve
|
||||
|
||||
23
README.md
23
README.md
@@ -3,22 +3,33 @@
|
||||
a CalDAV/CardDAV server
|
||||
|
||||
> [!WARNING]
|
||||
> RustiCal is **not production-ready!**
|
||||
> I'm just starting to use it myself so I cannot guarantee that everything will be working smoothly just yet.
|
||||
> I hope there won't be any manual migrations anymore but if you want to be an early adopter some SQL knowledge might be useful just in case.
|
||||
> If you still want to play around with it in its current state, absolutely feel free to do so and to open up an issue if something is not working. :)
|
||||
RustiCal is under **active development**!
|
||||
While I've been successfully using RustiCal productively for a few weeks now,
|
||||
you'd still be one of the first testers so expect bugs and rough edges.
|
||||
If you still want to play around with it in its current state, absolutely feel free to do so and to open up an issue if something is not working. :)
|
||||
|
||||
## Features
|
||||
|
||||
- easy to backup, everything saved in one SQLite database
|
||||
- ~~[WebDAV Push](https://github.com/bitfireAT/webdav-push/) support, so near-instant synchronisation to DAVx5~~ (currently broken)
|
||||
- also export feature in the frontend
|
||||
- **[WebDAV Push](https://github.com/bitfireAT/webdav-push/)** support, so near-instant synchronisation to DAVx5
|
||||
- lightweight (the container image contains only one binary)
|
||||
- adequately fast (I'd love to say blazingly fast™ :fire: but I don't have any benchmarks)
|
||||
- deleted calendars are recoverable
|
||||
- Nextcloud login flow (In DAVx5 you can login through the Nextcloud flow and automatically generate an app token)
|
||||
- Apple configuration profiles (skip copy-pasting passwords and instead generate the configuration in the frontend)
|
||||
- OpenID Connect support (with option to disable password login)
|
||||
- **OpenID Connect** support (with option to disable password login)
|
||||
- Group-based **sharing**
|
||||
|
||||
## Getting Started
|
||||
|
||||
- Check out the [documentation](https://lennart-k.github.io/rustical/installation/)
|
||||
|
||||
## Tested Clients
|
||||
|
||||
- DAVx5,
|
||||
- GNOME Accounts, GNOME Calendar, GNOME Contacts
|
||||
- Evolution
|
||||
- Apple Calendar
|
||||
- Home Assistant integration
|
||||
- Thunderbird
|
||||
|
||||
@@ -7,5 +7,6 @@ accepted = [
|
||||
"CDLA-Permissive-2.0",
|
||||
"Zlib",
|
||||
"AGPL-3.0",
|
||||
"MPL-2.0",
|
||||
]
|
||||
workarounds = ["ring", "chrono", "rustls"]
|
||||
|
||||
22
compose.oidc.yml
Normal file
22
compose.oidc.yml
Normal file
@@ -0,0 +1,22 @@
|
||||
services:
|
||||
rustical:
|
||||
image: ghcr.io/lennart-k/rustical:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
RUSTICAL_FRONTEND__ALLOW_PASSWORD_LOGIN: "false"
|
||||
RUSTICAL_OIDC__NAME: "Authelia"
|
||||
RUSTICAL_OIDC__ISSUER: "https://auth.example.com"
|
||||
RUSTICAL_OIDC__CLIENT_ID: "{{ rustical_oidc_client_id }}"
|
||||
RUSTICAL_OIDC__CLIENT_SECRET: "{{ rustical_oidc_client_secret }}"
|
||||
RUSTICAL_OIDC__CLAIM_USERID: "preferred_username"
|
||||
RUSTICAL_OIDC__SCOPES: '["openid", "profile", "groups"]'
|
||||
RUSTICAL_OIDC__REQUIRE_GROUP: "app:rustical" # optional
|
||||
RUSTICAL_OIDC__ALLOW_SIGN_UP: "true"
|
||||
volumes:
|
||||
- data:/var/lib/rustical
|
||||
# Here you probably want to you expose instead
|
||||
ports:
|
||||
- 4000:4000
|
||||
|
||||
volumes:
|
||||
data:
|
||||
@@ -4,8 +4,15 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dev-dependencies]
|
||||
rustical_store_sqlite = { workspace = true, features = ["test"] }
|
||||
rstest.workspace = true
|
||||
async-std.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
axum-extra.workspace = true
|
||||
@@ -34,3 +41,6 @@ rustical_ical.workspace = true
|
||||
http.workspace = true
|
||||
headers.workspace = true
|
||||
tower-http.workspace = true
|
||||
strum.workspace = true
|
||||
strum_macros.workspace = true
|
||||
vtimezones-rs.workspace = true
|
||||
|
||||
@@ -4,12 +4,12 @@ use axum::body::Body;
|
||||
use axum::extract::State;
|
||||
use axum::{extract::Path, response::Response};
|
||||
use headers::{ContentType, HeaderMapExt};
|
||||
use http::{HeaderValue, StatusCode, header};
|
||||
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, JournalObject, TodoObject};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::User};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
@@ -18,18 +18,23 @@ use tracing::instrument;
|
||||
pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, calendar_id)): Path<(String, String)>,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let calendar = cal_store.get_calendar(&principal, &calendar_id).await?;
|
||||
let calendar = cal_store
|
||||
.get_calendar(&principal, &calendar_id, true)
|
||||
.await?;
|
||||
if !user.is_principal(&calendar.principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let calendar = cal_store.get_calendar(&principal, &calendar_id).await?;
|
||||
let calendar = cal_store
|
||||
.get_calendar(&principal, &calendar_id, true)
|
||||
.await?;
|
||||
|
||||
let mut timezones = HashMap::new();
|
||||
let objects = cal_store.get_objects(&principal, &calendar_id).await?;
|
||||
@@ -58,14 +63,6 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
params: None,
|
||||
});
|
||||
}
|
||||
if calendar.color.is_some() {
|
||||
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||
name: "X-RUSTICAL-COLOR".to_owned(),
|
||||
value: calendar.color,
|
||||
params: None,
|
||||
});
|
||||
}
|
||||
let mut ical_calendar = ical_calendar_builder.build();
|
||||
|
||||
for object in &objects {
|
||||
match object.get_data() {
|
||||
@@ -75,17 +72,21 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
..
|
||||
}) => {
|
||||
timezones.extend(object_timezones);
|
||||
ical_calendar.events.push(event.clone());
|
||||
ical_calendar_builder = ical_calendar_builder.add_event(event.clone());
|
||||
}
|
||||
CalendarObjectComponent::Todo(TodoObject { todo, .. }) => {
|
||||
ical_calendar.todos.push(todo.clone());
|
||||
CalendarObjectComponent::Todo(TodoObject(todo)) => {
|
||||
ical_calendar_builder = ical_calendar_builder.add_todo(todo.clone());
|
||||
}
|
||||
CalendarObjectComponent::Journal(JournalObject { journal, .. }) => {
|
||||
ical_calendar.journals.push(journal.clone());
|
||||
CalendarObjectComponent::Journal(JournalObject(journal)) => {
|
||||
ical_calendar_builder = ical_calendar_builder.add_journal(journal.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let ical_calendar = ical_calendar_builder
|
||||
.build()
|
||||
.map_err(|parser_error| Error::IcalError(parser_error.into()))?;
|
||||
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ContentType::from_str("text/calendar").unwrap());
|
||||
@@ -99,5 +100,9 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
Ok(resp.body(Body::new(ical_calendar.generate())).unwrap())
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(ical_calendar.generate())).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ use crate::calendar::prop::SupportedCalendarComponentSet;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use http::{Method, StatusCode};
|
||||
use ical::IcalParser;
|
||||
use rustical_dav::xml::HrefElement;
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::{Calendar, CalendarStore, SubscriptionStore};
|
||||
use rustical_xml::{Unparsed, XmlDeserialize, XmlDocument, XmlRootTag};
|
||||
use tracing::instrument;
|
||||
@@ -29,6 +31,8 @@ pub struct MkcolCalendarProp {
|
||||
resourcetype: Option<Unparsed>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
supported_calendar_component_set: Option<SupportedCalendarComponentSet>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALENDARSERVER")]
|
||||
source: Option<HrefElement>,
|
||||
// Ignore that property, we don't support it but also don't want to throw an error
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
#[allow(dead_code)]
|
||||
@@ -60,7 +64,7 @@ struct MkcolRequest {
|
||||
#[instrument(skip(cal_store))]
|
||||
pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
method: Method,
|
||||
body: String,
|
||||
@@ -69,24 +73,53 @@ pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let request = match method.as_str() {
|
||||
let mut request = match method.as_str() {
|
||||
"MKCALENDAR" => MkcalendarRequest::parse_str(&body)?.set.prop,
|
||||
"MKCOL" => MkcolRequest::parse_str(&body)?.set.prop,
|
||||
_ => unreachable!("We never call with another method"),
|
||||
};
|
||||
|
||||
if let Some("") = request.displayname.as_deref() {
|
||||
request.displayname = None
|
||||
}
|
||||
|
||||
let timezone_id = if let Some(tzid) = request.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())
|
||||
.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()))?;
|
||||
|
||||
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(|_| rustical_dav::Error::BadRequest("No timezone data provided".to_owned()))?;
|
||||
|
||||
Some(timezone.name().to_owned())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let calendar = Calendar {
|
||||
id: cal_id.to_owned(),
|
||||
principal: principal.to_owned(),
|
||||
order: request.calendar_order.unwrap_or(0),
|
||||
displayname: request.displayname,
|
||||
timezone: request.calendar_timezone,
|
||||
timezone_id: request.calendar_timezone_id,
|
||||
timezone_id,
|
||||
color: request.calendar_color,
|
||||
description: request.calendar_description,
|
||||
deleted_at: None,
|
||||
synctoken: 0,
|
||||
subscription_url: None,
|
||||
subscription_url: request.source.map(|href| href.href),
|
||||
push_topic: uuid::Uuid::new_v4().to_string(),
|
||||
components: request
|
||||
.supported_calendar_component_set
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
pub mod mkcalendar;
|
||||
// pub mod post;
|
||||
pub mod get;
|
||||
pub mod put;
|
||||
pub mod mkcalendar;
|
||||
pub mod post;
|
||||
pub mod report;
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use crate::Error;
|
||||
use crate::calendar::resource::{CalendarResource, CalendarResourceService};
|
||||
use crate::calendar::CalendarResourceService;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use http::{HeaderMap, StatusCode, header};
|
||||
use http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
use rustical_dav::resource::Resource;
|
||||
use rustical_dav_push::register::PushRegister;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::{CalendarStore, Subscription, SubscriptionStore};
|
||||
use rustical_xml::XmlDocument;
|
||||
use tracing::instrument;
|
||||
@@ -14,7 +15,7 @@ use tracing::instrument;
|
||||
#[instrument(skip(resource_service))]
|
||||
pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
State(resource_service): State<CalendarResourceService<C, S>>,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
@@ -24,7 +25,7 @@ pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
||||
|
||||
let calendar = resource_service
|
||||
.cal_store
|
||||
.get_calendar(&principal, &cal_id)
|
||||
.get_calendar(&principal, &cal_id, false)
|
||||
.await?;
|
||||
let calendar_resource = CalendarResource {
|
||||
cal: calendar,
|
||||
@@ -73,20 +74,17 @@ pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
||||
.upsert_subscription(subscription)
|
||||
.await?;
|
||||
|
||||
// let location = req
|
||||
// .resource_map()
|
||||
// .url_for(&req, "subscription", &[sub_id])
|
||||
// .unwrap();
|
||||
//
|
||||
let location = "asd";
|
||||
// TODO: make nicer
|
||||
let location = format!("/push_subscription/{sub_id}");
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
HeaderMap::from_iter([(header::LOCATION, location)]),
|
||||
HeaderMap::from_iter([
|
||||
(header::LOCATION, HeaderValue::from_str(&location).unwrap()),
|
||||
(
|
||||
header::EXPIRES,
|
||||
HeaderValue::from_str(&expires.to_rfc2822()).unwrap(),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.into_response());
|
||||
|
||||
Ok(HttpResponse::Created()
|
||||
.append_header((header::LOCATION, location.to_string()))
|
||||
.append_header((header::EXPIRES, expires.to_rfc2822()))
|
||||
.finish())
|
||||
.into_response())
|
||||
}
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::calendar::prop::SupportedCalendarComponent;
|
||||
use crate::calendar::{self, CalendarResourceService};
|
||||
use crate::{Error, calendar_set};
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use ical::generator::Emitter;
|
||||
use ical::parser::ical::component::IcalTimeZone;
|
||||
use ical::{IcalParser, parser::Component};
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_store::{Calendar, CalendarStore, SubscriptionStore, auth::User};
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(cal_store))]
|
||||
pub async fn route_put<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
user: User,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let mut parser = IcalParser::new(body.as_bytes());
|
||||
let cal = parser
|
||||
.next()
|
||||
.ok_or(rustical_ical::Error::MissingCalendar)?
|
||||
.map_err(rustical_ical::Error::from)?;
|
||||
if parser.next().is_some() {
|
||||
return Err(rustical_ical::Error::InvalidData(
|
||||
"multiple calendars, only one allowed".to_owned(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
if !cal.alarms.is_empty() || !cal.free_busys.is_empty() {
|
||||
return Err(rustical_ical::Error::InvalidData(
|
||||
"Importer does not support VALARM and VFREEBUSY components".to_owned(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
let mut objects = vec![];
|
||||
for event in cal.events {}
|
||||
for todo in cal.todos {}
|
||||
for journal in cal.journals {}
|
||||
|
||||
let timezones: HashMap<String, IcalTimeZone> = cal
|
||||
.timezones
|
||||
.clone()
|
||||
.into_iter()
|
||||
.filter_map(|timezone| {
|
||||
let timezone_prop = timezone.get_property("TZID")?.to_owned();
|
||||
let tzid = timezone_prop.value?;
|
||||
Some((tzid, timezone))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let displayname = cal.get_property("X-WR-CALNAME").and_then(|prop| prop.value);
|
||||
let description = cal.get_property("X-WR-CALDESC").and_then(|prop| prop.value);
|
||||
let color = cal
|
||||
.get_property("X-RUSTICAL-COLOR")
|
||||
.and_then(|prop| prop.value);
|
||||
let timezone_id = cal
|
||||
.get_property("X-WR-TIMEZONE")
|
||||
.and_then(|prop| prop.value);
|
||||
let timezone = timezone_id
|
||||
.and_then(|tzid| timezones.get(&tzid))
|
||||
.map(|timezone| timezone.generate());
|
||||
|
||||
let mut components = vec![CalendarObjectType::Event, CalendarObjectType::Todo];
|
||||
if !cal.journals.is_empty() {
|
||||
components.push(CalendarObjectType::Journal);
|
||||
}
|
||||
|
||||
let calendar = Calendar {
|
||||
principal: principal.clone(),
|
||||
id: cal_id,
|
||||
displayname,
|
||||
description,
|
||||
color,
|
||||
timezone_id,
|
||||
timezone,
|
||||
components,
|
||||
subscription_url: None,
|
||||
push_topic: uuid::Uuid::new_v4().to_string(),
|
||||
synctoken: 0,
|
||||
deleted_at: None,
|
||||
order: 0,
|
||||
};
|
||||
|
||||
cal_store
|
||||
.import_calendar(&principal, calendar, objects)
|
||||
.await?;
|
||||
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
|
||||
if 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).await {
|
||||
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()),
|
||||
Err(err) => return Err(err.into()),
|
||||
|
||||
@@ -16,6 +16,7 @@ pub(crate) struct TimeRangeElement {
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
#[allow(dead_code)]
|
||||
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.3
|
||||
struct ParamFilterElement {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
is_not_defined: Option<()>,
|
||||
@@ -32,11 +33,13 @@ struct TextMatchElement {
|
||||
#[xml(ty = "attr")]
|
||||
collation: String,
|
||||
#[xml(ty = "attr")]
|
||||
negate_collation: String,
|
||||
// "yes" or "no", default: "no"
|
||||
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")]
|
||||
is_not_defined: Option<()>,
|
||||
@@ -46,6 +49,9 @@ pub(crate) struct PropFilterElement {
|
||||
text_match: Option<TextMatchElement>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
|
||||
param_filter: Vec<ParamFilterElement>,
|
||||
|
||||
#[xml(ty = "attr")]
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
@@ -61,7 +67,7 @@ pub(crate) struct CompFilterElement {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
|
||||
pub(crate) comp_filter: Vec<CompFilterElement>,
|
||||
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", ty = "attr")]
|
||||
#[xml(ty = "attr")]
|
||||
pub(crate) name: String,
|
||||
}
|
||||
|
||||
@@ -203,3 +209,102 @@ pub async fn get_objects_calendar_query<C: CalendarStore>(
|
||||
}
|
||||
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},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn calendar_query_7_8_7() {
|
||||
const INPUT: &str = r#"
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<C:calendar-query xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:prop xmlns:D="DAV:">
|
||||
<D:getetag/>
|
||||
<C:calendar-data/>
|
||||
</D:prop>
|
||||
<C:filter>
|
||||
<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>
|
||||
</C:calendar-query>
|
||||
"#;
|
||||
|
||||
let report = ReportRequest::parse_str(INPUT).unwrap();
|
||||
let calendar_query: CalendarQueryRequest =
|
||||
if let ReportRequest::CalendarQuery(query) = report {
|
||||
query
|
||||
} else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(
|
||||
calendar_query,
|
||||
CalendarQueryRequest {
|
||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(
|
||||
vec![
|
||||
CalendarObjectPropWrapperName::CalendarObject(
|
||||
CalendarObjectPropName::Getetag,
|
||||
),
|
||||
CalendarObjectPropWrapperName::CalendarObject(
|
||||
CalendarObjectPropName::CalendarData(Default::default())
|
||||
),
|
||||
],
|
||||
vec![]
|
||||
)),
|
||||
filter: Some(FilterElement {
|
||||
comp_filter: CompFilterElement {
|
||||
is_not_defined: None,
|
||||
time_range: None,
|
||||
prop_filter: vec![],
|
||||
comp_filter: vec![CompFilterElement {
|
||||
prop_filter: vec![PropFilterElement {
|
||||
name: "ATTENDEE".to_owned(),
|
||||
text_match: Some(TextMatchElement {
|
||||
collation: "i;ascii-casemap".to_owned(),
|
||||
negate_condition: None
|
||||
}),
|
||||
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
|
||||
}),
|
||||
}],
|
||||
time_range: None
|
||||
}],
|
||||
comp_filter: vec![],
|
||||
is_not_defined: None,
|
||||
name: "VEVENT".to_owned(),
|
||||
time_range: None
|
||||
}],
|
||||
name: "VCALENDAR".to_owned()
|
||||
}
|
||||
}),
|
||||
timezone: None,
|
||||
timezone_id: None
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ use rustical_dav::{
|
||||
},
|
||||
};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::User};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_xml::{XmlDeserialize, XmlDocument};
|
||||
use sync_collection::handle_sync_collection;
|
||||
use tracing::instrument;
|
||||
@@ -56,7 +56,7 @@ fn objects_response(
|
||||
path: &str,
|
||||
principal: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
prop: &PropfindType<CalendarObjectPropWrapperName>,
|
||||
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
|
||||
let mut responses = Vec::new();
|
||||
@@ -67,7 +67,7 @@ fn objects_response(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, prop, puri, user)?,
|
||||
.propfind(&path, prop, None, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ fn objects_response(
|
||||
#[instrument(skip(cal_store))]
|
||||
pub async fn route_report_calendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
Extension(puri): Extension<CalDavPrincipalUri>,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
OriginalUri(uri): OriginalUri,
|
||||
@@ -149,7 +149,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::calendar_object::{CalendarData, CalendarObjectPropName, ExpandElement};
|
||||
use calendar_query::{CompFilterElement, FilterElement, TimeRangeElement};
|
||||
use rustical_dav::xml::PropElement;
|
||||
use rustical_dav::{extensions::CommonPropertiesPropName, xml::PropElement};
|
||||
use rustical_ical::UtcDateTime;
|
||||
use rustical_xml::{NamespaceOwned, ValueDeserialize};
|
||||
|
||||
@@ -160,7 +160,6 @@ mod tests {
|
||||
<calendar-multiget xmlns="urn:ietf:params:xml:ns:caldav" xmlns:D="DAV:">
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<D:displayname/>
|
||||
<calendar-data>
|
||||
<expand start="20250426T220000Z" end="20250503T220000Z"/>
|
||||
</calendar-data>
|
||||
@@ -180,7 +179,7 @@ mod tests {
|
||||
end: <UtcDateTime as ValueDeserialize>::deserialize("20250503T220000Z").unwrap(),
|
||||
}), limit_recurrence_set: None, limit_freebusy_set: None }
|
||||
)),
|
||||
], vec![(Some(NamespaceOwned(Vec::from("DAV:"))), "displayname".to_string())])),
|
||||
], vec![])),
|
||||
href: vec![
|
||||
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
||||
]
|
||||
@@ -253,6 +252,7 @@ mod tests {
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<D:displayname/>
|
||||
<D:invalid-prop/>
|
||||
</D:prop>
|
||||
<D:href>/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b</D:href>
|
||||
</calendar-multiget>
|
||||
@@ -263,7 +263,8 @@ mod tests {
|
||||
ReportRequest::CalendarMultiget(CalendarMultigetRequest {
|
||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
||||
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::Getetag),
|
||||
], vec![(Some(NamespaceOwned(Vec::from("DAV:"))), "displayname".to_string())])),
|
||||
CalendarObjectPropWrapperName::Common(CommonPropertiesPropName::Displayname),
|
||||
], vec![(Some(NamespaceOwned(Vec::from("DAV:"))), "invalid-prop".to_string())])),
|
||||
href: vec![
|
||||
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
||||
]
|
||||
|
||||
@@ -13,7 +13,7 @@ use rustical_dav::{
|
||||
};
|
||||
use rustical_store::{
|
||||
CalendarStore,
|
||||
auth::User,
|
||||
auth::Principal,
|
||||
synctoken::{format_synctoken, parse_synctoken},
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ pub async fn handle_sync_collection<C: CalendarStore>(
|
||||
sync_collection: &SyncCollectionRequest<CalendarObjectPropWrapperName>,
|
||||
path: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
cal_store: &C,
|
||||
@@ -39,7 +39,7 @@ pub async fn handle_sync_collection<C: CalendarStore>(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, &sync_collection.prop, puri, user)?,
|
||||
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,3 +4,6 @@ pub mod resource;
|
||||
mod service;
|
||||
|
||||
pub use service::CalendarResourceService;
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use derive_more::derive::{From, Into};
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use strum_macros::VariantArray;
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, From, Into)]
|
||||
pub struct SupportedCalendarComponent {
|
||||
@@ -58,39 +59,12 @@ pub struct SupportedCalendarData {
|
||||
calendar_data: CalendarData,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
|
||||
pub enum ReportMethod {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
CalendarQuery,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
CalendarMultiget,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
SyncCollection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct ReportWrapper {
|
||||
report: ReportMethod,
|
||||
}
|
||||
|
||||
// RFC 3253 section-3.1.5
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportSet {
|
||||
#[xml(flatten)]
|
||||
supported_report: Vec<ReportWrapper>,
|
||||
}
|
||||
|
||||
impl Default for SupportedReportSet {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
supported_report: vec![
|
||||
ReportWrapper {
|
||||
report: ReportMethod::CalendarQuery,
|
||||
},
|
||||
ReportWrapper {
|
||||
report: ReportMethod::CalendarMultiget,
|
||||
},
|
||||
ReportWrapper {
|
||||
report: ReportMethod::SyncCollection,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,26 @@
|
||||
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData, SupportedReportSet};
|
||||
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData};
|
||||
use crate::Error;
|
||||
use crate::calendar::prop::ReportMethod;
|
||||
use chrono::{DateTime, Utc};
|
||||
use derive_more::derive::{From, Into};
|
||||
use ical::IcalParser;
|
||||
use rustical_dav::extensions::{
|
||||
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
|
||||
};
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
||||
use rustical_dav_push::DavPushExtension;
|
||||
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::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_xml::{EnumVariants, PropName};
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use std::str::FromStr;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "CalendarPropName")]
|
||||
pub enum CalendarProp {
|
||||
// WebDAV (RFC 2518)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(Option<String>),
|
||||
|
||||
// CalDAV (RFC 4791)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_ICAL")]
|
||||
CalendarColor(Option<String>),
|
||||
@@ -37,15 +35,15 @@ pub enum CalendarProp {
|
||||
CalendarTimezoneId(Option<String>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_ICAL")]
|
||||
CalendarOrder(Option<i64>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
SupportedCalendarComponentSet(SupportedCalendarComponentSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
||||
SupportedCalendarData(SupportedCalendarData),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
MaxResourceSize(i64),
|
||||
#[xml(skip_deserializing)]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
SupportedReportSet(SupportedReportSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALENDARSERVER")]
|
||||
Source(Option<HrefElement>),
|
||||
#[xml(skip_deserializing)]
|
||||
@@ -61,11 +59,11 @@ pub enum CalendarProp {
|
||||
pub enum CalendarPropWrapper {
|
||||
Calendar(CalendarProp),
|
||||
SyncToken(SyncTokenExtensionProp),
|
||||
// DavPush(DavPushExtensionProp),
|
||||
DavPush(DavPushExtensionProp),
|
||||
Common(CommonPropertiesProp),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, From, Into)]
|
||||
#[derive(Clone, Debug, From, Into, Deserialize)]
|
||||
pub struct CalendarResource {
|
||||
pub cal: Calendar,
|
||||
pub read_only: bool,
|
||||
@@ -98,9 +96,11 @@ impl DavPushExtension for CalendarResource {
|
||||
impl Resource for CalendarResource {
|
||||
type Prop = CalendarPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
|
||||
const IS_COLLECTION: bool = true;
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
if self.cal.subscription_url.is_none() {
|
||||
@@ -122,14 +122,11 @@ impl Resource for CalendarResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
prop: &CalendarPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
CalendarPropWrapperName::Calendar(prop) => CalendarPropWrapper::Calendar(match prop {
|
||||
CalendarPropName::Displayname => {
|
||||
CalendarProp::Displayname(self.cal.displayname.clone())
|
||||
}
|
||||
CalendarPropName::CalendarColor => {
|
||||
CalendarProp::CalendarColor(self.cal.color.clone())
|
||||
}
|
||||
@@ -137,7 +134,9 @@ impl Resource for CalendarResource {
|
||||
CalendarProp::CalendarDescription(self.cal.description.clone())
|
||||
}
|
||||
CalendarPropName::CalendarTimezone => {
|
||||
CalendarProp::CalendarTimezone(self.cal.timezone.clone())
|
||||
CalendarProp::CalendarTimezone(self.cal.timezone_id.as_ref().and_then(|tzid| {
|
||||
vtimezones_rs::VTIMEZONES.get(tzid).map(|tz| tz.to_string())
|
||||
}))
|
||||
}
|
||||
// chrono_tz uses the IANA database
|
||||
CalendarPropName::TimezoneServiceSet => CalendarProp::TimezoneServiceSet(
|
||||
@@ -157,7 +156,7 @@ impl Resource for CalendarResource {
|
||||
}
|
||||
CalendarPropName::MaxResourceSize => CalendarProp::MaxResourceSize(10000000),
|
||||
CalendarPropName::SupportedReportSet => {
|
||||
CalendarProp::SupportedReportSet(SupportedReportSet::default())
|
||||
CalendarProp::SupportedReportSet(SupportedReportSet::all())
|
||||
}
|
||||
CalendarPropName::Source => CalendarProp::Source(
|
||||
self.cal.subscription_url.to_owned().map(HrefElement::from),
|
||||
@@ -172,9 +171,9 @@ impl Resource for CalendarResource {
|
||||
CalendarPropWrapperName::SyncToken(prop) => {
|
||||
CalendarPropWrapper::SyncToken(SyncTokenExtension::get_prop(self, prop)?)
|
||||
}
|
||||
// CalendarPropWrapperName::DavPush(prop) => {
|
||||
// CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?)
|
||||
// }
|
||||
CalendarPropWrapperName::DavPush(prop) => {
|
||||
CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?)
|
||||
}
|
||||
CalendarPropWrapperName::Common(prop) => CalendarPropWrapper::Common(
|
||||
CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
|
||||
),
|
||||
@@ -187,10 +186,6 @@ impl Resource for CalendarResource {
|
||||
}
|
||||
match prop {
|
||||
CalendarPropWrapper::Calendar(prop) => match prop {
|
||||
CalendarProp::Displayname(displayname) => {
|
||||
self.cal.displayname = displayname;
|
||||
Ok(())
|
||||
}
|
||||
CalendarProp::CalendarColor(color) => {
|
||||
self.cal.color = color;
|
||||
Ok(())
|
||||
@@ -200,21 +195,42 @@ impl Resource for CalendarResource {
|
||||
Ok(())
|
||||
}
|
||||
CalendarProp::CalendarTimezone(timezone) => {
|
||||
// TODO: Ensure that timezone-id is also updated
|
||||
self.cal.timezone = timezone;
|
||||
if let Some(tz) = timezone {
|
||||
// TODO: Proper error (calendar-timezone precondition)
|
||||
let calendar = IcalParser::new(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(),
|
||||
)
|
||||
})?;
|
||||
|
||||
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(|_| {
|
||||
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 {
|
||||
// Validate timezone id
|
||||
chrono_tz::Tz::from_str(tzid).map_err(|_| {
|
||||
rustical_dav::Error::BadRequest(format!(
|
||||
"Invalid timezone-id: {}",
|
||||
tzid
|
||||
))
|
||||
})?;
|
||||
// TODO: Ensure that timezone is also updated (For now hope that clients play nice)
|
||||
if !vtimezones_rs::VTIMEZONES.contains_key(tzid) {
|
||||
return Err(rustical_dav::Error::BadRequest(format!(
|
||||
"Invalid timezone-id: {tzid}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
self.cal.timezone_id = timezone_id;
|
||||
Ok(())
|
||||
@@ -236,7 +252,7 @@ impl Resource for CalendarResource {
|
||||
CalendarProp::MaxDateTime(_) => Err(rustical_dav::Error::PropReadOnly),
|
||||
},
|
||||
CalendarPropWrapper::SyncToken(prop) => SyncTokenExtension::set_prop(self, prop),
|
||||
// CalendarPropWrapper::DavPush(prop) => DavPushExtension::set_prop(self, prop),
|
||||
CalendarPropWrapper::DavPush(prop) => DavPushExtension::set_prop(self, prop),
|
||||
CalendarPropWrapper::Common(prop) => CommonPropertiesExtension::set_prop(self, prop),
|
||||
}
|
||||
}
|
||||
@@ -247,10 +263,6 @@ impl Resource for CalendarResource {
|
||||
}
|
||||
match prop {
|
||||
CalendarPropWrapperName::Calendar(prop) => match prop {
|
||||
CalendarPropName::Displayname => {
|
||||
self.cal.displayname = None;
|
||||
Ok(())
|
||||
}
|
||||
CalendarPropName::CalendarColor => {
|
||||
self.cal.color = None;
|
||||
Ok(())
|
||||
@@ -259,15 +271,11 @@ impl Resource for CalendarResource {
|
||||
self.cal.description = None;
|
||||
Ok(())
|
||||
}
|
||||
CalendarPropName::CalendarTimezone => {
|
||||
self.cal.timezone = None;
|
||||
Ok(())
|
||||
}
|
||||
CalendarPropName::TimezoneServiceSet => Err(rustical_dav::Error::PropReadOnly),
|
||||
CalendarPropName::CalendarTimezoneId => {
|
||||
CalendarPropName::CalendarTimezone | CalendarPropName::CalendarTimezoneId => {
|
||||
self.cal.timezone_id = None;
|
||||
Ok(())
|
||||
}
|
||||
CalendarPropName::TimezoneServiceSet => Err(rustical_dav::Error::PropReadOnly),
|
||||
CalendarPropName::CalendarOrder => {
|
||||
self.cal.order = 0;
|
||||
Ok(())
|
||||
@@ -284,19 +292,32 @@ impl Resource for CalendarResource {
|
||||
CalendarPropName::MaxDateTime => Err(rustical_dav::Error::PropReadOnly),
|
||||
},
|
||||
CalendarPropWrapperName::SyncToken(prop) => SyncTokenExtension::remove_prop(self, prop),
|
||||
// CalendarPropWrapperName::DavPush(prop) => DavPushExtension::remove_prop(self, prop),
|
||||
CalendarPropWrapperName::DavPush(prop) => DavPushExtension::remove_prop(self, prop),
|
||||
CalendarPropWrapperName::Common(prop) => {
|
||||
CommonPropertiesExtension::remove_prop(self, prop)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
self.cal.displayname.as_deref()
|
||||
}
|
||||
fn set_displayname(&mut self, name: Option<String>) -> Result<(), rustical_dav::Error> {
|
||||
self.cal.displayname = name;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.cal.principal)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
if self.cal.subscription_url.is_some() || self.read_only {
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
if self.cal.subscription_url.is_some() {
|
||||
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),
|
||||
));
|
||||
@@ -307,3 +328,15 @@ impl Resource for CalendarResource {
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn test_tzdb_version() {
|
||||
// Ensure that both chrono_tz and vzic_rs use the same tzdb version
|
||||
assert_eq!(
|
||||
chrono_tz::IANA_TZDB_VERSION,
|
||||
vtimezones_rs::IANA_TZDB_VERSION
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::calendar::methods::get::route_get;
|
||||
use crate::calendar::methods::mkcalendar::route_mkcalendar;
|
||||
use crate::calendar::methods::post::route_post;
|
||||
use crate::calendar::methods::report::route_report_calendar;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use crate::calendar_object::CalendarObjectResourceService;
|
||||
@@ -12,7 +13,7 @@ use axum::handler::Handler;
|
||||
use axum::response::Response;
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
@@ -47,19 +48,23 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
|
||||
type PathComponents = (String, String); // principal, calendar_id
|
||||
type Resource = CalendarResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access, webdav-push";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal, cal_id): &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Error> {
|
||||
let calendar = self.cal_store.get_calendar(principal, cal_id).await?;
|
||||
let calendar = self
|
||||
.cal_store
|
||||
.get_calendar(principal, cal_id, show_deleted)
|
||||
.await?;
|
||||
Ok(CalendarResource {
|
||||
cal: calendar,
|
||||
read_only: self.cal_store.is_read_only(),
|
||||
read_only: self.cal_store.is_read_only(cal_id),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -126,6 +131,13 @@ impl<C: CalendarStore, S: SubscriptionStore> AxumMethods for CalendarResourceSer
|
||||
})
|
||||
}
|
||||
|
||||
fn post() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||
Some(|state, req| {
|
||||
let mut service = Handler::with_state(route_post::<C, S>, state);
|
||||
Box::pin(Service::call(&mut service, req))
|
||||
})
|
||||
}
|
||||
|
||||
fn mkcalendar() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>>
|
||||
{
|
||||
Some(|state, req| {
|
||||
|
||||
222
crates/caldav/src/calendar/test_files/propfind.outputs
Normal file
222
crates/caldav/src/calendar/test_files/propfind.outputs
Normal file
@@ -0,0 +1,222 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<response xmlns:CS="http://calendarserver.org/ns/" xmlns:CARD="urn:ietf:params:xml:ns:carddav" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns="DAV:" 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:CS="http://calendarserver.org/ns/" xmlns:CARD="urn:ietf:params:xml:ns:carddav" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns="DAV:" 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>
|
||||
@@ -0,0 +1,11 @@
|
||||
[
|
||||
{
|
||||
"id": "user",
|
||||
"displayname": null,
|
||||
"principal_type": "individual",
|
||||
"password": null,
|
||||
"memberships": [
|
||||
"group"
|
||||
]
|
||||
}
|
||||
]
|
||||
6
crates/caldav/src/calendar/test_files/propfind.requests
Normal file
6
crates/caldav/src/calendar/test_files/propfind.requests
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<propfind xmlns="DAV:"><propname/></propfind>
|
||||
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<propfind xmlns="DAV:"><allprop/></propfind>
|
||||
@@ -0,0 +1,42 @@
|
||||
[
|
||||
{
|
||||
"cal": {
|
||||
"principal": "user",
|
||||
"id": "calendar",
|
||||
"displayname": "Calendar",
|
||||
"order": 0,
|
||||
"description": null,
|
||||
"color": null,
|
||||
"timezone_id": "Europe/Berlin",
|
||||
"deleted_at": null,
|
||||
"synctoken": 12,
|
||||
"subscription_url": null,
|
||||
"push_topic": "b28b41e9-8801-4fc5-ae29-8efb5fadeb36",
|
||||
"components": [
|
||||
"VEVENT",
|
||||
"VTODO"
|
||||
]
|
||||
},
|
||||
"read_only": true
|
||||
},
|
||||
{
|
||||
"cal": {
|
||||
"principal": "user",
|
||||
"id": "calendar",
|
||||
"displayname": "Calendar",
|
||||
"order": 0,
|
||||
"description": null,
|
||||
"color": null,
|
||||
"timezone_id": "Europe/Berlin",
|
||||
"deleted_at": null,
|
||||
"synctoken": 12,
|
||||
"subscription_url": null,
|
||||
"push_topic": "b28b41e9-8801-4fc5-ae29-8efb5fadeb36",
|
||||
"components": [
|
||||
"VEVENT",
|
||||
"VTODO"
|
||||
]
|
||||
},
|
||||
"read_only": true
|
||||
}
|
||||
]
|
||||
47
crates/caldav/src/calendar/tests.rs
Normal file
47
crates/caldav/src/calendar/tests.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use crate::{CalDavPrincipalUri, calendar::resource::CalendarResource};
|
||||
use rustical_dav::resource::Resource;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_xml::XmlSerializeRoot;
|
||||
use serde_json::from_str;
|
||||
|
||||
// #[tokio::test]
|
||||
async fn test_propfind() {
|
||||
let requests: Vec<_> = include_str!("./test_files/propfind.requests")
|
||||
.trim()
|
||||
.split("\n\n")
|
||||
.collect();
|
||||
let principals: Vec<Principal> =
|
||||
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)
|
||||
{
|
||||
let propfind = CalendarResource::parse_propfind(request).unwrap();
|
||||
|
||||
let response = resource
|
||||
.propfind(
|
||||
&format!("/caldav/principal/{}/{}", principal.id, resource.cal.id),
|
||||
&propfind.prop,
|
||||
propfind.include.as_ref(),
|
||||
&CalDavPrincipalUri("/caldav"),
|
||||
&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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,10 @@ use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::TypedHeader;
|
||||
use headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||
use http::{HeaderMap, StatusCode};
|
||||
use http::{HeaderMap, Method, StatusCode};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::CalendarStore;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
|
||||
@@ -21,26 +21,33 @@ pub async fn get_event<C: CalendarStore>(
|
||||
object_id,
|
||||
}): Path<CalendarObjectPathComponents>,
|
||||
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let calendar = cal_store.get_calendar(&principal, &calendar_id).await?;
|
||||
let calendar = cal_store
|
||||
.get_calendar(&principal, &calendar_id, false)
|
||||
.await?;
|
||||
if !user.is_principal(&calendar.principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let event = cal_store
|
||||
.get_object(&principal, &calendar_id, &object_id)
|
||||
.get_object(&principal, &calendar_id, &object_id, false)
|
||||
.await?;
|
||||
|
||||
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());
|
||||
Ok(resp.body(Body::new(event.get_ics().to_owned())).unwrap())
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(event.get_ics().to_owned())).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(cal_store))]
|
||||
@@ -51,7 +58,7 @@ pub async fn put_event<C: CalendarStore>(
|
||||
object_id,
|
||||
}): Path<CalendarObjectPathComponents>,
|
||||
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
|
||||
header_map: HeaderMap,
|
||||
body: String,
|
||||
@@ -71,12 +78,13 @@ pub async fn put_event<C: CalendarStore>(
|
||||
true
|
||||
};
|
||||
|
||||
let object = match CalendarObject::from_ics(object_id, body) {
|
||||
let object = match CalendarObject::from_ics(body) {
|
||||
Ok(obj) => obj,
|
||||
Err(_) => {
|
||||
return Err(Error::PreconditionFailed(Precondition::ValidCalendarData));
|
||||
}
|
||||
};
|
||||
assert_eq!(object.get_id(), object_id);
|
||||
cal_store
|
||||
.put_object(principal, calendar_id, object, overwrite)
|
||||
.await?;
|
||||
|
||||
@@ -8,7 +8,7 @@ use rustical_dav::{
|
||||
xml::Resourcetype,
|
||||
};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
|
||||
#[derive(Clone, From, Into)]
|
||||
pub struct CalendarObjectResource {
|
||||
@@ -25,9 +25,11 @@ impl ResourceName for CalendarObjectResource {
|
||||
impl Resource for CalendarObjectResource {
|
||||
type Prop = CalendarObjectPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
|
||||
const IS_COLLECTION: bool = false;
|
||||
fn is_collection(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[])
|
||||
@@ -36,7 +38,7 @@ impl Resource for CalendarObjectResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
prop: &CalendarObjectPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
@@ -66,6 +68,10 @@ impl Resource for CalendarObjectResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal)
|
||||
}
|
||||
@@ -74,7 +80,7 @@ impl Resource for CalendarObjectResource {
|
||||
Some(self.object.get_etag())
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.principal),
|
||||
))
|
||||
|
||||
@@ -9,7 +9,7 @@ use async_trait::async_trait;
|
||||
use axum::{extract::Request, handler::Handler, response::Response};
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::{CalendarStore, auth::User};
|
||||
use rustical_store::{CalendarStore, auth::Principal};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::{convert::Infallible, sync::Arc};
|
||||
use tower::Service;
|
||||
@@ -46,7 +46,7 @@ impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
|
||||
type Resource = CalendarObjectResource;
|
||||
type MemberType = CalendarObjectResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||
@@ -58,10 +58,11 @@ impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
|
||||
calendar_id,
|
||||
object_id,
|
||||
}: &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let object = self
|
||||
.cal_store
|
||||
.get_object(principal, calendar_id, object_id)
|
||||
.get_object(principal, calendar_id, object_id, show_deleted)
|
||||
.await?;
|
||||
Ok(CalendarObjectResource {
|
||||
object,
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
use crate::Error;
|
||||
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{Resourcetype, ResourcetypeInner};
|
||||
use rustical_store::auth::User;
|
||||
|
||||
mod service;
|
||||
pub use service::*;
|
||||
mod prop;
|
||||
pub use prop::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CalendarSetResource {
|
||||
pub(crate) principal: String,
|
||||
pub(crate) read_only: bool,
|
||||
pub(crate) name: &'static str,
|
||||
}
|
||||
|
||||
impl ResourceName for CalendarSetResource {
|
||||
fn get_name(&self) -> String {
|
||||
self.name.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Resource for CalendarSetResource {
|
||||
type Prop = PrincipalPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
|
||||
const IS_COLLECTION: bool = true;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[ResourcetypeInner(
|
||||
Some(rustical_dav::namespace::NS_DAV),
|
||||
"collection",
|
||||
)])
|
||||
}
|
||||
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
prop: &PrincipalPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
||||
<Self as CommonPropertiesExtension>::get_prop(self, puri, user, prop)?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(if self.read_only {
|
||||
UserPrivilegeSet::owner_read(user.is_principal(&self.principal))
|
||||
} else {
|
||||
UserPrivilegeSet::owner_only(user.is_principal(&self.principal))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
use rustical_dav::extensions::CommonPropertiesProp;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
||||
pub enum PrincipalPropWrapper {
|
||||
Common(CommonPropertiesProp),
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
use crate::calendar::CalendarResourceService;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use crate::calendar_set::CalendarSetResource;
|
||||
use crate::{CalDavPrincipalUri, Error};
|
||||
use async_trait::async_trait;
|
||||
use axum::Router;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct CalendarSetResourceService<C: CalendarStore, S: SubscriptionStore> {
|
||||
name: &'static str,
|
||||
cal_store: Arc<C>,
|
||||
sub_store: Arc<S>,
|
||||
}
|
||||
|
||||
impl<C: CalendarStore, S: SubscriptionStore> Clone for CalendarSetResourceService<C, S> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
name: self.name,
|
||||
cal_store: self.cal_store.clone(),
|
||||
sub_store: self.sub_store.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: CalendarStore, S: SubscriptionStore> CalendarSetResourceService<C, S> {
|
||||
pub fn new(name: &'static str, cal_store: Arc<C>, sub_store: Arc<S>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
cal_store,
|
||||
sub_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarSetResourceService<C, S> {
|
||||
type PathComponents = (String,);
|
||||
type MemberType = CalendarResource;
|
||||
type Resource = CalendarSetResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, extended-mkcol, calendar-access";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
Ok(CalendarSetResource {
|
||||
principal: principal.to_owned(),
|
||||
read_only: self.cal_store.is_read_only(),
|
||||
name: self.name,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_members(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||
let calendars = self.cal_store.get_calendars(principal).await?;
|
||||
Ok(calendars
|
||||
.into_iter()
|
||||
.map(|cal| CalendarResource {
|
||||
cal,
|
||||
read_only: self.cal_store.is_read_only(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn axum_router<State: Send + Sync + Clone + 'static>(self) -> axum::Router<State> {
|
||||
Router::new()
|
||||
.nest(
|
||||
"/{calendar_id}",
|
||||
CalendarResourceService::new(self.cal_store.clone(), self.sub_store.clone())
|
||||
.axum_router(),
|
||||
)
|
||||
.route_service("/", self.axum_service())
|
||||
}
|
||||
}
|
||||
impl<C: CalendarStore, S: SubscriptionStore> AxumMethods for CalendarSetResourceService<C, S> {}
|
||||
@@ -1,63 +1,48 @@
|
||||
use axum::response::Redirect;
|
||||
use axum::routing::any;
|
||||
use axum::{Extension, Router};
|
||||
use derive_more::Constructor;
|
||||
use principal::PrincipalResourceService;
|
||||
use rustical_dav::resource::{PrincipalUri, ResourceService};
|
||||
use rustical_dav::resources::RootResourceService;
|
||||
use rustical_store::auth::middleware::AuthenticationLayer;
|
||||
use rustical_store::auth::{AuthenticationProvider, User};
|
||||
use rustical_store::{AddressbookStore, CalendarStore, ContactBirthdayStore, SubscriptionStore};
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub mod calendar;
|
||||
pub mod calendar_object;
|
||||
pub mod calendar_set;
|
||||
pub mod error;
|
||||
pub mod principal;
|
||||
// mod subscription;
|
||||
|
||||
pub use error::Error;
|
||||
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct CalDavPrincipalUri(&'static str);
|
||||
|
||||
impl PrincipalUri for CalDavPrincipalUri {
|
||||
fn principal_collection(&self) -> String {
|
||||
format!("{}/principal/", self.0)
|
||||
}
|
||||
fn principal_uri(&self, principal: &str) -> String {
|
||||
format!("{}/principal/{}/", self.0, principal)
|
||||
format!("{}{}/", self.principal_collection(), principal)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn caldav_router<
|
||||
AP: AuthenticationProvider,
|
||||
AS: AddressbookStore,
|
||||
C: CalendarStore,
|
||||
S: SubscriptionStore,
|
||||
>(
|
||||
pub fn caldav_router<AP: AuthenticationProvider, C: CalendarStore, S: SubscriptionStore>(
|
||||
prefix: &'static str,
|
||||
auth_provider: Arc<AP>,
|
||||
store: Arc<C>,
|
||||
addr_store: Arc<AS>,
|
||||
subscription_store: Arc<S>,
|
||||
simplified_home_set: bool,
|
||||
) -> Router {
|
||||
let birthday_store = Arc::new(ContactBirthdayStore::new(addr_store));
|
||||
let principal_service = PrincipalResourceService {
|
||||
auth_provider: auth_provider.clone(),
|
||||
sub_store: subscription_store.clone(),
|
||||
birthday_store: birthday_store.clone(),
|
||||
cal_store: store.clone(),
|
||||
};
|
||||
|
||||
Router::new()
|
||||
.nest(
|
||||
prefix,
|
||||
RootResourceService::<_, User, CalDavPrincipalUri>::new(principal_service.clone())
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CalDavPrincipalUri(prefix))),
|
||||
)
|
||||
.route(
|
||||
"/.well-known/caldav",
|
||||
any(async || Redirect::permanent(prefix)),
|
||||
)
|
||||
Router::new().nest(
|
||||
prefix,
|
||||
RootResourceService::<_, Principal, CalDavPrincipalUri>::new(PrincipalResourceService {
|
||||
auth_provider: auth_provider.clone(),
|
||||
sub_store: subscription_store.clone(),
|
||||
cal_store: store.clone(),
|
||||
simplified_home_set,
|
||||
})
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CalDavPrincipalUri(prefix))),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,18 +2,24 @@ use crate::Error;
|
||||
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
||||
use rustical_store::auth::User;
|
||||
use rustical_dav::xml::{
|
||||
GroupMemberSet, GroupMembership, Resourcetype, ResourcetypeInner, SupportedReportSet,
|
||||
};
|
||||
use rustical_store::auth::Principal;
|
||||
|
||||
mod service;
|
||||
pub use service::*;
|
||||
mod prop;
|
||||
pub use prop::*;
|
||||
#[cfg(test)]
|
||||
pub mod tests;
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PrincipalResource {
|
||||
principal: User,
|
||||
home_set: &'static [&'static str],
|
||||
principal: Principal,
|
||||
members: Vec<String>,
|
||||
// If true only return the principal as the calendar home set, otherwise also groups
|
||||
simplified_home_set: bool,
|
||||
}
|
||||
|
||||
impl ResourceName for PrincipalResource {
|
||||
@@ -25,9 +31,11 @@ impl ResourceName for PrincipalResource {
|
||||
impl Resource for PrincipalResource {
|
||||
type Prop = PrincipalPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
|
||||
const IS_COLLECTION: bool = true;
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[
|
||||
@@ -39,42 +47,58 @@ impl Resource for PrincipalResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
prop: &PrincipalPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
let principal_url = puri.principal_uri(&self.principal.id);
|
||||
|
||||
let home_set = CalendarHomeSet(
|
||||
user.memberships()
|
||||
.into_iter()
|
||||
.map(|principal| puri.principal_uri(principal))
|
||||
.flat_map(|principal_url| {
|
||||
self.home_set.iter().map(move |&home_name| {
|
||||
HrefElement::new(format!("{}{}/", &principal_url, home_name))
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
|
||||
Ok(match prop {
|
||||
PrincipalPropWrapperName::Principal(prop) => {
|
||||
PrincipalPropWrapper::Principal(match prop {
|
||||
PrincipalPropName::CalendarUserType => {
|
||||
PrincipalProp::CalendarUserType(self.principal.principal_type.to_owned())
|
||||
}
|
||||
PrincipalPropName::Displayname => PrincipalProp::Displayname(
|
||||
self.principal
|
||||
.displayname
|
||||
.to_owned()
|
||||
.unwrap_or(self.principal.id.to_owned()),
|
||||
),
|
||||
PrincipalPropName::PrincipalUrl => {
|
||||
PrincipalProp::PrincipalUrl(principal_url.into())
|
||||
}
|
||||
PrincipalPropName::CalendarHomeSet => PrincipalProp::CalendarHomeSet(home_set),
|
||||
PrincipalPropName::CalendarHomeSet => PrincipalProp::CalendarHomeSet(
|
||||
CalendarHomeSet(if self.simplified_home_set {
|
||||
vec![principal_url.into()]
|
||||
} else {
|
||||
self.principal
|
||||
.memberships()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect()
|
||||
}),
|
||||
),
|
||||
PrincipalPropName::CalendarUserAddressSet => {
|
||||
PrincipalProp::CalendarUserAddressSet(principal_url.into())
|
||||
}
|
||||
PrincipalPropName::GroupMemberSet => {
|
||||
PrincipalProp::GroupMemberSet(GroupMemberSet(
|
||||
self.members
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::GroupMembership => {
|
||||
PrincipalProp::GroupMembership(GroupMembership(
|
||||
self.principal
|
||||
.memberships_without_self()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::AlternateUriSet => PrincipalProp::AlternateUriSet,
|
||||
// PrincipalPropName::PrincipalCollectionSet => {
|
||||
// PrincipalProp::PrincipalCollectionSet(puri.principal_collection().into())
|
||||
// }
|
||||
PrincipalPropName::SupportedReportSet => {
|
||||
PrincipalProp::SupportedReportSet(SupportedReportSet::all())
|
||||
}
|
||||
})
|
||||
}
|
||||
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
||||
@@ -83,12 +107,21 @@ impl Resource for PrincipalResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
Some(
|
||||
self.principal
|
||||
.displayname
|
||||
.as_ref()
|
||||
.unwrap_or(&self.principal.id),
|
||||
)
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal.id)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_read(
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.principal.id),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
use rustical_dav::{extensions::CommonPropertiesProp, xml::HrefElement};
|
||||
use rustical_store::auth::user::PrincipalType;
|
||||
use rustical_dav::{
|
||||
extensions::CommonPropertiesProp,
|
||||
xml::{GroupMemberSet, GroupMembership, HrefElement, SupportedReportSet},
|
||||
};
|
||||
use rustical_store::auth::PrincipalType;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
use strum_macros::VariantArray;
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropName")]
|
||||
pub enum PrincipalProp {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(String),
|
||||
|
||||
// Scheduling Extensions to CalDAV (RFC 6638)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
||||
CalendarUserType(PrincipalType),
|
||||
@@ -17,12 +18,25 @@ pub enum PrincipalProp {
|
||||
// WebDAV Access Control (RFC 3744)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", rename = b"principal-URL")]
|
||||
PrincipalUrl(HrefElement),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMembership(GroupMembership),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMemberSet(GroupMemberSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", rename = b"alternate-URI-set")]
|
||||
AlternateUriSet,
|
||||
// #[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
// PrincipalCollectionSet(HrefElement),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
||||
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||
|
||||
// CalDAV (RFC 4791)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
CalendarHomeSet(CalendarHomeSet),
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct CalendarHomeSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
||||
pub enum PrincipalPropWrapper {
|
||||
@@ -30,5 +44,9 @@ pub enum PrincipalPropWrapper {
|
||||
Common(CommonPropertiesProp),
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct CalendarHomeSet(#[xml(ty = "untagged", flatten)] pub(super) Vec<HrefElement>);
|
||||
#[derive(XmlSerialize, PartialEq, Clone, VariantArray)]
|
||||
pub enum ReportMethod {
|
||||
// We don't actually support principal-match
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
PrincipalMatch,
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use crate::calendar_set::{CalendarSetResource, CalendarSetResourceService};
|
||||
use crate::calendar::CalendarResourceService;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use crate::principal::PrincipalResource;
|
||||
use crate::{CalDavPrincipalUri, Error};
|
||||
use async_trait::async_trait;
|
||||
use axum::Router;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::{AuthenticationProvider, User};
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -13,36 +14,36 @@ pub struct PrincipalResourceService<
|
||||
AP: AuthenticationProvider,
|
||||
S: SubscriptionStore,
|
||||
CS: CalendarStore,
|
||||
BS: CalendarStore,
|
||||
> {
|
||||
pub(crate) auth_provider: Arc<AP>,
|
||||
pub(crate) sub_store: Arc<S>,
|
||||
pub(crate) cal_store: Arc<CS>,
|
||||
pub(crate) birthday_store: Arc<BS>,
|
||||
// If true only return the principal as the calendar home set, otherwise also groups
|
||||
pub(crate) simplified_home_set: bool,
|
||||
}
|
||||
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: CalendarStore> Clone
|
||||
for PrincipalResourceService<AP, S, CS, BS>
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> Clone
|
||||
for PrincipalResourceService<AP, S, CS>
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
auth_provider: self.auth_provider.clone(),
|
||||
sub_store: self.sub_store.clone(),
|
||||
cal_store: self.cal_store.clone(),
|
||||
birthday_store: self.birthday_store.clone(),
|
||||
simplified_home_set: self.simplified_home_set,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: CalendarStore>
|
||||
ResourceService for PrincipalResourceService<AP, S, CS, BS>
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> ResourceService
|
||||
for PrincipalResourceService<AP, S, CS>
|
||||
{
|
||||
type PathComponents = (String,);
|
||||
type MemberType = CalendarSetResource;
|
||||
type MemberType = CalendarResource;
|
||||
type Resource = PrincipalResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||
@@ -50,6 +51,7 @@ impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: Ca
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
_show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let user = self
|
||||
.auth_provider
|
||||
@@ -57,8 +59,9 @@ impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: Ca
|
||||
.await?
|
||||
.ok_or(crate::Error::NotFound)?;
|
||||
Ok(PrincipalResource {
|
||||
members: self.auth_provider.list_members(&user.id).await?,
|
||||
principal: user,
|
||||
home_set: &["calendar", "birthdays"],
|
||||
simplified_home_set: self.simplified_home_set,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -66,45 +69,29 @@ impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: Ca
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||
Ok(vec![
|
||||
CalendarSetResource {
|
||||
name: "calendar",
|
||||
principal: principal.to_owned(),
|
||||
read_only: false,
|
||||
},
|
||||
CalendarSetResource {
|
||||
name: "birthdays",
|
||||
principal: principal.to_owned(),
|
||||
read_only: true,
|
||||
},
|
||||
])
|
||||
let calendars = self.cal_store.get_calendars(principal).await?;
|
||||
|
||||
Ok(calendars
|
||||
.into_iter()
|
||||
.map(|cal| CalendarResource {
|
||||
read_only: self.cal_store.is_read_only(&cal.id),
|
||||
cal,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn axum_router<State: Send + Sync + Clone + 'static>(self) -> axum::Router<State> {
|
||||
Router::new()
|
||||
.nest(
|
||||
"/calendar",
|
||||
CalendarSetResourceService::new(
|
||||
"calendar",
|
||||
self.cal_store.clone(),
|
||||
self.sub_store.clone(),
|
||||
)
|
||||
.axum_router(),
|
||||
)
|
||||
.nest(
|
||||
"/birthdays",
|
||||
CalendarSetResourceService::new(
|
||||
"birthdays",
|
||||
self.birthday_store.clone(),
|
||||
self.sub_store.clone(),
|
||||
)
|
||||
.axum_router(),
|
||||
"/{calendar_id}",
|
||||
CalendarResourceService::new(self.cal_store.clone(), self.sub_store.clone())
|
||||
.axum_router(),
|
||||
)
|
||||
.route_service("/", self.axum_service())
|
||||
}
|
||||
}
|
||||
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: CalendarStore>
|
||||
AxumMethods for PrincipalResourceService<AP, S, CS, BS>
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> AxumMethods
|
||||
for PrincipalResourceService<AP, S, CS>
|
||||
{
|
||||
}
|
||||
|
||||
83
crates/caldav/src/principal/tests.rs
Normal file
83
crates/caldav/src/principal/tests.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
CalDavPrincipalUri,
|
||||
principal::{PrincipalResource, PrincipalResourceService},
|
||||
};
|
||||
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_xml::XmlSerializeRoot;
|
||||
|
||||
#[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,
|
||||
) {
|
||||
let service = PrincipalResourceService {
|
||||
cal_store: Arc::new(cal_store.await),
|
||||
sub_store: Arc::new(sub_store.await),
|
||||
auth_provider: Arc::new(auth_provider.await),
|
||||
simplified_home_set: false,
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
service
|
||||
.get_resource(&("invalid-user".to_owned(),), true)
|
||||
.await,
|
||||
Err(crate::Error::NotFound)
|
||||
));
|
||||
|
||||
let _principal_resource = service
|
||||
.get_resource(&("user".to_owned(),), true)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_propfind() {
|
||||
let propfind = PrincipalResource::parse_propfind(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?><propfind xmlns="DAV:"><allprop/></propfind>"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let principal = Principal {
|
||||
id: "user".to_string(),
|
||||
displayname: None,
|
||||
principal_type: Individual,
|
||||
password: None,
|
||||
memberships: vec!["group".to_string()],
|
||||
};
|
||||
|
||||
let resource = PrincipalResource {
|
||||
principal: principal.clone(),
|
||||
members: vec![],
|
||||
simplified_home_set: false,
|
||||
};
|
||||
|
||||
let response = resource
|
||||
.propfind(
|
||||
&format!("/caldav/principal/{}", principal.id),
|
||||
&propfind.prop,
|
||||
propfind.include.as_ref(),
|
||||
&CalDavPrincipalUri("/caldav"),
|
||||
&principal,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let output = response.serialize_to_string().unwrap();
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::{
|
||||
HttpResponse,
|
||||
web::{self, Data, Path},
|
||||
};
|
||||
use rustical_dav::xml::multistatus::PropstatElement;
|
||||
use rustical_store::SubscriptionStore;
|
||||
use rustical_xml::{XmlRootTag, XmlSerialize};
|
||||
|
||||
use crate::calendar::resource::CalendarProp;
|
||||
|
||||
async fn handle_delete<S: SubscriptionStore>(
|
||||
store: Data<S>,
|
||||
path: Path<String>,
|
||||
) -> Result<HttpResponse, rustical_store::Error> {
|
||||
let id = path.into_inner();
|
||||
store.delete_subscription(&id).await?;
|
||||
Ok(HttpResponse::NoContent().body("Unregistered"))
|
||||
}
|
||||
|
||||
pub fn subscription_resource<S: SubscriptionStore>(sub_store: Arc<S>) -> actix_web::Resource {
|
||||
web::resource("/subscription/{id}")
|
||||
.app_data(Data::from(sub_store))
|
||||
.name("subscription")
|
||||
.delete(handle_delete::<S>)
|
||||
}
|
||||
|
||||
#[derive(XmlSerialize, XmlRootTag)]
|
||||
#[xml(root = b"push-message", ns = "rustical_dav::namespace::NS_DAVPUSH")]
|
||||
pub struct PushMessage {
|
||||
propstat: PropstatElement<CalendarProp>,
|
||||
}
|
||||
@@ -4,6 +4,7 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
@@ -31,3 +32,5 @@ http.workspace = true
|
||||
tower-http.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
ical.workspace = true
|
||||
strum.workspace = true
|
||||
strum_macros.workspace = true
|
||||
|
||||
@@ -7,12 +7,13 @@ use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::TypedHeader;
|
||||
use axum_extra::headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||
use http::Method;
|
||||
use http::{HeaderMap, StatusCode};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
use rustical_dav::resource::Resource;
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::AddressbookStore;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
|
||||
@@ -24,7 +25,8 @@ pub async fn get_object<AS: AddressbookStore>(
|
||||
object_id,
|
||||
}): Path<AddressObjectPathComponents>,
|
||||
State(AddressObjectResourceService { addr_store }): State<AddressObjectResourceService<AS>>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(Error::Unauthorized);
|
||||
@@ -49,7 +51,11 @@ pub async fn get_object<AS: AddressbookStore>(
|
||||
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());
|
||||
Ok(resp.body(Body::new(object.get_vcf().to_owned())).unwrap())
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(object.get_vcf().to_owned())).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(addr_store, body))]
|
||||
@@ -60,7 +66,7 @@ pub async fn put_object<AS: AddressbookStore>(
|
||||
object_id,
|
||||
}): Path<AddressObjectPathComponents>,
|
||||
State(AddressObjectResourceService { addr_store }): State<AddressObjectResourceService<AS>>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
|
||||
header_map: HeaderMap,
|
||||
body: String,
|
||||
|
||||
@@ -13,7 +13,7 @@ use rustical_dav::{
|
||||
xml::Resourcetype,
|
||||
};
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
|
||||
#[derive(Clone, From, Into)]
|
||||
pub struct AddressObjectResource {
|
||||
@@ -30,9 +30,11 @@ impl ResourceName for AddressObjectResource {
|
||||
impl Resource for AddressObjectResource {
|
||||
type Prop = AddressObjectPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
|
||||
const IS_COLLECTION: bool = false;
|
||||
fn is_collection(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[])
|
||||
@@ -41,7 +43,7 @@ impl Resource for AddressObjectResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
prop: &AddressObjectPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
@@ -64,6 +66,10 @@ impl Resource for AddressObjectResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
self.object.get_full_name()
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal)
|
||||
}
|
||||
@@ -72,7 +78,7 @@ impl Resource for AddressObjectResource {
|
||||
Some(self.object.get_etag())
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.principal),
|
||||
))
|
||||
|
||||
@@ -5,7 +5,7 @@ use axum::{extract::Request, handler::Handler, response::Response};
|
||||
use derive_more::derive::Constructor;
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::{AddressbookStore, auth::User};
|
||||
use rustical_store::{AddressbookStore, auth::Principal};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::{convert::Infallible, sync::Arc};
|
||||
use tower::Service;
|
||||
@@ -37,7 +37,7 @@ impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS>
|
||||
type Resource = AddressObjectResource;
|
||||
type MemberType = AddressObjectResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
type PrincipalUri = CardDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||
@@ -49,10 +49,11 @@ impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS>
|
||||
addressbook_id,
|
||||
object_id,
|
||||
}: &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let object = self
|
||||
.addr_store
|
||||
.get_object(principal, addressbook_id, object_id, false)
|
||||
.get_object(principal, addressbook_id, object_id, show_deleted)
|
||||
.await?;
|
||||
Ok(AddressObjectResource {
|
||||
object,
|
||||
|
||||
@@ -5,12 +5,12 @@ use axum::body::Body;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::Response;
|
||||
use axum_extra::headers::{ContentType, HeaderMapExt};
|
||||
use http::{HeaderValue, StatusCode, header};
|
||||
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::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
@@ -19,7 +19,8 @@ use tracing::instrument;
|
||||
pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(Error::Unauthorized);
|
||||
@@ -46,7 +47,7 @@ pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
|
||||
let filename = format!("{}_{}.vcf", principal, addressbook_id);
|
||||
let filename = format!("{principal}_{addressbook_id}.vcf");
|
||||
let filename = utf8_percent_encode(&filename, CONTROLS);
|
||||
hdrs.insert(
|
||||
header::CONTENT_DISPOSITION,
|
||||
@@ -55,5 +56,9 @@ pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
Ok(resp.body(Body::new(vcf)).unwrap())
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(vcf)).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::User};
|
||||
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_xml::{XmlDeserialize, XmlDocument, XmlRootTag};
|
||||
use tracing::instrument;
|
||||
|
||||
@@ -44,7 +44,7 @@ struct MkcolRequest {
|
||||
#[instrument(skip(addr_store))]
|
||||
pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
@@ -52,8 +52,10 @@ pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let request = MkcolRequest::parse_str(&body)?;
|
||||
let request = request.set.prop;
|
||||
let mut request = MkcolRequest::parse_str(&body)?.set.prop;
|
||||
if let Some("") = request.displayname.as_deref() {
|
||||
request.displayname = None
|
||||
}
|
||||
|
||||
let addressbook = Addressbook {
|
||||
id: addressbook_id.to_owned(),
|
||||
@@ -86,15 +88,8 @@ pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
}
|
||||
}
|
||||
|
||||
match addr_store.insert_addressbook(addressbook).await {
|
||||
// TODO: The spec says we should return a mkcol-response.
|
||||
// However, it works without one but breaks on iPadOS when using an empty one :)
|
||||
Ok(()) => Ok(StatusCode::CREATED.into_response()),
|
||||
Err(err) => {
|
||||
dbg!(err.to_string());
|
||||
Err(err.into())
|
||||
}
|
||||
}
|
||||
addr_store.insert_addressbook(addressbook).await?;
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
pub mod mkcol;
|
||||
// pub mod post;
|
||||
pub mod get;
|
||||
pub mod mkcol;
|
||||
pub mod post;
|
||||
pub mod put;
|
||||
pub mod report;
|
||||
|
||||
@@ -1,33 +1,40 @@
|
||||
use crate::Error;
|
||||
use crate::addressbook::resource::AddressbookResourceService;
|
||||
use actix_web::http::header;
|
||||
use actix_web::web::{Data, Path};
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use crate::addressbook::AddressbookResourceService;
|
||||
use crate::addressbook::resource::AddressbookResource;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
use rustical_dav::resource::Resource;
|
||||
use rustical_dav_push::register::PushRegister;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::{AddressbookStore, Subscription, SubscriptionStore};
|
||||
use rustical_xml::XmlDocument;
|
||||
use tracing::instrument;
|
||||
use tracing_actix_web::RootSpan;
|
||||
|
||||
#[instrument(parent = root_span.id(), skip(resource_service, root_span, req))]
|
||||
pub async fn route_post<A: AddressbookStore, S: SubscriptionStore>(
|
||||
path: Path<(String, String)>,
|
||||
#[instrument(skip(resource_service))]
|
||||
pub async fn route_post<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addr_id)): Path<(String, String)>,
|
||||
user: Principal,
|
||||
State(resource_service): State<AddressbookResourceService<AS, S>>,
|
||||
body: String,
|
||||
user: User,
|
||||
resource_service: Data<AddressbookResourceService<A, S>>,
|
||||
root_span: RootSpan,
|
||||
req: HttpRequest,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let (principal, addressbook_id) = path.into_inner();
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let addressbook = resource_service
|
||||
.addr_store
|
||||
.get_addressbook(&principal, &addressbook_id, false)
|
||||
.get_addressbook(&principal, &addr_id, false)
|
||||
.await?;
|
||||
let addressbook_resource = AddressbookResource(addressbook);
|
||||
if !addressbook_resource
|
||||
.get_user_privileges(&user)?
|
||||
.has(&UserPrivilege::Read)
|
||||
{
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let request = PushRegister::parse_str(&body)?;
|
||||
let sub_id = uuid::Uuid::new_v4().to_string();
|
||||
|
||||
@@ -44,7 +51,7 @@ pub async fn route_post<A: AddressbookStore, S: SubscriptionStore>(
|
||||
.web_push_subscription
|
||||
.push_resource
|
||||
.to_owned(),
|
||||
topic: addressbook.push_topic,
|
||||
topic: addressbook_resource.0.push_topic,
|
||||
expiration: expires.naive_local(),
|
||||
public_key: request
|
||||
.subscription
|
||||
@@ -63,13 +70,17 @@ pub async fn route_post<A: AddressbookStore, S: SubscriptionStore>(
|
||||
.upsert_subscription(subscription)
|
||||
.await?;
|
||||
|
||||
let location = req
|
||||
.resource_map()
|
||||
.url_for(&req, "subscription", &[sub_id])
|
||||
.unwrap();
|
||||
|
||||
Ok(HttpResponse::Created()
|
||||
.append_header((header::LOCATION, location.to_string()))
|
||||
.append_header((header::EXPIRES, expires.to_rfc2822()))
|
||||
.finish())
|
||||
// TODO: make nicer
|
||||
let location = format!("/push_subscription/{sub_id}");
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
HeaderMap::from_iter([
|
||||
(header::LOCATION, HeaderValue::from_str(&location).unwrap()),
|
||||
(
|
||||
header::EXPIRES,
|
||||
HeaderValue::from_str(&expires.to_rfc2822()).unwrap(),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ use http::StatusCode;
|
||||
use ical::VcardParser;
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::Addressbook;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::User};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(addr_store))]
|
||||
pub async fn route_put<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
|
||||
@@ -10,7 +10,7 @@ use rustical_dav::{
|
||||
xml::{MultistatusElement, PropfindType, multistatus::ResponseElement},
|
||||
};
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::{AddressbookStore, auth::User};
|
||||
use rustical_store::{AddressbookStore, auth::Principal};
|
||||
use rustical_xml::XmlDeserialize;
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
@@ -58,12 +58,13 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
|
||||
Ok((result, not_found))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
|
||||
addr_multiget: &AddressbookMultigetRequest,
|
||||
prop: &PropfindType<AddressObjectPropWrapperName>,
|
||||
path: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
addr_store: &AS,
|
||||
@@ -80,7 +81,7 @@ pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, prop, puri, user)?,
|
||||
.propfind(&path, prop, None, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use axum::{
|
||||
response::IntoResponse,
|
||||
};
|
||||
use rustical_dav::xml::{PropfindType, sync_collection::SyncCollectionRequest};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::User};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_xml::{XmlDeserialize, XmlDocument};
|
||||
use sync_collection::handle_sync_collection;
|
||||
use tracing::instrument;
|
||||
@@ -37,7 +37,7 @@ impl ReportRequest {
|
||||
#[instrument(skip(addr_store))]
|
||||
pub async fn route_report_addressbook<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
user: User,
|
||||
user: Principal,
|
||||
OriginalUri(uri): OriginalUri,
|
||||
Extension(puri): Extension<CardDavPrincipalUri>,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
|
||||
@@ -13,7 +13,7 @@ use rustical_dav::{
|
||||
};
|
||||
use rustical_store::{
|
||||
AddressbookStore,
|
||||
auth::User,
|
||||
auth::Principal,
|
||||
synctoken::{format_synctoken, parse_synctoken},
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
|
||||
sync_collection: &SyncCollectionRequest<AddressObjectPropWrapperName>,
|
||||
path: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
addr_store: &AS,
|
||||
@@ -39,7 +39,7 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, &sync_collection.prop, puri, user)?,
|
||||
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
use rustical_dav::extensions::{CommonPropertiesProp, SyncTokenExtensionProp};
|
||||
use rustical_dav::{
|
||||
extensions::{CommonPropertiesProp, SyncTokenExtensionProp},
|
||||
xml::SupportedReportSet,
|
||||
};
|
||||
use rustical_dav_push::DavPushExtensionProp;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
use strum_macros::VariantArray;
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "AddressbookPropName")]
|
||||
pub enum AddressbookProp {
|
||||
// WebDAV (RFC 2518)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(Option<String>),
|
||||
|
||||
// CardDAV (RFC 6352)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
AddressbookDescription(Option<String>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
|
||||
SupportedAddressData(SupportedAddressData),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
|
||||
SupportedReportSet(SupportedReportSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
||||
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
MaxResourceSize(i64),
|
||||
}
|
||||
@@ -60,37 +60,10 @@ impl Default for SupportedAddressData {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
|
||||
pub enum ReportMethod {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
AddressbookMultiget,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
SyncCollection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportWrapper {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
report: ReportMethod,
|
||||
}
|
||||
|
||||
// RFC 3253 section-3.1.5
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportSet {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
|
||||
supported_report: &'static [SupportedReportWrapper],
|
||||
}
|
||||
|
||||
impl Default for SupportedReportSet {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
supported_report: &[
|
||||
SupportedReportWrapper {
|
||||
report: ReportMethod::AddressbookMultiget,
|
||||
},
|
||||
SupportedReportWrapper {
|
||||
report: ReportMethod::SyncCollection,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::prop::{SupportedAddressData, SupportedReportSet};
|
||||
use super::prop::SupportedAddressData;
|
||||
use crate::Error;
|
||||
use crate::addressbook::prop::{
|
||||
AddressbookProp, AddressbookPropName, AddressbookPropWrapper, AddressbookPropWrapperName,
|
||||
@@ -7,10 +7,10 @@ use derive_more::derive::{From, Into};
|
||||
use rustical_dav::extensions::{CommonPropertiesExtension, SyncTokenExtension};
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{Resourcetype, ResourcetypeInner};
|
||||
use rustical_dav::xml::{Resourcetype, ResourcetypeInner, SupportedReportSet};
|
||||
use rustical_dav_push::DavPushExtension;
|
||||
use rustical_store::Addressbook;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
|
||||
#[derive(Clone, Debug, From, Into)]
|
||||
pub struct AddressbookResource(pub(crate) Addressbook);
|
||||
@@ -36,9 +36,11 @@ impl DavPushExtension for AddressbookResource {
|
||||
impl Resource for AddressbookResource {
|
||||
type Prop = AddressbookPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
|
||||
const IS_COLLECTION: bool = true;
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[
|
||||
@@ -50,20 +52,17 @@ impl Resource for AddressbookResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
prop: &AddressbookPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
AddressbookPropWrapperName::Addressbook(prop) => {
|
||||
AddressbookPropWrapper::Addressbook(match prop {
|
||||
AddressbookPropName::Displayname => {
|
||||
AddressbookProp::Displayname(self.0.displayname.clone())
|
||||
}
|
||||
AddressbookPropName::MaxResourceSize => {
|
||||
AddressbookProp::MaxResourceSize(10000000)
|
||||
}
|
||||
AddressbookPropName::SupportedReportSet => {
|
||||
AddressbookProp::SupportedReportSet(SupportedReportSet::default())
|
||||
AddressbookProp::SupportedReportSet(SupportedReportSet::all())
|
||||
}
|
||||
AddressbookPropName::AddressbookDescription => {
|
||||
AddressbookProp::AddressbookDescription(self.0.description.to_owned())
|
||||
@@ -89,10 +88,6 @@ impl Resource for AddressbookResource {
|
||||
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
|
||||
match prop {
|
||||
AddressbookPropWrapper::Addressbook(prop) => match prop {
|
||||
AddressbookProp::Displayname(displayname) => {
|
||||
self.0.displayname = displayname;
|
||||
Ok(())
|
||||
}
|
||||
AddressbookProp::AddressbookDescription(description) => {
|
||||
self.0.description = description;
|
||||
Ok(())
|
||||
@@ -113,10 +108,6 @@ impl Resource for AddressbookResource {
|
||||
) -> Result<(), rustical_dav::Error> {
|
||||
match prop {
|
||||
AddressbookPropWrapperName::Addressbook(prop) => match prop {
|
||||
AddressbookPropName::Displayname => {
|
||||
self.0.displayname = None;
|
||||
Ok(())
|
||||
}
|
||||
AddressbookPropName::AddressbookDescription => {
|
||||
self.0.description = None;
|
||||
Ok(())
|
||||
@@ -135,11 +126,19 @@ impl Resource for AddressbookResource {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
self.0.displayname.as_deref()
|
||||
}
|
||||
fn set_displayname(&mut self, name: Option<String>) -> Result<(), rustical_dav::Error> {
|
||||
self.0.displayname = name;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.0.principal)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.0.principal),
|
||||
))
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::methods::report::route_report_addressbook;
|
||||
use crate::address_object::AddressObjectResourceService;
|
||||
use crate::address_object::resource::AddressObjectResource;
|
||||
use crate::addressbook::methods::get::route_get;
|
||||
use crate::addressbook::methods::post::route_post;
|
||||
use crate::addressbook::methods::put::route_put;
|
||||
use crate::addressbook::resource::AddressbookResource;
|
||||
use crate::{CardDavPrincipalUri, Error};
|
||||
@@ -13,7 +14,7 @@ use axum::handler::Handler;
|
||||
use axum::response::Response;
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||
use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
@@ -50,18 +51,19 @@ impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
|
||||
type PathComponents = (String, String); // principal, addressbook_id
|
||||
type Resource = AddressbookResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
type PrincipalUri = CardDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook, webdav-push";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal, addressbook_id): &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Error> {
|
||||
let addressbook = self
|
||||
.addr_store
|
||||
.get_addressbook(principal, addressbook_id, false)
|
||||
.get_addressbook(principal, addressbook_id, show_deleted)
|
||||
.await
|
||||
.map_err(|_e| Error::NotFound)?;
|
||||
Ok(addressbook.into())
|
||||
@@ -130,6 +132,13 @@ impl<AS: AddressbookStore, S: SubscriptionStore> AxumMethods for AddressbookReso
|
||||
})
|
||||
}
|
||||
|
||||
fn post() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||
Some(|state, req| {
|
||||
let mut service = Handler::with_state(route_post::<AS, S>, state);
|
||||
Box::pin(Service::call(&mut service, req))
|
||||
})
|
||||
}
|
||||
|
||||
fn put() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||
Some(|state, req| {
|
||||
let mut service = Handler::with_state(route_put::<AS, S>, state);
|
||||
|
||||
@@ -9,7 +9,7 @@ use rustical_dav::resources::RootResourceService;
|
||||
use rustical_store::auth::middleware::AuthenticationLayer;
|
||||
use rustical_store::{
|
||||
AddressbookStore, SubscriptionStore,
|
||||
auth::{AuthenticationProvider, User},
|
||||
auth::{AuthenticationProvider, Principal},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -22,8 +22,11 @@ pub mod principal;
|
||||
pub struct CardDavPrincipalUri(&'static str);
|
||||
|
||||
impl PrincipalUri for CardDavPrincipalUri {
|
||||
fn principal_collection(&self) -> String {
|
||||
format!("{}/principal/", self.0)
|
||||
}
|
||||
fn principal_uri(&self, principal: &str) -> String {
|
||||
format!("{}/principal/{}/", self.0, principal)
|
||||
format!("{}{}/", self.principal_collection(), principal)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,10 +44,12 @@ pub fn carddav_router<AP: AuthenticationProvider, A: AddressbookStore, S: Subscr
|
||||
Router::new()
|
||||
.nest(
|
||||
prefix,
|
||||
RootResourceService::<_, User, CardDavPrincipalUri>::new(principal_service.clone())
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CardDavPrincipalUri(prefix))),
|
||||
RootResourceService::<_, Principal, CardDavPrincipalUri>::new(
|
||||
principal_service.clone(),
|
||||
)
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CardDavPrincipalUri(prefix))),
|
||||
)
|
||||
.route(
|
||||
"/.well-known/carddav",
|
||||
|
||||
@@ -2,8 +2,10 @@ use crate::Error;
|
||||
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
||||
use rustical_store::auth::User;
|
||||
use rustical_dav::xml::{
|
||||
GroupMemberSet, GroupMembership, HrefElement, Resourcetype, ResourcetypeInner,
|
||||
};
|
||||
use rustical_store::auth::Principal;
|
||||
|
||||
mod service;
|
||||
pub use service::*;
|
||||
@@ -12,7 +14,8 @@ pub use prop::*;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PrincipalResource {
|
||||
principal: User,
|
||||
principal: Principal,
|
||||
members: Vec<String>,
|
||||
}
|
||||
|
||||
impl ResourceName for PrincipalResource {
|
||||
@@ -24,9 +27,11 @@ impl ResourceName for PrincipalResource {
|
||||
impl Resource for PrincipalResource {
|
||||
type Prop = PrincipalPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
|
||||
const IS_COLLECTION: bool = true;
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[
|
||||
@@ -38,33 +43,46 @@ impl Resource for PrincipalResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
user: &Principal,
|
||||
prop: &PrincipalPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
let principal_href = HrefElement::new(puri.principal_uri(&user.id));
|
||||
|
||||
let home_set = AddressbookHomeSet(
|
||||
user.memberships()
|
||||
.into_iter()
|
||||
.map(|principal| puri.principal_uri(principal))
|
||||
.map(HrefElement::new)
|
||||
.collect(),
|
||||
);
|
||||
let principal_href = HrefElement::new(puri.principal_uri(&self.principal.id));
|
||||
|
||||
Ok(match prop {
|
||||
PrincipalPropWrapperName::Principal(prop) => {
|
||||
PrincipalPropWrapper::Principal(match prop {
|
||||
PrincipalPropName::Displayname => PrincipalProp::Displayname(
|
||||
self.principal
|
||||
.displayname
|
||||
.to_owned()
|
||||
.unwrap_or(self.principal.id.to_owned()),
|
||||
),
|
||||
PrincipalPropName::PrincipalUrl => PrincipalProp::PrincipalUrl(principal_href),
|
||||
PrincipalPropName::AddressbookHomeSet => {
|
||||
PrincipalProp::AddressbookHomeSet(home_set)
|
||||
PrincipalProp::AddressbookHomeSet(AddressbookHomeSet(
|
||||
self.principal
|
||||
.memberships()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::PrincipalAddress => PrincipalProp::PrincipalAddress(None),
|
||||
PrincipalPropName::GroupMembership => {
|
||||
PrincipalProp::GroupMembership(GroupMembership(
|
||||
self.principal
|
||||
.memberships_without_self()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::GroupMemberSet => {
|
||||
PrincipalProp::GroupMemberSet(GroupMemberSet(
|
||||
self.members
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::AlternateUriSet => PrincipalProp::AlternateUriSet,
|
||||
PrincipalPropName::PrincipalCollectionSet => {
|
||||
PrincipalProp::PrincipalCollectionSet(puri.principal_collection().into())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -74,11 +92,20 @@ impl Resource for PrincipalResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
Some(
|
||||
self.principal
|
||||
.displayname
|
||||
.as_ref()
|
||||
.unwrap_or(&self.principal.id),
|
||||
)
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal.id)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.principal.id),
|
||||
))
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
use rustical_dav::{extensions::CommonPropertiesProp, xml::HrefElement};
|
||||
use rustical_dav::{
|
||||
extensions::CommonPropertiesProp,
|
||||
xml::{GroupMemberSet, GroupMembership, HrefElement},
|
||||
};
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct AddressbookHomeSet(#[xml(ty = "untagged", flatten)] pub(super) Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropName")]
|
||||
pub enum PrincipalProp {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(String),
|
||||
|
||||
// WebDAV Access Control (RFC 3744)
|
||||
#[xml(rename = b"principal-URL")]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
PrincipalUrl(HrefElement),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMembership(GroupMembership),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMemberSet(GroupMemberSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", rename = b"alternate-URI-set")]
|
||||
AlternateUriSet,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
PrincipalCollectionSet(HrefElement),
|
||||
|
||||
// CardDAV (RFC 6352)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
@@ -22,6 +27,9 @@ pub enum PrincipalProp {
|
||||
PrincipalAddress(Option<HrefElement>),
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct AddressbookHomeSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
||||
pub enum PrincipalPropWrapper {
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{CardDavPrincipalUri, Error};
|
||||
use async_trait::async_trait;
|
||||
use axum::Router;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::{AuthenticationProvider, User};
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -51,7 +51,7 @@ impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> Reso
|
||||
type MemberType = AddressbookResource;
|
||||
type Resource = PrincipalResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type Principal = Principal;
|
||||
type PrincipalUri = CardDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||
@@ -59,13 +59,17 @@ impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> Reso
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
_show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let user = self
|
||||
.auth_provider
|
||||
.get_principal(principal)
|
||||
.await?
|
||||
.ok_or(crate::Error::NotFound)?;
|
||||
Ok(PrincipalResource { principal: user })
|
||||
Ok(PrincipalResource {
|
||||
members: self.auth_provider.list_members(&user.id).await?,
|
||||
principal: user,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_members(
|
||||
|
||||
@@ -4,6 +4,7 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
@@ -24,3 +25,6 @@ tracing.workspace = true
|
||||
tokio.workspace = true
|
||||
http.workspace = true
|
||||
headers.workspace = true
|
||||
strum.workspace = true
|
||||
matchit.workspace = true
|
||||
matchit-serde.workspace = true
|
||||
|
||||
@@ -28,6 +28,9 @@ pub enum Error {
|
||||
|
||||
#[error("Precondition Failed")]
|
||||
PreconditionFailed,
|
||||
|
||||
#[error("Forbidden")]
|
||||
Forbidden,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
@@ -49,6 +52,7 @@ impl Error {
|
||||
Error::PropReadOnly => StatusCode::CONFLICT,
|
||||
Error::PreconditionFailed => StatusCode::PRECONDITION_FAILED,
|
||||
Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::Forbidden => StatusCode::FORBIDDEN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ pub enum CommonPropertiesProp {
|
||||
#[xml(skip_deserializing)]
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
Resourcetype(Resourcetype),
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
Displayname(Option<String>),
|
||||
|
||||
// WebDAV Current Principal Extension (RFC 5397)
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
@@ -37,6 +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::CurrentUserPrincipal => {
|
||||
CommonPropertiesProp::CurrentUserPrincipal(
|
||||
principal_uri.principal_uri(principal.get_id()).into(),
|
||||
@@ -52,12 +57,18 @@ pub trait CommonPropertiesExtension: Resource {
|
||||
})
|
||||
}
|
||||
|
||||
fn set_prop(&self, _prop: CommonPropertiesProp) -> Result<(), crate::Error> {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
fn set_prop(&mut self, prop: CommonPropertiesProp) -> Result<(), crate::Error> {
|
||||
match prop {
|
||||
CommonPropertiesProp::Displayname(name) => self.set_displayname(name),
|
||||
_ => Err(crate::Error::PropReadOnly),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_prop(&self, _prop: &CommonPropertiesPropName) -> Result<(), crate::Error> {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
fn remove_prop(&mut self, prop: &CommonPropertiesPropName) -> Result<(), crate::Error> {
|
||||
match prop {
|
||||
CommonPropertiesPropName::Displayname => self.set_displayname(None),
|
||||
_ => Err(crate::Error::PropReadOnly),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use itertools::Itertools;
|
||||
use quick_xml::name::Namespace;
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, Eq, Hash, PartialEq)]
|
||||
// https://datatracker.ietf.org/doc/html/rfc3744
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||
pub enum UserPrivilege {
|
||||
Read,
|
||||
Write,
|
||||
@@ -15,12 +17,12 @@ pub enum UserPrivilege {
|
||||
}
|
||||
|
||||
impl XmlSerialize for UserPrivilegeSet {
|
||||
fn serialize<W: std::io::Write>(
|
||||
fn serialize(
|
||||
&self,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
) -> std::io::Result<()> {
|
||||
#[derive(XmlSerialize)]
|
||||
pub struct FakeUserPrivilegeSet {
|
||||
@@ -29,12 +31,11 @@ impl XmlSerialize for UserPrivilegeSet {
|
||||
}
|
||||
|
||||
FakeUserPrivilegeSet {
|
||||
privileges: self.privileges.iter().cloned().collect(),
|
||||
privileges: self.privileges.iter().cloned().sorted().collect(),
|
||||
}
|
||||
.serialize(ns, tag, namespaces, writer)
|
||||
}
|
||||
|
||||
#[allow(refining_impl_trait)]
|
||||
fn attributes<'a>(&self) -> Option<Vec<quick_xml::events::attributes::Attribute<'a>>> {
|
||||
None
|
||||
}
|
||||
@@ -47,6 +48,12 @@ pub struct UserPrivilegeSet {
|
||||
|
||||
impl UserPrivilegeSet {
|
||||
pub fn has(&self, privilege: &UserPrivilege) -> bool {
|
||||
if (privilege == &UserPrivilege::WriteProperties
|
||||
|| privilege == &UserPrivilege::WriteContent)
|
||||
&& self.privileges.contains(&UserPrivilege::Write)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
self.privileges.contains(privilege) || self.privileges.contains(&UserPrivilege::All)
|
||||
}
|
||||
|
||||
@@ -72,6 +79,15 @@ impl UserPrivilegeSet {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn owner_write_properties(is_owner: bool) -> Self {
|
||||
// Content is read-only but we can write properties
|
||||
if is_owner {
|
||||
Self::write_properties()
|
||||
} else {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_only() -> Self {
|
||||
Self {
|
||||
privileges: HashSet::from([
|
||||
@@ -81,6 +97,17 @@ impl UserPrivilegeSet {
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_properties() -> Self {
|
||||
Self {
|
||||
privileges: HashSet::from([
|
||||
UserPrivilege::Read,
|
||||
UserPrivilege::WriteProperties,
|
||||
UserPrivilege::ReadAcl,
|
||||
UserPrivilege::ReadCurrentUserPrivilegeSet,
|
||||
]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> From<[UserPrivilege; N]> for UserPrivilegeSet {
|
||||
|
||||
@@ -18,11 +18,6 @@ pub trait AxumMethods: Sized + Send + Sync + 'static {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn head() -> Option<MethodFunction<Self>> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn post() -> Option<MethodFunction<Self>> {
|
||||
None
|
||||
@@ -58,8 +53,6 @@ pub trait AxumMethods: Sized + Send + Sync + 'static {
|
||||
}
|
||||
if Self::get().is_some() {
|
||||
allow.push(Method::GET);
|
||||
}
|
||||
if Self::head().is_some() {
|
||||
allow.push(Method::HEAD);
|
||||
}
|
||||
if Self::post().is_some() {
|
||||
|
||||
@@ -72,16 +72,11 @@ where
|
||||
return svc(self.resource_service.clone(), req);
|
||||
}
|
||||
}
|
||||
"GET" => {
|
||||
"GET" | "HEAD" => {
|
||||
if let Some(svc) = RS::get() {
|
||||
return svc(self.resource_service.clone(), req);
|
||||
}
|
||||
}
|
||||
"HEAD" => {
|
||||
if let Some(svc) = RS::head() {
|
||||
return svc(self.resource_service.clone(), req);
|
||||
}
|
||||
}
|
||||
"POST" => {
|
||||
if let Some(svc) = RS::post() {
|
||||
return svc(self.resource_service.clone(), req);
|
||||
@@ -114,6 +109,9 @@ where
|
||||
}
|
||||
|
||||
async fn route_options<RS: ResourceService + AxumMethods>() -> Response<Body> {
|
||||
// Semantically NO_CONTENT would also make sense,
|
||||
// but GNOME Accounts only works when returning OK
|
||||
// https://gitlab.gnome.org/GNOME/gnome-online-accounts/-/blob/master/src/goabackend/goadavclient.c#L289
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let headers = resp.headers_mut().unwrap();
|
||||
headers.insert("DAV", HeaderValue::from_static(RS::DAV_HEADER));
|
||||
|
||||
@@ -1,25 +1,54 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::{
|
||||
header::{Depth, Overwrite},
|
||||
resource::ResourceService,
|
||||
};
|
||||
use axum::{
|
||||
extract::{MatchedPath, Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::{HeaderMap, StatusCode, Uri};
|
||||
use matchit_serde::ParamsDeserializer;
|
||||
use serde::Deserialize;
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(_path, _resource_service,))]
|
||||
#[instrument(skip(path, resource_service,))]
|
||||
pub(crate) async fn axum_route_copy<R: ResourceService>(
|
||||
Path(_path): Path<R::PathComponents>,
|
||||
State(_resource_service): State<R>,
|
||||
Path(path): Path<R::PathComponents>,
|
||||
State(resource_service): State<R>,
|
||||
depth: Option<Depth>,
|
||||
principal: R::Principal,
|
||||
overwrite: Overwrite,
|
||||
matched_path: MatchedPath,
|
||||
header_map: HeaderMap,
|
||||
) -> Result<Response, R::Error> {
|
||||
// TODO: Actually implement, but to be WebDAV-compliant we must at least support this route but
|
||||
// can return a 403 error
|
||||
let _depth = depth.unwrap_or(Depth::Infinity);
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
let destination = header_map
|
||||
.get("Destination")
|
||||
.ok_or(crate::Error::Forbidden)?
|
||||
.to_str()
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
let destination_uri: Uri = destination.parse().map_err(|_| crate::Error::Forbidden)?;
|
||||
// TODO: Check that host also matches
|
||||
let destination = destination_uri.path();
|
||||
|
||||
let mut router = matchit::Router::new();
|
||||
router.insert(matched_path.as_str(), ()).unwrap();
|
||||
if let Ok(matchit::Match { params, .. }) = router.at(destination) {
|
||||
let params =
|
||||
matchit_serde::Params::try_from(¶ms).map_err(|_| crate::Error::Forbidden)?;
|
||||
let dest_path = R::PathComponents::deserialize(&ParamsDeserializer::new(params))
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
|
||||
if resource_service
|
||||
.copy_resource(&path, &dest_path, &principal, overwrite.is_true())
|
||||
.await?
|
||||
{
|
||||
// Overwritten
|
||||
Ok(StatusCode::NO_CONTENT.into_response())
|
||||
} else {
|
||||
// Not overwritten
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
}
|
||||
} else {
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,10 +45,11 @@ pub async fn route_delete<R: ResourceService>(
|
||||
if_match: Option<IfMatch>,
|
||||
if_none_match: Option<IfNoneMatch>,
|
||||
) -> Result<(), R::Error> {
|
||||
let resource = resource_service.get_resource(path_components).await?;
|
||||
let resource = resource_service.get_resource(path_components, true).await?;
|
||||
|
||||
// Kind of a bodge since we don't get unbind from the parent
|
||||
let privileges = resource.get_user_privileges(principal)?;
|
||||
if !privileges.has(&UserPrivilege::Write) {
|
||||
if !privileges.has(&UserPrivilege::WriteProperties) {
|
||||
return Err(Error::Unauthorized.into());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,54 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::{
|
||||
header::{Depth, Overwrite},
|
||||
resource::ResourceService,
|
||||
};
|
||||
use axum::{
|
||||
extract::{MatchedPath, Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::{HeaderMap, StatusCode, Uri};
|
||||
use matchit_serde::ParamsDeserializer;
|
||||
use serde::Deserialize;
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(_path, _resource_service,))]
|
||||
#[instrument(skip(path, resource_service,))]
|
||||
pub(crate) async fn axum_route_move<R: ResourceService>(
|
||||
Path(_path): Path<R::PathComponents>,
|
||||
State(_resource_service): State<R>,
|
||||
Path(path): Path<R::PathComponents>,
|
||||
State(resource_service): State<R>,
|
||||
depth: Option<Depth>,
|
||||
principal: R::Principal,
|
||||
overwrite: Overwrite,
|
||||
matched_path: MatchedPath,
|
||||
header_map: HeaderMap,
|
||||
) -> Result<Response, R::Error> {
|
||||
// TODO: Actually implement, but to be WebDAV-compliant we must at least support this route but
|
||||
// can return a 403 error
|
||||
let _depth = depth.unwrap_or(Depth::Infinity);
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
let destination = header_map
|
||||
.get("Destination")
|
||||
.ok_or(crate::Error::Forbidden)?
|
||||
.to_str()
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
let destination_uri: Uri = destination.parse().map_err(|_| crate::Error::Forbidden)?;
|
||||
// TODO: Check that host also matches
|
||||
let destination = destination_uri.path();
|
||||
|
||||
let mut router = matchit::Router::new();
|
||||
router.insert(matched_path.as_str(), ()).unwrap();
|
||||
if let Ok(matchit::Match { params, .. }) = router.at(destination) {
|
||||
let params =
|
||||
matchit_serde::Params::try_from(¶ms).map_err(|_| crate::Error::Forbidden)?;
|
||||
let dest_path = R::PathComponents::deserialize(&ParamsDeserializer::new(params))
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
|
||||
if resource_service
|
||||
.copy_resource(&path, &dest_path, &principal, overwrite.is_true())
|
||||
.await?
|
||||
{
|
||||
// Overwritten
|
||||
Ok(StatusCode::NO_CONTENT.into_response())
|
||||
} else {
|
||||
// Not overwritten
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
}
|
||||
} else {
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,7 @@ use crate::resource::Resource;
|
||||
use crate::resource::ResourceName;
|
||||
use crate::resource::ResourceService;
|
||||
use crate::xml::MultistatusElement;
|
||||
use crate::xml::PropfindElement;
|
||||
use crate::xml::PropfindType;
|
||||
use axum::extract::{Extension, OriginalUri, Path, State};
|
||||
use rustical_xml::PropName;
|
||||
use rustical_xml::XmlDocument;
|
||||
use tracing::instrument;
|
||||
|
||||
type RSMultistatus<R> = MultistatusElement<
|
||||
@@ -49,43 +45,39 @@ pub(crate) async fn route_propfind<R: ResourceService>(
|
||||
resource_service: &R,
|
||||
puri: &impl PrincipalUri,
|
||||
) -> Result<RSMultistatus<R>, R::Error> {
|
||||
let resource = resource_service.get_resource(path_components).await?;
|
||||
let resource = resource_service
|
||||
.get_resource(path_components, false)
|
||||
.await?;
|
||||
let privileges = resource.get_user_privileges(principal)?;
|
||||
if !privileges.has(&UserPrivilege::Read) {
|
||||
return Err(Error::Unauthorized.into());
|
||||
}
|
||||
|
||||
// A request body is optional. If empty we MUST return all props
|
||||
let propfind_self: PropfindElement<<<R::Resource as Resource>::Prop as PropName>::Names> =
|
||||
if !body.is_empty() {
|
||||
PropfindElement::parse_str(body).map_err(Error::XmlError)?
|
||||
} else {
|
||||
PropfindElement {
|
||||
prop: PropfindType::Allprop,
|
||||
}
|
||||
};
|
||||
let propfind_member: PropfindElement<<<R::MemberType as Resource>::Prop as PropName>::Names> =
|
||||
if !body.is_empty() {
|
||||
PropfindElement::parse_str(body).map_err(Error::XmlError)?
|
||||
} else {
|
||||
PropfindElement {
|
||||
prop: PropfindType::Allprop,
|
||||
}
|
||||
};
|
||||
let propfind_self = R::Resource::parse_propfind(body).map_err(Error::XmlError)?;
|
||||
let propfind_member = R::MemberType::parse_propfind(body).map_err(Error::XmlError)?;
|
||||
|
||||
let mut member_responses = Vec::new();
|
||||
if depth != &Depth::Zero {
|
||||
// TODO: authorization check for member resources
|
||||
for member in resource_service.get_members(path_components).await? {
|
||||
member_responses.push(member.propfind(
|
||||
&format!("{}/{}", path.trim_end_matches('/'), member.get_name()),
|
||||
&propfind_member.prop,
|
||||
propfind_member.include.as_ref(),
|
||||
puri,
|
||||
principal,
|
||||
)?);
|
||||
}
|
||||
}
|
||||
|
||||
let response = resource.propfind(path, &propfind_self.prop, puri, principal)?;
|
||||
let response = resource.propfind(
|
||||
path,
|
||||
&propfind_self.prop,
|
||||
propfind_self.include.as_ref(),
|
||||
puri,
|
||||
principal,
|
||||
)?;
|
||||
|
||||
Ok(MultistatusElement {
|
||||
responses: vec![response],
|
||||
|
||||
@@ -26,21 +26,21 @@ enum SetPropertyPropWrapper<T: XmlDeserialize> {
|
||||
// We are <prop>
|
||||
#[derive(XmlDeserialize, Clone, Debug)]
|
||||
struct SetPropertyPropWrapperWrapper<T: XmlDeserialize>(
|
||||
#[xml(ty = "untagged")] SetPropertyPropWrapper<T>,
|
||||
#[xml(ty = "untagged", flatten)] Vec<SetPropertyPropWrapper<T>>,
|
||||
);
|
||||
|
||||
// We are <set>
|
||||
#[derive(XmlDeserialize, Clone, Debug)]
|
||||
struct SetPropertyElement<T: XmlDeserialize> {
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
prop: T,
|
||||
prop: SetPropertyPropWrapperWrapper<T>,
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug)]
|
||||
struct TagName(#[xml(ty = "tag_name")] String);
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug)]
|
||||
struct PropertyElement(#[xml(ty = "untagged")] TagName);
|
||||
struct PropertyElement(#[xml(ty = "untagged", flatten)] Vec<TagName>);
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug)]
|
||||
struct RemovePropertyElement {
|
||||
@@ -81,11 +81,12 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
|
||||
let href = path.to_owned();
|
||||
|
||||
// Extract operations
|
||||
let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>>(
|
||||
operations,
|
||||
) = XmlDocument::parse_str(body).map_err(Error::XmlError)?;
|
||||
let PropertyupdateElement::<<R::Resource as Resource>::Prop>(operations) =
|
||||
XmlDocument::parse_str(body).map_err(Error::XmlError)?;
|
||||
|
||||
let mut resource = resource_service.get_resource(path_components).await?;
|
||||
let mut resource = resource_service
|
||||
.get_resource(path_components, false)
|
||||
.await?;
|
||||
let privileges = resource.get_user_privileges(principal)?;
|
||||
if !privileges.has(&UserPrivilege::Write) {
|
||||
return Err(Error::Unauthorized.into());
|
||||
@@ -98,59 +99,63 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
|
||||
for operation in operations.into_iter() {
|
||||
match operation {
|
||||
Operation::Set(SetPropertyElement {
|
||||
prop: SetPropertyPropWrapperWrapper(property),
|
||||
prop: SetPropertyPropWrapperWrapper(properties),
|
||||
}) => {
|
||||
match property {
|
||||
SetPropertyPropWrapper::Valid(prop) => {
|
||||
let propname: <<R::Resource as Resource>::Prop as PropName>::Names =
|
||||
prop.clone().into();
|
||||
let (ns, propname): (Option<Namespace>, &str) = propname.into();
|
||||
match resource.set_prop(prop) {
|
||||
Ok(()) => {
|
||||
props_ok.push((ns.map(NamespaceOwned::from), propname.to_owned()))
|
||||
}
|
||||
Err(Error::PropReadOnly) => props_conflict
|
||||
.push((ns.map(NamespaceOwned::from), propname.to_owned())),
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
}
|
||||
SetPropertyPropWrapper::Invalid(invalid) => {
|
||||
let propname = invalid.tag_name();
|
||||
for property in properties {
|
||||
match property {
|
||||
SetPropertyPropWrapper::Valid(prop) => {
|
||||
let propname: <<R::Resource as Resource>::Prop as PropName>::Names =
|
||||
prop.clone().into();
|
||||
let (ns, propname): (Option<Namespace>, &str) = propname.into();
|
||||
match resource.set_prop(prop) {
|
||||
Ok(()) => props_ok
|
||||
.push((ns.map(NamespaceOwned::from), propname.to_owned())),
|
||||
Err(Error::PropReadOnly) => props_conflict
|
||||
.push((ns.map(NamespaceOwned::from), propname.to_owned())),
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
}
|
||||
SetPropertyPropWrapper::Invalid(invalid) => {
|
||||
let propname = invalid.tag_name();
|
||||
|
||||
if let Some(full_propname) = <R::Resource as Resource>::list_props()
|
||||
.into_iter()
|
||||
.find_map(|(ns, tag)| {
|
||||
if tag == propname.as_str() {
|
||||
Some((ns.map(NamespaceOwned::from), tag.to_owned()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
{
|
||||
// This happens in following cases:
|
||||
// - read-only properties with #[serde(skip_deserializing)]
|
||||
// - internal properties
|
||||
props_conflict.push(full_propname)
|
||||
} else {
|
||||
props_not_found.push((None, propname));
|
||||
if let Some(full_propname) = <R::Resource as Resource>::list_props()
|
||||
.into_iter()
|
||||
.find_map(|(ns, tag)| {
|
||||
if tag == propname.as_str() {
|
||||
Some((ns.map(NamespaceOwned::from), tag.to_owned()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
{
|
||||
// This happens in following cases:
|
||||
// - read-only properties with #[serde(skip_deserializing)]
|
||||
// - internal properties
|
||||
props_conflict.push(full_propname)
|
||||
} else {
|
||||
props_not_found.push((None, propname));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Operation::Remove(remove_el) => {
|
||||
let propname = remove_el.prop.0.0;
|
||||
match <<R::Resource as Resource>::Prop as PropName>::Names::from_str(&propname) {
|
||||
Ok(prop) => match resource.remove_prop(&prop) {
|
||||
Ok(()) => props_ok.push((None, propname)),
|
||||
Err(Error::PropReadOnly) => props_conflict.push({
|
||||
let (ns, tag) = prop.into();
|
||||
(ns.map(NamespaceOwned::from), tag.to_owned())
|
||||
}),
|
||||
Err(err) => return Err(err.into()),
|
||||
},
|
||||
// I guess removing a nonexisting property should be successful :)
|
||||
Err(_) => props_ok.push((None, propname)),
|
||||
};
|
||||
for tagname in remove_el.prop.0 {
|
||||
let propname = tagname.0;
|
||||
match <<R::Resource as Resource>::Prop as PropName>::Names::from_str(&propname)
|
||||
{
|
||||
Ok(prop) => match resource.remove_prop(&prop) {
|
||||
Ok(()) => props_ok.push((None, propname)),
|
||||
Err(Error::PropReadOnly) => props_conflict.push({
|
||||
let (ns, tag) = prop.into();
|
||||
(ns.map(NamespaceOwned::from), tag.to_owned())
|
||||
}),
|
||||
Err(err) => return Err(err.into()),
|
||||
},
|
||||
// I guess removing a nonexisting property should be successful :)
|
||||
Err(_) => props_ok.push((None, propname)),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use crate::Principal;
|
||||
use crate::privileges::UserPrivilegeSet;
|
||||
use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper};
|
||||
use crate::xml::{PropElement, PropfindType, Resourcetype};
|
||||
use crate::xml::{PropElement, PropfindElement, PropfindType, Resourcetype};
|
||||
use crate::xml::{TagList, multistatus::ResponseElement};
|
||||
use headers::{ETag, IfMatch, IfNoneMatch};
|
||||
use http::StatusCode;
|
||||
use itertools::Itertools;
|
||||
use quick_xml::name::Namespace;
|
||||
pub use resource_service::ResourceService;
|
||||
use rustical_xml::{EnumVariants, NamespaceOwned, PropName, XmlDeserialize, XmlSerialize};
|
||||
use std::collections::HashSet;
|
||||
use rustical_xml::{
|
||||
EnumVariants, NamespaceOwned, PropName, XmlDeserialize, XmlDocument, XmlSerialize,
|
||||
};
|
||||
use std::str::FromStr;
|
||||
|
||||
mod axum_methods;
|
||||
@@ -18,7 +19,7 @@ mod methods;
|
||||
mod principal_uri;
|
||||
mod resource_service;
|
||||
|
||||
pub use axum_methods::AxumMethods;
|
||||
pub use axum_methods::{AxumMethods, MethodFunction};
|
||||
pub use axum_service::AxumService;
|
||||
pub use principal_uri::PrincipalUri;
|
||||
|
||||
@@ -37,7 +38,7 @@ pub trait Resource: Clone + Send + 'static {
|
||||
type Error: From<crate::Error>;
|
||||
type Principal: Principal;
|
||||
|
||||
const IS_COLLECTION: bool;
|
||||
fn is_collection(&self) -> bool;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype;
|
||||
|
||||
@@ -60,6 +61,11 @@ pub trait Resource: Clone + Send + 'static {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str>;
|
||||
fn set_displayname(&mut self, _name: Option<String>) -> Result<(), crate::Error> {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
@@ -97,49 +103,67 @@ pub trait Resource: Clone + Send + 'static {
|
||||
principal: &Self::Principal,
|
||||
) -> Result<UserPrivilegeSet, Self::Error>;
|
||||
|
||||
fn parse_propfind(
|
||||
body: &str,
|
||||
) -> Result<PropfindElement<<Self::Prop as PropName>::Names>, rustical_xml::XmlError> {
|
||||
if !body.is_empty() {
|
||||
PropfindElement::parse_str(body)
|
||||
} else {
|
||||
Ok(PropfindElement {
|
||||
prop: PropfindType::Allprop,
|
||||
include: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn propfind(
|
||||
&self,
|
||||
path: &str,
|
||||
prop: &PropfindType<<Self::Prop as PropName>::Names>,
|
||||
include: Option<&PropElement<<Self::Prop as PropName>::Names>>,
|
||||
principal_uri: &impl PrincipalUri,
|
||||
principal: &Self::Principal,
|
||||
) -> Result<ResponseElement<Self::Prop>, Self::Error> {
|
||||
// Collections have a trailing slash
|
||||
let mut path = path.to_string();
|
||||
if Self::IS_COLLECTION && !path.ends_with('/') {
|
||||
if self.is_collection() && !path.ends_with('/') {
|
||||
path.push('/');
|
||||
}
|
||||
|
||||
// TODO: Support include element
|
||||
let (props, invalid_props): (HashSet<<Self::Prop as PropName>::Names>, Vec<_>) = match prop
|
||||
{
|
||||
PropfindType::Propname => {
|
||||
let props = Self::list_props()
|
||||
.into_iter()
|
||||
.map(|(ns, tag)| (ns.map(NamespaceOwned::from), tag.to_string()))
|
||||
.collect_vec();
|
||||
let (mut props, mut invalid_props): (Vec<<Self::Prop as PropName>::Names>, Vec<_>) =
|
||||
match prop {
|
||||
PropfindType::Propname => {
|
||||
let props = Self::list_props()
|
||||
.into_iter()
|
||||
.map(|(ns, tag)| (ns.map(NamespaceOwned::from), tag.to_string()))
|
||||
.collect_vec();
|
||||
|
||||
return Ok(ResponseElement {
|
||||
href: path.to_owned(),
|
||||
propstat: vec![PropstatWrapper::TagList(PropstatElement {
|
||||
prop: TagList::from(props),
|
||||
status: StatusCode::OK,
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
PropfindType::Allprop => (
|
||||
Self::list_props()
|
||||
.iter()
|
||||
.map(|(_ns, name)| <Self::Prop as PropName>::Names::from_str(name).unwrap())
|
||||
.collect(),
|
||||
vec![],
|
||||
),
|
||||
PropfindType::Prop(PropElement(valid_tags, invalid_tags)) => (
|
||||
valid_tags.iter().cloned().collect(),
|
||||
invalid_tags.to_owned(),
|
||||
),
|
||||
};
|
||||
return Ok(ResponseElement {
|
||||
href: path.to_owned(),
|
||||
propstat: vec![PropstatWrapper::TagList(PropstatElement {
|
||||
prop: TagList::from(props),
|
||||
status: StatusCode::OK,
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
PropfindType::Allprop => (
|
||||
Self::list_props()
|
||||
.iter()
|
||||
.map(|(_ns, name)| <Self::Prop as PropName>::Names::from_str(name).unwrap())
|
||||
.collect(),
|
||||
vec![],
|
||||
),
|
||||
PropfindType::Prop(PropElement(valid_tags, invalid_tags)) => (
|
||||
valid_tags.iter().unique().cloned().collect(),
|
||||
invalid_tags.to_owned(),
|
||||
),
|
||||
};
|
||||
|
||||
if let Some(PropElement(valid_tags, invalid_tags)) = include {
|
||||
props.extend(valid_tags.clone());
|
||||
invalid_props.extend(invalid_tags.to_owned());
|
||||
}
|
||||
|
||||
let prop_responses = props
|
||||
.into_iter()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub trait PrincipalUri: 'static + Clone + Send + Sync {
|
||||
fn principal_collection(&self) -> String;
|
||||
fn principal_uri(&self, principal: &str) -> String;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,13 @@ use serde::Deserialize;
|
||||
|
||||
#[async_trait]
|
||||
pub trait ResourceService: Clone + Sized + Send + Sync + AxumMethods + 'static {
|
||||
type PathComponents: for<'de> Deserialize<'de> + Sized + Send + Sync + Clone + 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
||||
type PathComponents: std::fmt::Debug
|
||||
+ for<'de> Deserialize<'de>
|
||||
+ Sized
|
||||
+ Send
|
||||
+ Sync
|
||||
+ Clone
|
||||
+ 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
||||
type MemberType: Resource<Error = Self::Error, Principal = Self::Principal>
|
||||
+ super::ResourceName;
|
||||
type Resource: Resource<Error = Self::Error, Principal = Self::Principal>;
|
||||
@@ -28,7 +34,8 @@ pub trait ResourceService: Clone + Sized + Send + Sync + AxumMethods + 'static {
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
_path: &Self::PathComponents,
|
||||
path: &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error>;
|
||||
|
||||
async fn save_resource(
|
||||
@@ -47,6 +54,28 @@ pub trait ResourceService: Clone + Sized + Send + Sync + AxumMethods + 'static {
|
||||
Err(crate::Error::Unauthorized.into())
|
||||
}
|
||||
|
||||
// Returns whether an existing resource was overwritten
|
||||
async fn copy_resource(
|
||||
&self,
|
||||
_path: &Self::PathComponents,
|
||||
_destination: &Self::PathComponents,
|
||||
_user: &Self::Principal,
|
||||
_overwrite: bool,
|
||||
) -> Result<bool, Self::Error> {
|
||||
Err(crate::Error::Forbidden.into())
|
||||
}
|
||||
|
||||
// Returns whether an existing resource was overwritten
|
||||
async fn move_resource(
|
||||
&self,
|
||||
_path: &Self::PathComponents,
|
||||
_destination: &Self::PathComponents,
|
||||
_user: &Self::Principal,
|
||||
_overwrite: bool,
|
||||
) -> Result<bool, Self::Error> {
|
||||
Err(crate::Error::Forbidden.into())
|
||||
}
|
||||
|
||||
fn axum_service(self) -> AxumService<Self>
|
||||
where
|
||||
Self: AxumMethods,
|
||||
|
||||
@@ -24,7 +24,9 @@ impl<PR: Resource, P: Principal> Resource for RootResource<PR, P> {
|
||||
type Error = PR::Error;
|
||||
type Principal = P;
|
||||
|
||||
const IS_COLLECTION: bool = true;
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[ResourcetypeInner(
|
||||
@@ -33,6 +35,10 @@ impl<PR: Resource, P: Principal> Resource for RootResource<PR, P> {
|
||||
)])
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
Some("RustiCal DAV root")
|
||||
}
|
||||
|
||||
fn get_prop(
|
||||
&self,
|
||||
principal_uri: &impl PrincipalUri,
|
||||
@@ -80,7 +86,11 @@ where
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control";
|
||||
|
||||
async fn get_resource(&self, _: &()) -> Result<Self::Resource, Self::Error> {
|
||||
async fn get_resource(
|
||||
&self,
|
||||
_: &(),
|
||||
_show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
Ok(RootResource::<PRS::Resource, P>::default())
|
||||
}
|
||||
|
||||
|
||||
8
crates/dav/src/xml/group.rs
Normal file
8
crates/dav/src/xml/group.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use crate::xml::HrefElement;
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct GroupMembership(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct GroupMemberSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
@@ -11,3 +11,7 @@ pub use tag_list::TagList;
|
||||
mod error;
|
||||
pub mod sync_collection;
|
||||
pub use error::ErrorElement;
|
||||
mod report_set;
|
||||
pub use report_set::SupportedReportSet;
|
||||
mod group;
|
||||
pub use group::*;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::xml::TagList;
|
||||
use headers::{CacheControl, ContentType, HeaderMapExt};
|
||||
use http::StatusCode;
|
||||
use quick_xml::name::Namespace;
|
||||
use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot};
|
||||
@@ -18,12 +19,12 @@ pub struct PropstatElement<PropType: XmlSerialize> {
|
||||
pub status: StatusCode,
|
||||
}
|
||||
|
||||
fn xml_serialize_status<W: ::std::io::Write>(
|
||||
fn xml_serialize_status(
|
||||
status: &StatusCode,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
) -> std::io::Result<()> {
|
||||
XmlSerialize::serialize(&format!("HTTP/1.1 {}", status), ns, tag, namespaces, writer)
|
||||
}
|
||||
@@ -38,8 +39,15 @@ pub enum PropstatWrapper<T: XmlSerialize> {
|
||||
// RFC 2518
|
||||
// <!ELEMENT response (href, ((href*, status)|(propstat+)),
|
||||
// responsedescription?) >
|
||||
#[derive(XmlSerialize)]
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
#[derive(XmlSerialize, XmlRootTag)]
|
||||
#[xml(ns = "crate::namespace::NS_DAV", root = b"response")]
|
||||
#[xml(ns_prefix(
|
||||
crate::namespace::NS_DAV = b"",
|
||||
crate::namespace::NS_CARDDAV = b"CARD",
|
||||
crate::namespace::NS_CALDAV = b"CAL",
|
||||
crate::namespace::NS_CALENDARSERVER = b"CS",
|
||||
crate::namespace::NS_DAVPUSH = b"PUSH"
|
||||
))]
|
||||
pub struct ResponseElement<PropstatType: XmlSerialize> {
|
||||
pub href: String,
|
||||
#[xml(serialize_with = "xml_serialize_optional_status")]
|
||||
@@ -48,12 +56,12 @@ pub struct ResponseElement<PropstatType: XmlSerialize> {
|
||||
pub propstat: Vec<PropstatWrapper<PropstatType>>,
|
||||
}
|
||||
|
||||
fn xml_serialize_optional_status<W: ::std::io::Write>(
|
||||
fn xml_serialize_optional_status(
|
||||
val: &Option<StatusCode>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
) -> std::io::Result<()> {
|
||||
XmlSerialize::serialize(
|
||||
&val.map(|status| format!("HTTP/1.1 {}", status)),
|
||||
@@ -109,18 +117,16 @@ impl<T1: XmlSerialize, T2: XmlSerialize> axum::response::IntoResponse
|
||||
{
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
use axum::body::Body;
|
||||
use http::header;
|
||||
|
||||
let mut output: Vec<_> = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".into();
|
||||
let mut writer = quick_xml::Writer::new_with_indent(&mut output, b' ', 4);
|
||||
if let Err(err) = self.serialize_root(&mut writer) {
|
||||
return crate::Error::from(err).into_response();
|
||||
}
|
||||
let output = match self.serialize_to_string() {
|
||||
Ok(out) => out,
|
||||
Err(err) => return crate::Error::from(err).into_response(),
|
||||
};
|
||||
|
||||
let mut resp = axum::response::Response::builder().status(StatusCode::MULTI_STATUS);
|
||||
resp.headers_mut()
|
||||
.unwrap()
|
||||
.insert(header::CONTENT_TYPE, "application/xml".try_into().unwrap());
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ContentType::xml());
|
||||
hdrs.typed_insert(CacheControl::new().with_no_cache());
|
||||
resp.body(Body::from(output)).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,11 @@ use rustical_xml::XmlRootTag;
|
||||
pub struct PropfindElement<PN: XmlDeserialize> {
|
||||
#[xml(ty = "untagged")]
|
||||
pub prop: PropfindType<PN>,
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub include: Option<PropElement<PN>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
// pub struct PropElement<PN: XmlDeserialize = Propname>(#[xml(ty = "untagged", flatten)] pub Vec<PN>);
|
||||
pub struct PropElement<PN: XmlDeserialize>(
|
||||
// valid
|
||||
pub Vec<PN>,
|
||||
|
||||
34
crates/dav/src/xml/report_set.rs
Normal file
34
crates/dav/src/xml/report_set.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use rustical_xml::XmlSerialize;
|
||||
use strum::VariantArray;
|
||||
|
||||
// RFC 3253 section-3.1.5
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportSet<T: XmlSerialize + 'static> {
|
||||
#[xml(flatten)]
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
supported_report: Vec<ReportWrapper<T>>,
|
||||
}
|
||||
|
||||
impl<T: XmlSerialize + Clone + 'static> SupportedReportSet<T> {
|
||||
pub fn new(methods: Vec<T>) -> Self {
|
||||
Self {
|
||||
supported_report: methods
|
||||
.into_iter()
|
||||
.map(|method| ReportWrapper { report: method })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all() -> Self
|
||||
where
|
||||
T: VariantArray,
|
||||
{
|
||||
Self::new(T::VARIANTS.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct ReportWrapper<T: XmlSerialize> {
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
report: T,
|
||||
}
|
||||
@@ -23,20 +23,23 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_serialize_resourcetype() {
|
||||
let mut buf = Vec::new();
|
||||
let mut writer = quick_xml::Writer::new(&mut buf);
|
||||
Document {
|
||||
let out = Document {
|
||||
resourcetype: Resourcetype(&[
|
||||
ResourcetypeInner(Some(crate::namespace::NS_DAV), "displayname"),
|
||||
ResourcetypeInner(Some(crate::namespace::NS_CALENDARSERVER), "calendar-color"),
|
||||
]),
|
||||
}
|
||||
.serialize_root(&mut writer)
|
||||
.serialize_to_string()
|
||||
.unwrap();
|
||||
let out = String::from_utf8(buf).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
"<document><resourcetype><displayname xmlns=\"DAV:\"/><calendar-color xmlns=\"http://calendarserver.org/ns/\"/></resourcetype></document>"
|
||||
r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<document>
|
||||
<resourcetype>
|
||||
<displayname xmlns="DAV:"/>
|
||||
<calendar-color xmlns="http://calendarserver.org/ns/"/>
|
||||
</resourcetype>
|
||||
</document>"#
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlDeserialize};
|
||||
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlDeserialize, XmlRootTag};
|
||||
|
||||
use super::PropfindType;
|
||||
|
||||
@@ -32,11 +32,35 @@ impl ValueSerialize for SyncLevel {
|
||||
}
|
||||
}
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/rfc5323#section-5.17
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
pub struct LimitElement {
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
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)]
|
||||
pub struct NresultsElement(#[xml(ty = "text")] u64);
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, XmlRootTag)]
|
||||
// <!ELEMENT sync-collection (sync-token, sync-level, limit?, prop)>
|
||||
// <!-- DAV:limit defined in RFC 5323, Section 5.17 -->
|
||||
// <!-- DAV:prop defined in RFC 4918, Section 14.18 -->
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
#[xml(ns = "crate::namespace::NS_DAV", root = b"sync-collection")]
|
||||
pub struct SyncCollectionRequest<PN: XmlDeserialize> {
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub sync_token: String,
|
||||
@@ -45,5 +69,48 @@ pub struct SyncCollectionRequest<PN: XmlDeserialize> {
|
||||
#[xml(ns = "crate::namespace::NS_DAV", ty = "untagged")]
|
||||
pub prop: PropfindType<PN>,
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub limit: Option<u64>,
|
||||
pub limit: Option<LimitElement>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::xml::{
|
||||
PropElement, PropfindType,
|
||||
sync_collection::{SyncCollectionRequest, SyncLevel},
|
||||
};
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlDocument};
|
||||
|
||||
const SYNC_COLLECTION_REQUEST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<sync-collection xmlns="DAV:">
|
||||
<sync-token />
|
||||
<sync-level>1</sync-level>
|
||||
<limit>
|
||||
<nresults>100</nresults>
|
||||
</limit>
|
||||
<prop>
|
||||
<getetag />
|
||||
</prop>
|
||||
</sync-collection>
|
||||
"#;
|
||||
|
||||
#[derive(XmlDeserialize, PropName, EnumVariants, PartialEq)]
|
||||
#[xml(unit_variants_ident = "TestPropName")]
|
||||
enum TestProp {
|
||||
Getetag(String),
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_sync_collection_request() {
|
||||
let request =
|
||||
SyncCollectionRequest::<TestPropName>::parse_str(SYNC_COLLECTION_REQUEST).unwrap();
|
||||
assert_eq!(
|
||||
request,
|
||||
SyncCollectionRequest {
|
||||
sync_token: "".to_owned(),
|
||||
sync_level: SyncLevel::One,
|
||||
prop: PropfindType::Prop(PropElement(vec![TestPropName::Getetag], vec![])),
|
||||
limit: Some(100.into())
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use derive_more::derive::From;
|
||||
use quick_xml::name::Namespace;
|
||||
use quick_xml::{
|
||||
events::{BytesEnd, BytesStart, Event},
|
||||
name::Namespace,
|
||||
};
|
||||
use rustical_xml::{NamespaceOwned, XmlSerialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -7,13 +10,39 @@ use std::collections::HashMap;
|
||||
pub struct TagList(Vec<(Option<NamespaceOwned>, String)>);
|
||||
|
||||
impl XmlSerialize for TagList {
|
||||
fn serialize<W: std::io::Write>(
|
||||
fn serialize(
|
||||
&self,
|
||||
_ns: Option<Namespace>,
|
||||
_tag: Option<&[u8]>,
|
||||
_namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
) -> std::io::Result<()> {
|
||||
let prefix = ns
|
||||
.map(|ns| namespaces.get(&ns))
|
||||
.unwrap_or(None)
|
||||
.map(|prefix| {
|
||||
if !prefix.is_empty() {
|
||||
[*prefix, b":"].concat()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
});
|
||||
let has_prefix = prefix.is_some();
|
||||
let tagname = tag.map(|tag| [&prefix.unwrap_or_default(), tag].concat());
|
||||
let qname = tagname
|
||||
.as_ref()
|
||||
.map(|tagname| ::quick_xml::name::QName(tagname));
|
||||
|
||||
if let Some(qname) = &qname {
|
||||
let mut bytes_start = BytesStart::from(qname.to_owned());
|
||||
if !has_prefix {
|
||||
if let Some(ns) = &ns {
|
||||
bytes_start.push_attribute((b"xmlns".as_ref(), ns.as_ref()));
|
||||
}
|
||||
}
|
||||
writer.write_event(Event::Start(bytes_start))?;
|
||||
}
|
||||
|
||||
for (ns, tag) in &self.0 {
|
||||
let mut el = writer.create_element(tag);
|
||||
if let Some(ns) = ns {
|
||||
@@ -21,10 +50,13 @@ impl XmlSerialize for TagList {
|
||||
}
|
||||
el.write_empty()?;
|
||||
}
|
||||
|
||||
if let Some(qname) = &qname {
|
||||
writer.write_event(Event::End(BytesEnd::from(qname.to_owned())))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(refining_impl_trait)]
|
||||
fn attributes<'a>(&self) -> Option<Vec<quick_xml::events::attributes::Attribute<'a>>> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
@@ -22,3 +23,7 @@ tokio.workspace = true
|
||||
rustical_dav.workspace = true
|
||||
rustical_store.workspace = true
|
||||
http.workspace = true
|
||||
base64.workspace = true
|
||||
ece.workspace = true
|
||||
axum.workspace = true
|
||||
openssl.workspace = true
|
||||
|
||||
23
crates/dav_push/src/endpoints.rs
Normal file
23
crates/dav_push/src/endpoints.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
routing::delete,
|
||||
};
|
||||
use http::StatusCode;
|
||||
use rustical_store::SubscriptionStore;
|
||||
use std::sync::Arc;
|
||||
|
||||
async fn handle_delete<S: SubscriptionStore>(
|
||||
State(store): State<Arc<S>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Response, rustical_store::Error> {
|
||||
store.delete_subscription(&id).await?;
|
||||
Ok((StatusCode::NO_CONTENT, "Unregistered").into_response())
|
||||
}
|
||||
|
||||
pub fn subscription_service<S: SubscriptionStore>(sub_store: Arc<S>) -> Router {
|
||||
Router::new()
|
||||
.route("/push_subscription/{id}", delete(handle_delete::<S>))
|
||||
.with_state(sub_store)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user