mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-13 21:42:34 +00:00
Compare commits
281 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a26f44dd7 | ||
|
|
f8a660c222 | ||
|
|
a991baaf7d | ||
|
|
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 | ||
|
|
a20e9800bd | ||
|
|
80cca7b7b2 | ||
|
|
f04987a171 | ||
|
|
3eeef18a14 | ||
|
|
32225bdda8 | ||
|
|
103ac0b1f9 | ||
|
|
300a0024ee | ||
|
|
0dbc05345b | ||
|
|
b5f23b0f9b | ||
|
|
5ee789bec1 | ||
|
|
49aab931d0 | ||
|
|
7628cdafbd | ||
|
|
6d6f8f20df | ||
|
|
fc590976bc | ||
|
|
71c2f8c019 | ||
|
|
0595920809 | ||
|
|
0feaaaaca1 | ||
|
|
e000165555 | ||
|
|
487e99216a | ||
|
|
38dcf88f24 | ||
|
|
2ce0c00f89 | ||
|
|
38de0ab268 | ||
|
|
9dd5995950 | ||
|
|
2ba0beeafc | ||
|
|
8f29a468db | ||
|
|
764d049d3c | ||
|
|
720e6f6115 | ||
|
|
d5b43b33f4 | ||
|
|
6ae2276035 | ||
|
|
152bf374d7 | ||
|
|
61f14ca072 | ||
|
|
6bcad7cc65 | ||
|
|
e58973d366 | ||
|
|
573781310a | ||
|
|
bbe9113f5c | ||
|
|
ac1dbb29d8 | ||
|
|
1d25d6cc70 | ||
|
|
c05c330601 | ||
|
|
00eb43f048 | ||
|
|
95889e3df1 | ||
|
|
790c657b08 | ||
|
|
57832116aa | ||
|
|
0c6aef7c06 | ||
|
|
22ed278dbb | ||
|
|
1a827a164f | ||
|
|
e57a14cad1 | ||
|
|
5ad6ee2e99 | ||
|
|
c14f98a432 | ||
|
|
7f3ce01c2b | ||
|
|
5a6ffd3c19 | ||
|
|
cf3e213894 | ||
|
|
13128a5caa | ||
|
|
9836a696ad | ||
|
|
05ff2536f6 | ||
|
|
bcc6bef848 | ||
|
|
088b920b68 | ||
|
|
3c9c1c7abf | ||
|
|
b7c24fe2f0 | ||
|
|
08c4bd4289 | ||
|
|
ef33868151 | ||
|
|
0f294cf2e1 | ||
|
|
fb8889b5f6 | ||
|
|
5ebcab7a19 | ||
|
|
3c7ee09116 | ||
|
|
f55224b21a | ||
|
|
0acc3c22d9 | ||
|
|
212274fce9 | ||
|
|
1436af1f9c | ||
|
|
8f69bc839a | ||
|
|
37eb6df64a | ||
|
|
3af9b3b8b4 | ||
|
|
d14ded7179 | ||
|
|
de6ccdc37b | ||
|
|
86ecaef6db | ||
|
|
2686530024 |
@@ -2,3 +2,5 @@
|
|||||||
indent_style = space
|
indent_style = space
|
||||||
indent_size = 4
|
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:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: ["main"]
|
branches: ["main"]
|
||||||
|
release:
|
||||||
|
types: ["published"]
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: ghcr.io
|
REGISTRY: ghcr.io
|
||||||
IMAGE_NAME: ${{ github.repository }}
|
IMAGE_NAME: ${{ github.repository }}
|
||||||
@@ -38,13 +41,10 @@ jobs:
|
|||||||
# https://github.com/docker/metadata-action
|
# https://github.com/docker/metadata-action
|
||||||
- name: Extract Docker metadata
|
- name: Extract Docker metadata
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
|
uses: docker/metadata-action@v5
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
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: |
|
tags: |
|
||||||
type=raw,value=latest,enable={{is_default_branch}}
|
|
||||||
type=ref,event=branch
|
type=ref,event=branch
|
||||||
type=ref,event=pr
|
type=ref,event=pr
|
||||||
type=semver,pattern={{version}}
|
type=semver,pattern={{version}}
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -12,3 +12,7 @@ principals.toml
|
|||||||
.env
|
.env
|
||||||
|
|
||||||
site
|
site
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
**/node_modules
|
||||||
|
**/.vite
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"db_name": "SQLite",
|
"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": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -22,5 +22,5 @@
|
|||||||
false
|
false
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"hash": "395e40a7b3333b79bc2ad50a123d99f74bc2712a16257ee2119dd211fdb61f7e"
|
"hash": "246ec675667992c1297c29348d46496a884c59adb8b64b569d36f4ce10f88f47"
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"db_name": "SQLite",
|
"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": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -14,68 +14,63 @@
|
|||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "synctoken",
|
"name": "displayname",
|
||||||
"ordinal": 2,
|
"ordinal": 2,
|
||||||
"type_info": "Integer"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "displayname",
|
"name": "order",
|
||||||
"ordinal": 3,
|
"ordinal": 3,
|
||||||
"type_info": "Text"
|
"type_info": "Integer"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "description",
|
"name": "description",
|
||||||
"ordinal": 4,
|
"ordinal": 4,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "order",
|
|
||||||
"ordinal": 5,
|
|
||||||
"type_info": "Integer"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "color",
|
"name": "color",
|
||||||
"ordinal": 6,
|
"ordinal": 5,
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "timezone",
|
|
||||||
"ordinal": 7,
|
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "timezone_id",
|
"name": "timezone_id",
|
||||||
"ordinal": 8,
|
"ordinal": 6,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "deleted_at",
|
"name": "deleted_at",
|
||||||
"ordinal": 9,
|
"ordinal": 7,
|
||||||
"type_info": "Datetime"
|
"type_info": "Datetime"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "synctoken",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "subscription_url",
|
"name": "subscription_url",
|
||||||
"ordinal": 10,
|
"ordinal": 9,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "push_topic",
|
"name": "push_topic",
|
||||||
"ordinal": 11,
|
"ordinal": 10,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_event",
|
"name": "comp_event",
|
||||||
"ordinal": 12,
|
"ordinal": 11,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_todo",
|
"name": "comp_todo",
|
||||||
"ordinal": 13,
|
"ordinal": 12,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_journal",
|
"name": "comp_journal",
|
||||||
"ordinal": 14,
|
"ordinal": 13,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -85,14 +80,13 @@
|
|||||||
"nullable": [
|
"nullable": [
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
false,
|
|
||||||
true,
|
|
||||||
true,
|
true,
|
||||||
false,
|
false,
|
||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
|
false,
|
||||||
true,
|
true,
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
@@ -100,5 +94,5 @@
|
|||||||
false
|
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",
|
"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": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -15,12 +15,12 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"Right": 3
|
"Right": 4
|
||||||
},
|
},
|
||||||
"nullable": [
|
"nullable": [
|
||||||
false,
|
false,
|
||||||
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",
|
"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": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -39,48 +39,43 @@
|
|||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "timezone",
|
"name": "timezone_id",
|
||||||
"ordinal": 7,
|
"ordinal": 7,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "timezone_id",
|
|
||||||
"ordinal": 8,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "deleted_at",
|
"name": "deleted_at",
|
||||||
"ordinal": 9,
|
"ordinal": 8,
|
||||||
"type_info": "Datetime"
|
"type_info": "Datetime"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "subscription_url",
|
"name": "subscription_url",
|
||||||
"ordinal": 10,
|
"ordinal": 9,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "push_topic",
|
"name": "push_topic",
|
||||||
"ordinal": 11,
|
"ordinal": 10,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_event",
|
"name": "comp_event",
|
||||||
"ordinal": 12,
|
"ordinal": 11,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_todo",
|
"name": "comp_todo",
|
||||||
"ordinal": 13,
|
"ordinal": 12,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_journal",
|
"name": "comp_journal",
|
||||||
"ordinal": 14,
|
"ordinal": 13,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"Right": 2
|
"Right": 3
|
||||||
},
|
},
|
||||||
"nullable": [
|
"nullable": [
|
||||||
false,
|
false,
|
||||||
@@ -93,12 +88,11 @@
|
|||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
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"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "timezone",
|
"name": "timezone_id",
|
||||||
"ordinal": 7,
|
"ordinal": 7,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "timezone_id",
|
|
||||||
"ordinal": 8,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "deleted_at",
|
"name": "deleted_at",
|
||||||
"ordinal": 9,
|
"ordinal": 8,
|
||||||
"type_info": "Datetime"
|
"type_info": "Datetime"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "subscription_url",
|
"name": "subscription_url",
|
||||||
"ordinal": 10,
|
"ordinal": 9,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "push_topic",
|
"name": "push_topic",
|
||||||
"ordinal": 11,
|
"ordinal": 10,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_event",
|
"name": "comp_event",
|
||||||
"ordinal": 12,
|
"ordinal": 11,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_todo",
|
"name": "comp_todo",
|
||||||
"ordinal": 13,
|
"ordinal": 12,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "comp_journal",
|
"name": "comp_journal",
|
||||||
"ordinal": 14,
|
"ordinal": 13,
|
||||||
"type_info": "Bool"
|
"type_info": "Bool"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -93,7 +88,6 @@
|
|||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
|
||||||
false,
|
false,
|
||||||
false,
|
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"
|
||||||
|
}
|
||||||
2523
Cargo.lock
generated
2523
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
75
Cargo.toml
75
Cargo.toml
@@ -2,10 +2,11 @@
|
|||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.8.4"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "A CalDAV server"
|
description = "A CalDAV server"
|
||||||
repository = "https://github.com/lennart-k/rustical"
|
repository = "https://github.com/lennart-k/rustical"
|
||||||
|
license = "AGPL-3.0-or-later"
|
||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "rustical"
|
name = "rustical"
|
||||||
@@ -13,11 +14,13 @@ version.workspace = true
|
|||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
description.workspace = true
|
description.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
license.workspace = true
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
debug = ["opentelemetry"]
|
debug = ["opentelemetry"]
|
||||||
|
frontend-dev = ["rustical_frontend/dev"]
|
||||||
opentelemetry = [
|
opentelemetry = [
|
||||||
"dep:opentelemetry",
|
"dep:opentelemetry",
|
||||||
"dep:opentelemetry-otlp",
|
"dep:opentelemetry-otlp",
|
||||||
@@ -26,17 +29,16 @@ opentelemetry = [
|
|||||||
"dep:tracing-opentelemetry",
|
"dep:tracing-opentelemetry",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
[profile.dev]
|
[profile.dev]
|
||||||
debug = 0
|
debug = 0
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
|
matchit = "0.8"
|
||||||
uuid = { version = "1.11", features = ["v4", "fast-rng"] }
|
uuid = { version = "1.11", features = ["v4", "fast-rng"] }
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
actix-web = "4.9"
|
axum = "0.8"
|
||||||
tracing = { version = "0.1", features = ["async-await"] }
|
tracing = { version = "0.1", features = ["async-await"] }
|
||||||
tracing-actix-web = "0.7"
|
|
||||||
actix-session = { version = "0.10", features = ["cookie-session"] }
|
|
||||||
actix-web-httpauth = "0.8"
|
|
||||||
anyhow = { version = "1.0", features = ["backtrace"] }
|
anyhow = { version = "1.0", features = ["backtrace"] }
|
||||||
serde = { version = "1.0", features = ["serde_derive", "derive", "rc"] }
|
serde = { version = "1.0", features = ["serde_derive", "derive", "rc"] }
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
@@ -61,9 +63,10 @@ base64 = "0.22"
|
|||||||
thiserror = "2.0"
|
thiserror = "2.0"
|
||||||
quick-xml = { version = "0.37" }
|
quick-xml = { version = "0.37" }
|
||||||
rust-embed = "8.5"
|
rust-embed = "8.5"
|
||||||
|
tower-sessions = "0.14"
|
||||||
futures-core = "0.3.31"
|
futures-core = "0.3.31"
|
||||||
hex = { version = "0.4.3", features = ["serde"] }
|
hex = { version = "0.4.3", features = ["serde"] }
|
||||||
mime_guess = "2.0.5"
|
mime_guess = "2.0"
|
||||||
itertools = "0.14"
|
itertools = "0.14"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
derive_more = { version = "2.0", features = [
|
derive_more = { version = "2.0", features = [
|
||||||
@@ -72,9 +75,10 @@ derive_more = { version = "2.0", features = [
|
|||||||
"into",
|
"into",
|
||||||
"deref",
|
"deref",
|
||||||
"constructor",
|
"constructor",
|
||||||
|
"display",
|
||||||
] }
|
] }
|
||||||
askama = { version = "0.13", features = ["serde_json"] }
|
askama = { version = "0.14", features = ["serde_json"] }
|
||||||
askama_web = { version = "0.13.0", features = ["actix-web-4"] }
|
askama_web = { version = "0.14.0", features = ["axum-0.8"] }
|
||||||
sqlx = { version = "0.8", default-features = false, features = [
|
sqlx = { version = "0.8", default-features = false, features = [
|
||||||
"sqlx-sqlite",
|
"sqlx-sqlite",
|
||||||
"uuid",
|
"uuid",
|
||||||
@@ -85,12 +89,25 @@ sqlx = { version = "0.8", default-features = false, features = [
|
|||||||
"migrate",
|
"migrate",
|
||||||
"json",
|
"json",
|
||||||
] }
|
] }
|
||||||
|
http = "1.3"
|
||||||
|
headers = "0.4"
|
||||||
strum = "0.27"
|
strum = "0.27"
|
||||||
strum_macros = "0.27"
|
strum_macros = "0.27"
|
||||||
serde_json = { version = "1.0", features = ["raw_value"] }
|
serde_json = { version = "1.0", features = ["raw_value"] }
|
||||||
sqlx-sqlite = { version = "0.8", features = ["bundled"] }
|
sqlx-sqlite = { version = "0.8", features = ["bundled"] }
|
||||||
ical = { version = "0.11", features = ["generator", "serde"] }
|
ical = { git = "https://github.com/lennart-k/ical-rs", features = [
|
||||||
toml = "0.8"
|
"generator",
|
||||||
|
"serde",
|
||||||
|
"chrono-tz",
|
||||||
|
] }
|
||||||
|
toml = "0.9"
|
||||||
|
tower = "0.5"
|
||||||
|
tower-http = { version = "0.6", features = [
|
||||||
|
"trace",
|
||||||
|
"normalize-path",
|
||||||
|
"catch-panic",
|
||||||
|
] }
|
||||||
|
percent-encoding = "2.3"
|
||||||
rustical_dav = { path = "./crates/dav/" }
|
rustical_dav = { path = "./crates/dav/" }
|
||||||
rustical_dav_push = { path = "./crates/dav_push/" }
|
rustical_dav_push = { path = "./crates/dav_push/" }
|
||||||
rustical_store = { path = "./crates/store/" }
|
rustical_store = { path = "./crates/store/" }
|
||||||
@@ -100,9 +117,12 @@ rustical_carddav = { path = "./crates/carddav/" }
|
|||||||
rustical_frontend = { path = "./crates/frontend/" }
|
rustical_frontend = { path = "./crates/frontend/" }
|
||||||
rustical_xml = { path = "./crates/xml/" }
|
rustical_xml = { path = "./crates/xml/" }
|
||||||
rustical_oidc = { path = "./crates/oidc/" }
|
rustical_oidc = { path = "./crates/oidc/" }
|
||||||
|
rustical_ical = { path = "./crates/ical/" }
|
||||||
chrono-tz = "0.10"
|
chrono-tz = "0.10"
|
||||||
chrono-humanize = "0.2"
|
chrono-humanize = "0.2"
|
||||||
rand = "0.8"
|
rand = "0.9"
|
||||||
|
axum-extra = { version = "0.10", features = ["typed-header"] }
|
||||||
|
rrule = "0.14"
|
||||||
argon2 = "0.5"
|
argon2 = "0.5"
|
||||||
rpassword = "7.3"
|
rpassword = "7.3"
|
||||||
password-hash = { version = "0.5" }
|
password-hash = { version = "0.5" }
|
||||||
@@ -110,7 +130,7 @@ syn = { version = "2.0", features = ["full"] }
|
|||||||
quote = "1.0"
|
quote = "1.0"
|
||||||
proc-macro2 = "1.0"
|
proc-macro2 = "1.0"
|
||||||
heck = "0.5"
|
heck = "0.5"
|
||||||
darling = "0.20"
|
darling = "0.21"
|
||||||
reqwest = { version = "0.12", features = [
|
reqwest = { version = "0.12", features = [
|
||||||
"rustls-tls",
|
"rustls-tls",
|
||||||
"charset",
|
"charset",
|
||||||
@@ -118,14 +138,20 @@ reqwest = { version = "0.12", features = [
|
|||||||
], default-features = false }
|
], default-features = false }
|
||||||
openidconnect = "4.0"
|
openidconnect = "4.0"
|
||||||
clap = { version = "4.5", features = ["derive", "env"] }
|
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]
|
[dependencies]
|
||||||
rustical_store = { workspace = true }
|
rustical_store = { workspace = true }
|
||||||
rustical_store_sqlite = { workspace = true }
|
rustical_store_sqlite = { workspace = true }
|
||||||
rustical_caldav = { workspace = true }
|
rustical_caldav = { workspace = true }
|
||||||
rustical_carddav = { workspace = true }
|
rustical_carddav.workspace = true
|
||||||
rustical_frontend = { workspace = true }
|
rustical_frontend = { workspace = true }
|
||||||
actix-web = { workspace = true }
|
|
||||||
toml = { workspace = true }
|
toml = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
@@ -134,28 +160,27 @@ anyhow = { workspace = true }
|
|||||||
clap.workspace = true
|
clap.workspace = true
|
||||||
sqlx = { workspace = true }
|
sqlx = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
tracing-actix-web = { workspace = true }
|
|
||||||
uuid.workspace = true
|
uuid.workspace = true
|
||||||
|
axum.workspace = true
|
||||||
|
|
||||||
opentelemetry = { version = "0.29", optional = true }
|
opentelemetry = { version = "0.30", optional = true }
|
||||||
opentelemetry-otlp = { version = "0.29", optional = true, features = [
|
opentelemetry-otlp = { version = "0.30", optional = true, features = [
|
||||||
"grpc-tonic",
|
"grpc-tonic",
|
||||||
] }
|
] }
|
||||||
opentelemetry_sdk = { version = "0.29", features = [
|
opentelemetry_sdk = { version = "0.30", features = [
|
||||||
"rt-tokio",
|
"rt-tokio",
|
||||||
], optional = true }
|
], optional = true }
|
||||||
opentelemetry-semantic-conventions = { version = "0.29", optional = true }
|
opentelemetry-semantic-conventions = { version = "0.30", optional = true }
|
||||||
tracing-opentelemetry = { version = "0.30", optional = true }
|
tracing-opentelemetry = { version = "0.31", optional = true }
|
||||||
tracing-subscriber = { version = "0.3", features = [
|
tracing-subscriber = { version = "0.3", features = [
|
||||||
"env-filter",
|
"env-filter",
|
||||||
"fmt",
|
"fmt",
|
||||||
"registry",
|
"registry",
|
||||||
] }
|
] }
|
||||||
|
|
||||||
figment = { version = "0.10", features = ["env", "toml"] }
|
figment = { version = "0.10", features = ["env", "toml"] }
|
||||||
|
tower-sessions.workspace = true
|
||||||
rand.workspace = true
|
|
||||||
rpassword.workspace = true
|
rpassword.workspace = true
|
||||||
|
tower.workspace = true
|
||||||
argon2.workspace = true
|
argon2.workspace = true
|
||||||
pbkdf2.workspace = true
|
pbkdf2.workspace = true
|
||||||
password-hash.workspace = true
|
password-hash.workspace = true
|
||||||
@@ -164,3 +189,7 @@ rustical_dav.workspace = true
|
|||||||
rustical_dav_push.workspace = true
|
rustical_dav_push.workspace = true
|
||||||
rustical_oidc.workspace = true
|
rustical_oidc.workspace = true
|
||||||
quick-xml.workspace = true
|
quick-xml.workspace = true
|
||||||
|
tower-http.workspace = true
|
||||||
|
axum-extra.workspace = true
|
||||||
|
headers.workspace = true
|
||||||
|
http.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 TARGETPLATFORM
|
||||||
ARG BUILDPLATFORM
|
ARG BUILDPLATFORM
|
||||||
|
|
||||||
# the compiler will otherwise ask for aarch64-linux-musl-gcc
|
# the compiler will otherwise ask for aarch64-linux-musl-gcc
|
||||||
ENV CC_aarch64_unknown_linux_musl="clang"
|
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"
|
ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS="-Clink-self-contained=yes -Clinker=rust-lld"
|
||||||
|
|
||||||
# Stupid workaound with tempfiles since environment variables
|
# Stupid workaound with tempfiles since environment variables
|
||||||
@@ -16,7 +16,7 @@ RUN case $TARGETPLATFORM in \
|
|||||||
*) echo "Unsupported platform ${TARGETPLATFORM}"; exit 1;; \
|
*) echo "Unsupported platform ${TARGETPLATFORM}"; exit 1;; \
|
||||||
esac
|
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)" \
|
&& rustup target add "$(cat /tmp/rust_target)" \
|
||||||
&& cargo install cargo-chef --locked \
|
&& cargo install cargo-chef --locked \
|
||||||
&& rm -rf "$CARGO_HOME/registry"
|
&& rm -rf "$CARGO_HOME/registry"
|
||||||
@@ -42,5 +42,7 @@ FROM scratch
|
|||||||
COPY --from=builder /usr/local/cargo/bin/rustical /usr/local/bin/rustical
|
COPY --from=builder /usr/local/cargo/bin/rustical /usr/local/bin/rustical
|
||||||
CMD ["/usr/local/bin/rustical"]
|
CMD ["/usr/local/bin/rustical"]
|
||||||
|
|
||||||
|
ENV RUSTICAL_DATA_STORE__SQLITE__DB_URL=/var/lib/rustical/db.sqlite3
|
||||||
|
|
||||||
LABEL org.opencontainers.image.authors="Lennart K github.com/lennart-k"
|
LABEL org.opencontainers.image.authors="Lennart K github.com/lennart-k"
|
||||||
EXPOSE 4000
|
EXPOSE 4000
|
||||||
|
|||||||
14
Justfile
Normal file
14
Justfile
Normal file
@@ -0,0 +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
|
a CalDAV/CardDAV server
|
||||||
|
|
||||||
> [!WARNING]
|
> [!WARNING]
|
||||||
> RustiCal is **not production-ready!**
|
RustiCal is under **active development**!
|
||||||
> I'm just starting to use it myself so I cannot guarantee that everything will be working smoothly just yet.
|
While I've been successfully using RustiCal productively for a few weeks now,
|
||||||
> 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.
|
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. :)
|
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
|
## Features
|
||||||
|
|
||||||
- easy to backup, everything saved in one SQLite database
|
- easy to backup, everything saved in one SQLite database
|
||||||
- [WebDAV Push](https://github.com/bitfireAT/webdav-push/) support, so near-instant synchronisation to DAVx5
|
- 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)
|
- 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)
|
- adequately fast (I'd love to say blazingly fast™ :fire: but I don't have any benchmarks)
|
||||||
- deleted calendars are recoverable
|
- deleted calendars are recoverable
|
||||||
- Nextcloud login flow (In DAVx5 you can login through the Nextcloud flow and automatically generate an app token)
|
- 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)
|
- 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
|
## Getting Started
|
||||||
|
|
||||||
- Check out the [documentation](https://lennart-k.github.io/rustical/installation/)
|
- 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
|
||||||
|
|||||||
70
about.hbs
Normal file
70
about.hbs
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<style>
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
body {
|
||||||
|
background: #333;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
color: skyblue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.container {
|
||||||
|
font-family: sans-serif;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
.intro {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.licenses-list {
|
||||||
|
list-style-type: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.license-used-by {
|
||||||
|
margin-top: -10px;
|
||||||
|
}
|
||||||
|
.license-text {
|
||||||
|
max-height: 200px;
|
||||||
|
overflow-y: scroll;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<main class="container">
|
||||||
|
<div class="intro">
|
||||||
|
<h1>Third Party Licenses</h1>
|
||||||
|
<p>This page lists the licenses of packages used by RustiCal.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>Overview of licenses:</h2>
|
||||||
|
<ul class="licenses-overview">
|
||||||
|
{{#each overview}}
|
||||||
|
<li><a href="#{{id}}">{{name}}</a> ({{count}})</li>
|
||||||
|
{{/each}}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>All license text:</h2>
|
||||||
|
<ul class="licenses-list">
|
||||||
|
{{#each licenses}}
|
||||||
|
<li class="license">
|
||||||
|
<h3 id="{{id}}">{{name}}</h3>
|
||||||
|
<h4>Used by:</h4>
|
||||||
|
<ul class="license-used-by">
|
||||||
|
{{#each used_by}}
|
||||||
|
<li><a href="{{#if crate.repository}} {{crate.repository}} {{else}} https://crates.io/crates/{{crate.name}} {{/if}}">{{crate.name}} {{crate.version}}</a></li>
|
||||||
|
{{/each}}
|
||||||
|
</ul>
|
||||||
|
<pre class="license-text">{{text}}</pre>
|
||||||
|
</li>
|
||||||
|
{{/each}}
|
||||||
|
</ul>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
12
about.toml
Normal file
12
about.toml
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
accepted = [
|
||||||
|
"Apache-2.0",
|
||||||
|
"MIT",
|
||||||
|
"BSD-3-Clause",
|
||||||
|
"ISC",
|
||||||
|
"Unicode-3.0",
|
||||||
|
"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,18 +4,25 @@ version.workspace = true
|
|||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
description.workspace = true
|
description.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
license.workspace = true
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
rustical_store_sqlite = { workspace = true, features = ["test"] }
|
||||||
|
rstest.workspace = true
|
||||||
|
async-std.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { workspace = true }
|
axum.workspace = true
|
||||||
|
axum-extra.workspace = true
|
||||||
|
tower.workspace = true
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
quick-xml = { workspace = true }
|
quick-xml = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
tracing-actix-web = { workspace = true }
|
|
||||||
futures-util = { workspace = true }
|
futures-util = { workspace = true }
|
||||||
derive_more = { workspace = true }
|
derive_more = { workspace = true }
|
||||||
actix-web-httpauth = { workspace = true }
|
|
||||||
base64 = { workspace = true }
|
base64 = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
@@ -25,6 +32,15 @@ rustical_store = { workspace = true }
|
|||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
chrono-tz = { workspace = true }
|
chrono-tz = { workspace = true }
|
||||||
sha2 = { workspace = true }
|
sha2 = { workspace = true }
|
||||||
|
ical.workspace = true
|
||||||
|
percent-encoding.workspace = true
|
||||||
rustical_xml.workspace = true
|
rustical_xml.workspace = true
|
||||||
uuid.workspace = true
|
uuid.workspace = true
|
||||||
rustical_dav_push.workspace = true
|
rustical_dav_push.workspace = true
|
||||||
|
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
|
||||||
|
|||||||
108
crates/caldav/src/calendar/methods/get.rs
Normal file
108
crates/caldav/src/calendar/methods/get.rs
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
use crate::Error;
|
||||||
|
use crate::calendar::CalendarResourceService;
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::{extract::Path, response::Response};
|
||||||
|
use headers::{ContentType, HeaderMapExt};
|
||||||
|
use http::{HeaderValue, Method, StatusCode, header};
|
||||||
|
use ical::generator::{Emitter, IcalCalendarBuilder};
|
||||||
|
use ical::property::Property;
|
||||||
|
use percent_encoding::{CONTROLS, utf8_percent_encode};
|
||||||
|
use rustical_ical::{CalendarObjectComponent, EventObject, JournalObject, TodoObject};
|
||||||
|
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
|
#[instrument(skip(cal_store))]
|
||||||
|
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: 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, true)
|
||||||
|
.await?;
|
||||||
|
if !user.is_principal(&calendar.principal) {
|
||||||
|
return Err(crate::Error::Unauthorized);
|
||||||
|
}
|
||||||
|
|
||||||
|
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?;
|
||||||
|
|
||||||
|
let mut ical_calendar_builder = IcalCalendarBuilder::version("4.0")
|
||||||
|
.gregorian()
|
||||||
|
.prodid("RustiCal");
|
||||||
|
if calendar.displayname.is_some() {
|
||||||
|
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||||
|
name: "X-WR-CALNAME".to_owned(),
|
||||||
|
value: calendar.displayname,
|
||||||
|
params: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if calendar.description.is_some() {
|
||||||
|
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||||
|
name: "X-WR-CALDESC".to_owned(),
|
||||||
|
value: calendar.description,
|
||||||
|
params: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if calendar.timezone_id.is_some() {
|
||||||
|
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||||
|
name: "X-WR-TIMEZONE".to_owned(),
|
||||||
|
value: calendar.timezone_id,
|
||||||
|
params: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for object in &objects {
|
||||||
|
match object.get_data() {
|
||||||
|
CalendarObjectComponent::Event(EventObject {
|
||||||
|
event,
|
||||||
|
timezones: object_timezones,
|
||||||
|
..
|
||||||
|
}) => {
|
||||||
|
timezones.extend(object_timezones);
|
||||||
|
ical_calendar_builder = ical_calendar_builder.add_event(event.clone());
|
||||||
|
}
|
||||||
|
CalendarObjectComponent::Todo(TodoObject(todo)) => {
|
||||||
|
ical_calendar_builder = ical_calendar_builder.add_todo(todo.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());
|
||||||
|
|
||||||
|
let filename = format!("{}_{}.ics", calendar.principal, calendar.id);
|
||||||
|
let filename = utf8_percent_encode(&filename, CONTROLS);
|
||||||
|
hdrs.insert(
|
||||||
|
header::CONTENT_DISPOSITION,
|
||||||
|
HeaderValue::from_str(&format!(
|
||||||
|
"attachement; filename*=UTF-8''{filename}; filename={filename}",
|
||||||
|
))
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
if matches!(method, Method::HEAD) {
|
||||||
|
Ok(resp.body(Body::empty()).unwrap())
|
||||||
|
} else {
|
||||||
|
Ok(resp.body(Body::new(ical_calendar.generate())).unwrap())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
use crate::Error;
|
use crate::Error;
|
||||||
|
use crate::calendar::CalendarResourceService;
|
||||||
use crate::calendar::prop::SupportedCalendarComponentSet;
|
use crate::calendar::prop::SupportedCalendarComponentSet;
|
||||||
use actix_web::HttpResponse;
|
use axum::extract::{Path, State};
|
||||||
use actix_web::web::{Data, Path};
|
use axum::response::{IntoResponse, Response};
|
||||||
use rustical_store::auth::User;
|
use http::{Method, StatusCode};
|
||||||
use rustical_store::calendar::CalendarObjectType;
|
use ical::IcalParser;
|
||||||
use rustical_store::{Calendar, CalendarStore};
|
use rustical_dav::xml::HrefElement;
|
||||||
|
use rustical_ical::CalendarObjectType;
|
||||||
|
use rustical_store::auth::Principal;
|
||||||
|
use rustical_store::{Calendar, CalendarStore, SubscriptionStore};
|
||||||
use rustical_xml::{Unparsed, XmlDeserialize, XmlDocument, XmlRootTag};
|
use rustical_xml::{Unparsed, XmlDeserialize, XmlDocument, XmlRootTag};
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug)]
|
#[derive(XmlDeserialize, Clone, Debug)]
|
||||||
pub struct MkcolCalendarProp {
|
pub struct MkcolCalendarProp {
|
||||||
@@ -28,6 +31,8 @@ pub struct MkcolCalendarProp {
|
|||||||
resourcetype: Option<Unparsed>,
|
resourcetype: Option<Unparsed>,
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
supported_calendar_component_set: Option<SupportedCalendarComponentSet>,
|
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
|
// Ignore that property, we don't support it but also don't want to throw an error
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@@ -48,34 +53,73 @@ struct MkcalendarRequest {
|
|||||||
set: PropElement,
|
set: PropElement,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(store, root_span))]
|
#[derive(XmlDeserialize, XmlRootTag, Clone, Debug)]
|
||||||
pub async fn route_mkcalendar<C: CalendarStore>(
|
#[xml(root = b"mkcol")]
|
||||||
path: Path<(String, String)>,
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
|
struct MkcolRequest {
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
|
set: PropElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(cal_store))]
|
||||||
|
pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
|
||||||
|
Path((principal, cal_id)): Path<(String, String)>,
|
||||||
|
user: Principal,
|
||||||
|
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||||
|
method: Method,
|
||||||
body: String,
|
body: String,
|
||||||
user: User,
|
) -> Result<Response, Error> {
|
||||||
store: Data<C>,
|
|
||||||
root_span: RootSpan,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let (principal, cal_id) = path.into_inner();
|
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let request = MkcalendarRequest::parse_str(&body)?;
|
let mut request = match method.as_str() {
|
||||||
let request = request.set.prop;
|
"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 {
|
let calendar = Calendar {
|
||||||
id: cal_id.to_owned(),
|
id: cal_id.to_owned(),
|
||||||
principal: principal.to_owned(),
|
principal: principal.to_owned(),
|
||||||
order: request.calendar_order.unwrap_or(0),
|
order: request.calendar_order.unwrap_or(0),
|
||||||
displayname: request.displayname,
|
displayname: request.displayname,
|
||||||
timezone: request.calendar_timezone,
|
timezone_id,
|
||||||
timezone_id: request.calendar_timezone_id,
|
|
||||||
color: request.calendar_color,
|
color: request.calendar_color,
|
||||||
description: request.calendar_description,
|
description: request.calendar_description,
|
||||||
deleted_at: None,
|
deleted_at: None,
|
||||||
synctoken: 0,
|
synctoken: 0,
|
||||||
subscription_url: None,
|
subscription_url: request.source.map(|href| href.href),
|
||||||
push_topic: uuid::Uuid::new_v4().to_string(),
|
push_topic: uuid::Uuid::new_v4().to_string(),
|
||||||
components: request
|
components: request
|
||||||
.supported_calendar_component_set
|
.supported_calendar_component_set
|
||||||
@@ -87,17 +131,9 @@ pub async fn route_mkcalendar<C: CalendarStore>(
|
|||||||
]),
|
]),
|
||||||
};
|
};
|
||||||
|
|
||||||
match store.insert_calendar(calendar).await {
|
cal_store.insert_calendar(calendar).await?;
|
||||||
// The spec says we should return a mkcalendar-response but I don't know what goes into it.
|
// The spec says we don't have to return a response everything was successful
|
||||||
// However, it works without one but breaks on iPadOS when using an empty one :)
|
Ok(StatusCode::CREATED.into_response())
|
||||||
Ok(()) => Ok(HttpResponse::Created()
|
|
||||||
.insert_header(("Cache-Control", "no-cache"))
|
|
||||||
.body("")),
|
|
||||||
Err(err) => {
|
|
||||||
dbg!(err.to_string());
|
|
||||||
Err(err.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -130,4 +166,31 @@ mod tests {
|
|||||||
</CAL:mkcalendar>
|
</CAL:mkcalendar>
|
||||||
"#).unwrap();
|
"#).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_xml_mkcol() {
|
||||||
|
MkcolRequest::parse_str(r#"
|
||||||
|
<?xml version='1.0' encoding='UTF-8' ?>
|
||||||
|
<mkcol xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CARD="urn:ietf:params:xml:ns:carddav">
|
||||||
|
<set>
|
||||||
|
<prop>
|
||||||
|
<resourcetype>
|
||||||
|
<collection />
|
||||||
|
<CAL:calendar />
|
||||||
|
</resourcetype>
|
||||||
|
<displayname>jfs</displayname>
|
||||||
|
<CAL:calendar-description>rggg</CAL:calendar-description>
|
||||||
|
<n0:calendar-color xmlns:n0="http://apple.com/ns/ical/">#FFF8DCFF</n0:calendar-color>
|
||||||
|
<CAL:calendar-timezone-id>Europe/Berlin</CAL:calendar-timezone-id>
|
||||||
|
<CAL:supported-calendar-component-set>
|
||||||
|
<CAL:comp name="VEVENT"/>
|
||||||
|
<CAL:comp name="VTODO"/>
|
||||||
|
<CAL:comp name="VJOURNAL"/>
|
||||||
|
</CAL:supported-calendar-component-set>
|
||||||
|
<CAL:calendar-timezone>BEGIN:VCALENDAR\r\nBEGIN:VTIMEZONE\r\nTZID:Europe/Berlin\r\nLAST-MODIFIED:20240422T053450Z\r\nTZURL:https://www.tzurl.org/zoneinfo/Europe/Berlin\r\nX-LIC-LOCATION:Europe/Berlin\r\nX-PROLEPTIC-TZNAME:LMT\r\nBEGIN:STANDARD\r\nTZNAME:CET\r\nTZOFFSETFROM:+005328\r\nTZOFFSETTO:+0100\r\nDTSTART:18930401T000632\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nTZNAME:CEST\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nDTSTART:19160430T230000\r\nRDATE:19400401T020000\r\nRDATE:19430329T020000\r\nRDATE:19460414T020000\r\nRDATE:19470406T030000\r\nRDATE:19480418T020000\r\nRDATE:19490410T020000\r\nRDATE:19800406T020000\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZNAME:CET\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nDTSTART:19161001T010000\r\nRDATE:19421102T030000\r\nRDATE:19431004T030000\r\nRDATE:19441002T030000\r\nRDATE:19451118T030000\r\nRDATE:19461007T030000\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nTZNAME:CEST\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nDTSTART:19170416T020000\r\nRRULE:FREQ=YEARLY;UNTIL=19180415T010000Z;BYMONTH=4;BYDAY=3MO\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZNAME:CET\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nDTSTART:19170917T030000\r\nRRULE:FREQ=YEARLY;UNTIL=19180916T010000Z;BYMONTH=9;BYDAY=3MO\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nTZNAME:CEST\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nDTSTART:19440403T020000\r\nRRULE:FREQ=YEARLY;UNTIL=19450402T010000Z;BYMONTH=4;BYDAY=1MO\r\nEND:DAYLIGHT\r\nBEGIN:DAYLIGHT\r\nTZNAME:CEMT\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0300\r\nDTSTART:19450524T000000\r\nRDATE:19470511T010000\r\nEND:DAYLIGHT\r\nBEGIN:DAYLIGHT\r\nTZNAME:CEST\r\nTZOFFSETFROM:+0300\r\nTZOFFSETTO:+0200\r\nDTSTART:19450924T030000\r\nRDATE:19470629T030000\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZNAME:CET\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0100\r\nDTSTART:19460101T000000\r\nRDATE:19800101T000000\r\nEND:STANDARD\r\nBEGIN:STANDARD\r\nTZNAME:CET\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nDTSTART:19471005T030000\r\nRRULE:FREQ=YEARLY;UNTIL=19491002T010000Z;BYMONTH=10;BYDAY=1SU\r\nEND:STANDARD\r\nBEGIN:STANDARD\r\nTZNAME:CET\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nDTSTART:19800928T030000\r\nRRULE:FREQ=YEARLY;UNTIL=19950924T010000Z;BYMONTH=9;BYDAY=-1SU\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nTZNAME:CEST\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nDTSTART:19810329T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZNAME:CET\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nDTSTART:19961027T030000\r\nRRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nEND:VCALENDAR\r\n</CAL:calendar-timezone>
|
||||||
|
</prop>
|
||||||
|
</set>
|
||||||
|
</mkcol>
|
||||||
|
"#).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod get;
|
||||||
pub mod mkcalendar;
|
pub mod mkcalendar;
|
||||||
pub mod post;
|
pub mod post;
|
||||||
pub mod report;
|
pub mod report;
|
||||||
|
|||||||
@@ -1,33 +1,32 @@
|
|||||||
use crate::Error;
|
use crate::Error;
|
||||||
|
use crate::calendar::CalendarResourceService;
|
||||||
use crate::calendar::resource::CalendarResource;
|
use crate::calendar::resource::CalendarResource;
|
||||||
use actix_web::http::header;
|
use axum::extract::{Path, State};
|
||||||
use actix_web::web::{Data, Path};
|
use axum::response::{IntoResponse, Response};
|
||||||
use actix_web::{HttpRequest, HttpResponse};
|
use http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||||
use rustical_dav::privileges::UserPrivilege;
|
use rustical_dav::privileges::UserPrivilege;
|
||||||
use rustical_dav::resource::Resource;
|
use rustical_dav::resource::Resource;
|
||||||
use rustical_dav_push::register::PushRegister;
|
use rustical_dav_push::register::PushRegister;
|
||||||
use rustical_store::auth::User;
|
use rustical_store::auth::Principal;
|
||||||
use rustical_store::{CalendarStore, Subscription, SubscriptionStore};
|
use rustical_store::{CalendarStore, Subscription, SubscriptionStore};
|
||||||
use rustical_xml::XmlDocument;
|
use rustical_xml::XmlDocument;
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(store, subscription_store, root_span, req))]
|
#[instrument(skip(resource_service))]
|
||||||
pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
||||||
path: Path<(String, String)>,
|
Path((principal, cal_id)): Path<(String, String)>,
|
||||||
|
user: Principal,
|
||||||
|
State(resource_service): State<CalendarResourceService<C, S>>,
|
||||||
body: String,
|
body: String,
|
||||||
user: User,
|
) -> Result<Response, Error> {
|
||||||
store: Data<C>,
|
|
||||||
subscription_store: Data<S>,
|
|
||||||
root_span: RootSpan,
|
|
||||||
req: HttpRequest,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let (principal, cal_id) = path.into_inner();
|
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let calendar = store.get_calendar(&principal, &cal_id).await?;
|
let calendar = resource_service
|
||||||
|
.cal_store
|
||||||
|
.get_calendar(&principal, &cal_id, false)
|
||||||
|
.await?;
|
||||||
let calendar_resource = CalendarResource {
|
let calendar_resource = CalendarResource {
|
||||||
cal: calendar,
|
cal: calendar,
|
||||||
read_only: true,
|
read_only: true,
|
||||||
@@ -70,15 +69,22 @@ pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
|||||||
.ty,
|
.ty,
|
||||||
auth_secret: request.subscription.web_push_subscription.auth_secret,
|
auth_secret: request.subscription.web_push_subscription.auth_secret,
|
||||||
};
|
};
|
||||||
subscription_store.upsert_subscription(subscription).await?;
|
resource_service
|
||||||
|
.sub_store
|
||||||
|
.upsert_subscription(subscription)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let location = req
|
// TODO: make nicer
|
||||||
.resource_map()
|
let location = format!("/push_subscription/{sub_id}");
|
||||||
.url_for(&req, "subscription", &[sub_id])
|
Ok((
|
||||||
.unwrap();
|
StatusCode::CREATED,
|
||||||
|
HeaderMap::from_iter([
|
||||||
Ok(HttpResponse::Created()
|
(header::LOCATION, HeaderValue::from_str(&location).unwrap()),
|
||||||
.append_header((header::LOCATION, location.to_string()))
|
(
|
||||||
.append_header((header::EXPIRES, expires.to_rfc2822()))
|
header::EXPIRES,
|
||||||
.finish())
|
HeaderValue::from_str(&expires.to_rfc2822()).unwrap(),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.into_response())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,7 @@
|
|||||||
use super::ReportPropName;
|
use crate::{Error, calendar_object::CalendarObjectPropWrapperName};
|
||||||
use crate::{
|
use rustical_dav::xml::PropfindType;
|
||||||
Error,
|
use rustical_ical::CalendarObject;
|
||||||
calendar_object::resource::{CalendarObjectPropWrapper, CalendarObjectResource},
|
use rustical_store::CalendarStore;
|
||||||
};
|
|
||||||
use actix_web::{
|
|
||||||
HttpRequest,
|
|
||||||
dev::{Path, ResourceDef},
|
|
||||||
http::StatusCode,
|
|
||||||
};
|
|
||||||
use rustical_dav::{
|
|
||||||
resource::Resource,
|
|
||||||
xml::{MultistatusElement, PropfindType, multistatus::ResponseElement},
|
|
||||||
};
|
|
||||||
use rustical_store::{CalendarObject, CalendarStore, auth::User};
|
|
||||||
use rustical_xml::XmlDeserialize;
|
use rustical_xml::XmlDeserialize;
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||||
@@ -20,7 +9,7 @@ use rustical_xml::XmlDeserialize;
|
|||||||
// <!ELEMENT calendar-query ((DAV:allprop | DAV:propname | DAV:prop)?, href+)>
|
// <!ELEMENT calendar-query ((DAV:allprop | DAV:propname | DAV:prop)?, href+)>
|
||||||
pub(crate) struct CalendarMultigetRequest {
|
pub(crate) struct CalendarMultigetRequest {
|
||||||
#[xml(ty = "untagged")]
|
#[xml(ty = "untagged")]
|
||||||
pub(crate) prop: PropfindType<ReportPropName>,
|
pub(crate) prop: PropfindType<CalendarObjectPropWrapperName>,
|
||||||
#[xml(flatten)]
|
#[xml(flatten)]
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
pub(crate) href: Vec<String>,
|
pub(crate) href: Vec<String>,
|
||||||
@@ -33,65 +22,27 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
|
|||||||
cal_id: &str,
|
cal_id: &str,
|
||||||
store: &C,
|
store: &C,
|
||||||
) -> Result<(Vec<CalendarObject>, Vec<String>), Error> {
|
) -> Result<(Vec<CalendarObject>, Vec<String>), Error> {
|
||||||
let resource_def = ResourceDef::prefix(path).join(&ResourceDef::new("/{object_id}.ics"));
|
|
||||||
|
|
||||||
let mut result = vec![];
|
let mut result = vec![];
|
||||||
let mut not_found = vec![];
|
let mut not_found = vec![];
|
||||||
|
|
||||||
for href in &cal_query.href {
|
for href in &cal_query.href {
|
||||||
let mut path = Path::new(href.as_str());
|
if let Some(filename) = href.strip_prefix(path) {
|
||||||
if !resource_def.capture_match_info(&mut path) {
|
let filename = filename.trim_start_matches("/");
|
||||||
|
if let Some(object_id) = filename.strip_suffix(".ics") {
|
||||||
|
match store.get_object(principal, cal_id, object_id, false).await {
|
||||||
|
Ok(object) => result.push(object),
|
||||||
|
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
|
||||||
|
Err(err) => return Err(err.into()),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
not_found.push(href.to_owned());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
not_found.push(href.to_owned());
|
not_found.push(href.to_owned());
|
||||||
continue;
|
continue;
|
||||||
};
|
}
|
||||||
let object_id = path.get("object_id").unwrap();
|
|
||||||
match store.get_object(principal, cal_id, object_id).await {
|
|
||||||
Ok(object) => result.push(object),
|
|
||||||
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
|
|
||||||
Err(err) => return Err(err.into()),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok((result, not_found))
|
Ok((result, not_found))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle_calendar_multiget<C: CalendarStore>(
|
|
||||||
cal_multiget: &CalendarMultigetRequest,
|
|
||||||
props: &[&str],
|
|
||||||
req: HttpRequest,
|
|
||||||
user: &User,
|
|
||||||
principal: &str,
|
|
||||||
cal_id: &str,
|
|
||||||
cal_store: &C,
|
|
||||||
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
|
|
||||||
let (objects, not_found) =
|
|
||||||
get_objects_calendar_multiget(cal_multiget, req.path(), principal, cal_id, cal_store)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut responses = Vec::new();
|
|
||||||
for object in objects {
|
|
||||||
let path = format!("{}/{}.ics", req.path(), object.get_id());
|
|
||||||
responses.push(
|
|
||||||
CalendarObjectResource {
|
|
||||||
object,
|
|
||||||
principal: principal.to_owned(),
|
|
||||||
}
|
|
||||||
.propfind(&path, props, user, req.resource_map())?,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let not_found_responses = not_found
|
|
||||||
.into_iter()
|
|
||||||
.map(|path| ResponseElement {
|
|
||||||
href: path,
|
|
||||||
status: Some(StatusCode::NOT_FOUND),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
Ok(MultistatusElement {
|
|
||||||
responses,
|
|
||||||
member_responses: not_found_responses,
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,21 +1,10 @@
|
|||||||
use actix_web::HttpRequest;
|
use crate::{Error, calendar_object::CalendarObjectPropWrapperName};
|
||||||
use rustical_dav::{
|
use rustical_dav::xml::PropfindType;
|
||||||
resource::Resource,
|
use rustical_ical::{CalendarObject, UtcDateTime};
|
||||||
xml::{MultistatusElement, PropfindType},
|
use rustical_store::{CalendarStore, calendar_store::CalendarQuery};
|
||||||
};
|
|
||||||
use rustical_store::{
|
|
||||||
CalendarObject, CalendarStore, auth::User, calendar::UtcDateTime, calendar_store::CalendarQuery,
|
|
||||||
};
|
|
||||||
use rustical_xml::XmlDeserialize;
|
use rustical_xml::XmlDeserialize;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
use crate::{
|
|
||||||
Error,
|
|
||||||
calendar_object::resource::{CalendarObjectPropWrapper, CalendarObjectResource},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::ReportPropName;
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub(crate) struct TimeRangeElement {
|
pub(crate) struct TimeRangeElement {
|
||||||
@@ -27,6 +16,7 @@ pub(crate) struct TimeRangeElement {
|
|||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.3
|
||||||
struct ParamFilterElement {
|
struct ParamFilterElement {
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
is_not_defined: Option<()>,
|
is_not_defined: Option<()>,
|
||||||
@@ -43,11 +33,13 @@ struct TextMatchElement {
|
|||||||
#[xml(ty = "attr")]
|
#[xml(ty = "attr")]
|
||||||
collation: String,
|
collation: String,
|
||||||
#[xml(ty = "attr")]
|
#[xml(ty = "attr")]
|
||||||
negate_collation: String,
|
// "yes" or "no", default: "no"
|
||||||
|
negate_condition: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.2
|
||||||
pub(crate) struct PropFilterElement {
|
pub(crate) struct PropFilterElement {
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
is_not_defined: Option<()>,
|
is_not_defined: Option<()>,
|
||||||
@@ -57,6 +49,9 @@ pub(crate) struct PropFilterElement {
|
|||||||
text_match: Option<TextMatchElement>,
|
text_match: Option<TextMatchElement>,
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
|
||||||
param_filter: Vec<ParamFilterElement>,
|
param_filter: Vec<ParamFilterElement>,
|
||||||
|
|
||||||
|
#[xml(ty = "attr")]
|
||||||
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||||
@@ -72,7 +67,7 @@ pub(crate) struct CompFilterElement {
|
|||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
|
||||||
pub(crate) comp_filter: Vec<CompFilterElement>,
|
pub(crate) comp_filter: Vec<CompFilterElement>,
|
||||||
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", ty = "attr")]
|
#[xml(ty = "attr")]
|
||||||
pub(crate) name: String,
|
pub(crate) name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +176,7 @@ impl From<&FilterElement> for CalendarQuery {
|
|||||||
// <!ELEMENT calendar-query ((DAV:allprop | DAV:propname | DAV:prop)?, filter, timezone?)>
|
// <!ELEMENT calendar-query ((DAV:allprop | DAV:propname | DAV:prop)?, filter, timezone?)>
|
||||||
pub struct CalendarQueryRequest {
|
pub struct CalendarQueryRequest {
|
||||||
#[xml(ty = "untagged")]
|
#[xml(ty = "untagged")]
|
||||||
pub prop: PropfindType<ReportPropName>,
|
pub prop: PropfindType<CalendarObjectPropWrapperName>,
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
pub(crate) filter: Option<FilterElement>,
|
pub(crate) filter: Option<FilterElement>,
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
@@ -215,35 +210,101 @@ pub async fn get_objects_calendar_query<C: CalendarStore>(
|
|||||||
Ok(objects)
|
Ok(objects)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle_calendar_query<C: CalendarStore>(
|
#[cfg(test)]
|
||||||
cal_query: &CalendarQueryRequest,
|
mod tests {
|
||||||
props: &[&str],
|
use rustical_dav::xml::PropElement;
|
||||||
req: HttpRequest,
|
use rustical_xml::XmlDocument;
|
||||||
user: &User,
|
|
||||||
principal: &str,
|
|
||||||
cal_id: &str,
|
|
||||||
cal_store: &C,
|
|
||||||
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
|
|
||||||
let objects = get_objects_calendar_query(cal_query, principal, cal_id, cal_store).await?;
|
|
||||||
|
|
||||||
let mut responses = Vec::new();
|
use crate::{
|
||||||
for object in objects {
|
calendar::methods::report::{
|
||||||
let path = format!(
|
ReportRequest,
|
||||||
"{}/{}.ics",
|
calendar_query::{
|
||||||
req.path().trim_end_matches('/'),
|
CalendarQueryRequest, CompFilterElement, FilterElement, ParamFilterElement,
|
||||||
object.get_id()
|
PropFilterElement, TextMatchElement,
|
||||||
);
|
},
|
||||||
responses.push(
|
},
|
||||||
CalendarObjectResource {
|
calendar_object::{CalendarObjectPropName, CalendarObjectPropWrapperName},
|
||||||
object,
|
};
|
||||||
principal: principal.to_owned(),
|
|
||||||
|
#[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
|
||||||
}
|
}
|
||||||
.propfind(&path, props, user, req.resource_map())?,
|
)
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(MultistatusElement {
|
|
||||||
responses,
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,27 @@
|
|||||||
use crate::Error;
|
use crate::{
|
||||||
use actix_web::{
|
CalDavPrincipalUri, Error,
|
||||||
HttpRequest, Responder,
|
calendar::CalendarResourceService,
|
||||||
web::{Data, Path},
|
calendar_object::{
|
||||||
|
CalendarObjectPropWrapper, CalendarObjectPropWrapperName, resource::CalendarObjectResource,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use calendar_multiget::{CalendarMultigetRequest, handle_calendar_multiget};
|
use axum::{
|
||||||
use calendar_query::{CalendarQueryRequest, handle_calendar_query};
|
Extension,
|
||||||
use rustical_dav::xml::{
|
extract::{OriginalUri, Path, State},
|
||||||
PropElement, PropfindType, Propname, sync_collection::SyncCollectionRequest,
|
response::IntoResponse,
|
||||||
};
|
};
|
||||||
use rustical_store::{CalendarStore, auth::User};
|
use calendar_multiget::{CalendarMultigetRequest, get_objects_calendar_multiget};
|
||||||
|
use calendar_query::{CalendarQueryRequest, get_objects_calendar_query};
|
||||||
|
use http::StatusCode;
|
||||||
|
use rustical_dav::{
|
||||||
|
resource::{PrincipalUri, Resource},
|
||||||
|
xml::{
|
||||||
|
MultistatusElement, PropfindType, multistatus::ResponseElement,
|
||||||
|
sync_collection::SyncCollectionRequest,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use rustical_ical::CalendarObject;
|
||||||
|
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
|
||||||
use rustical_xml::{XmlDeserialize, XmlDocument};
|
use rustical_xml::{XmlDeserialize, XmlDocument};
|
||||||
use sync_collection::handle_sync_collection;
|
use sync_collection::handle_sync_collection;
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
@@ -17,34 +30,6 @@ mod calendar_multiget;
|
|||||||
mod calendar_query;
|
mod calendar_query;
|
||||||
mod sync_collection;
|
mod sync_collection;
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
|
||||||
pub(crate) struct ExpandElement {
|
|
||||||
#[xml(ty = "attr")]
|
|
||||||
start: String,
|
|
||||||
#[xml(ty = "attr")]
|
|
||||||
end: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
|
||||||
pub struct CalendarData {
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
comp: Option<()>,
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
expand: Option<ExpandElement>,
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
limit_recurrence_set: Option<()>,
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
limit_freebusy_set: Option<()>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
|
||||||
pub enum ReportPropName {
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
CalendarData(CalendarData),
|
|
||||||
#[xml(other)]
|
|
||||||
Propname(Propname),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlDocument, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, XmlDocument, Clone, Debug, PartialEq)]
|
||||||
pub(crate) enum ReportRequest {
|
pub(crate) enum ReportRequest {
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
@@ -52,44 +37,65 @@ pub(crate) enum ReportRequest {
|
|||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
CalendarQuery(CalendarQueryRequest),
|
CalendarQuery(CalendarQueryRequest),
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
SyncCollection(SyncCollectionRequest<ReportPropName>),
|
SyncCollection(SyncCollectionRequest<CalendarObjectPropWrapperName>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ReportRequest {
|
impl ReportRequest {
|
||||||
fn props(&self) -> Vec<&str> {
|
fn props(&self) -> &PropfindType<CalendarObjectPropWrapperName> {
|
||||||
let prop_element = match self {
|
match &self {
|
||||||
ReportRequest::CalendarMultiget(CalendarMultigetRequest { prop, .. }) => prop,
|
ReportRequest::CalendarMultiget(CalendarMultigetRequest { prop, .. }) => prop,
|
||||||
ReportRequest::CalendarQuery(CalendarQueryRequest { prop, .. }) => prop,
|
ReportRequest::CalendarQuery(CalendarQueryRequest { prop, .. }) => prop,
|
||||||
ReportRequest::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
|
ReportRequest::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
|
||||||
};
|
|
||||||
|
|
||||||
match prop_element {
|
|
||||||
PropfindType::Allprop => {
|
|
||||||
vec!["allprop"]
|
|
||||||
}
|
|
||||||
PropfindType::Propname => {
|
|
||||||
vec!["propname"]
|
|
||||||
}
|
|
||||||
PropfindType::Prop(PropElement(prop_tags)) => prop_tags
|
|
||||||
.iter()
|
|
||||||
.map(|propname| match propname {
|
|
||||||
ReportPropName::Propname(propname) => propname.0.as_str(),
|
|
||||||
ReportPropName::CalendarData(_) => "calendar-data",
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(skip(req, cal_store))]
|
fn objects_response(
|
||||||
pub async fn route_report_calendar<C: CalendarStore>(
|
objects: Vec<CalendarObject>,
|
||||||
path: Path<(String, String)>,
|
not_found: Vec<String>,
|
||||||
|
path: &str,
|
||||||
|
principal: &str,
|
||||||
|
puri: &impl PrincipalUri,
|
||||||
|
user: &Principal,
|
||||||
|
prop: &PropfindType<CalendarObjectPropWrapperName>,
|
||||||
|
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
|
||||||
|
let mut responses = Vec::new();
|
||||||
|
for object in objects {
|
||||||
|
let path = format!("{}/{}.ics", path, object.get_id());
|
||||||
|
responses.push(
|
||||||
|
CalendarObjectResource {
|
||||||
|
object,
|
||||||
|
principal: principal.to_owned(),
|
||||||
|
}
|
||||||
|
.propfind(&path, prop, None, puri, user)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let not_found_responses = not_found
|
||||||
|
.into_iter()
|
||||||
|
.map(|path| ResponseElement {
|
||||||
|
href: path,
|
||||||
|
status: Some(StatusCode::NOT_FOUND),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(MultistatusElement {
|
||||||
|
responses,
|
||||||
|
member_responses: not_found_responses,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(cal_store))]
|
||||||
|
pub async fn route_report_calendar<C: CalendarStore, S: SubscriptionStore>(
|
||||||
|
Path((principal, cal_id)): Path<(String, String)>,
|
||||||
|
user: Principal,
|
||||||
|
Extension(puri): Extension<CalDavPrincipalUri>,
|
||||||
|
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||||
|
OriginalUri(uri): OriginalUri,
|
||||||
body: String,
|
body: String,
|
||||||
user: User,
|
) -> Result<impl IntoResponse, Error> {
|
||||||
req: HttpRequest,
|
|
||||||
cal_store: Data<C>,
|
|
||||||
) -> Result<impl Responder, Error> {
|
|
||||||
let (principal, cal_id) = path.into_inner();
|
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
@@ -99,34 +105,35 @@ pub async fn route_report_calendar<C: CalendarStore>(
|
|||||||
|
|
||||||
Ok(match &request {
|
Ok(match &request {
|
||||||
ReportRequest::CalendarQuery(cal_query) => {
|
ReportRequest::CalendarQuery(cal_query) => {
|
||||||
handle_calendar_query(
|
let objects =
|
||||||
cal_query,
|
get_objects_calendar_query(cal_query, &principal, &cal_id, cal_store.as_ref())
|
||||||
&props,
|
.await?;
|
||||||
req,
|
objects_response(objects, vec![], uri.path(), &principal, &puri, &user, props)?
|
||||||
&user,
|
|
||||||
&principal,
|
|
||||||
&cal_id,
|
|
||||||
cal_store.as_ref(),
|
|
||||||
)
|
|
||||||
.await?
|
|
||||||
}
|
}
|
||||||
ReportRequest::CalendarMultiget(cal_multiget) => {
|
ReportRequest::CalendarMultiget(cal_multiget) => {
|
||||||
handle_calendar_multiget(
|
let (objects, not_found) = get_objects_calendar_multiget(
|
||||||
cal_multiget,
|
cal_multiget,
|
||||||
&props,
|
uri.path(),
|
||||||
req,
|
|
||||||
&user,
|
|
||||||
&principal,
|
&principal,
|
||||||
&cal_id,
|
&cal_id,
|
||||||
cal_store.as_ref(),
|
cal_store.as_ref(),
|
||||||
)
|
)
|
||||||
.await?
|
.await?;
|
||||||
|
objects_response(
|
||||||
|
objects,
|
||||||
|
not_found,
|
||||||
|
uri.path(),
|
||||||
|
&principal,
|
||||||
|
&puri,
|
||||||
|
&user,
|
||||||
|
props,
|
||||||
|
)?
|
||||||
}
|
}
|
||||||
ReportRequest::SyncCollection(sync_collection) => {
|
ReportRequest::SyncCollection(sync_collection) => {
|
||||||
handle_sync_collection(
|
handle_sync_collection(
|
||||||
sync_collection,
|
sync_collection,
|
||||||
&props,
|
uri.path(),
|
||||||
req,
|
&puri,
|
||||||
&user,
|
&user,
|
||||||
&principal,
|
&principal,
|
||||||
&cal_id,
|
&cal_id,
|
||||||
@@ -140,10 +147,11 @@ pub async fn route_report_calendar<C: CalendarStore>(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::calendar_object::{CalendarData, CalendarObjectPropName, ExpandElement};
|
||||||
use calendar_query::{CompFilterElement, FilterElement, TimeRangeElement};
|
use calendar_query::{CompFilterElement, FilterElement, TimeRangeElement};
|
||||||
use rustical_dav::xml::{PropElement, PropfindType, Propname};
|
use rustical_dav::{extensions::CommonPropertiesPropName, xml::PropElement};
|
||||||
use rustical_store::calendar::UtcDateTime;
|
use rustical_ical::UtcDateTime;
|
||||||
use rustical_xml::ValueDeserialize;
|
use rustical_xml::{NamespaceOwned, ValueDeserialize};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_xml_calendar_data() {
|
fn test_xml_calendar_data() {
|
||||||
@@ -152,7 +160,6 @@ mod tests {
|
|||||||
<calendar-multiget xmlns="urn:ietf:params:xml:ns:caldav" xmlns:D="DAV:">
|
<calendar-multiget xmlns="urn:ietf:params:xml:ns:caldav" xmlns:D="DAV:">
|
||||||
<D:prop>
|
<D:prop>
|
||||||
<D:getetag/>
|
<D:getetag/>
|
||||||
<D:displayname/>
|
|
||||||
<calendar-data>
|
<calendar-data>
|
||||||
<expand start="20250426T220000Z" end="20250503T220000Z"/>
|
<expand start="20250426T220000Z" end="20250503T220000Z"/>
|
||||||
</calendar-data>
|
</calendar-data>
|
||||||
@@ -165,10 +172,14 @@ mod tests {
|
|||||||
report_request,
|
report_request,
|
||||||
ReportRequest::CalendarMultiget(CalendarMultigetRequest {
|
ReportRequest::CalendarMultiget(CalendarMultigetRequest {
|
||||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
||||||
ReportPropName::Propname(Propname("getetag".to_owned())),
|
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::Getetag),
|
||||||
ReportPropName::Propname(Propname("displayname".to_owned())),
|
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::CalendarData(
|
||||||
ReportPropName::CalendarData(CalendarData { comp: None, expand: Some(ExpandElement { start: "20250426T220000Z".to_owned(), end: "20250503T220000Z".to_owned() }), limit_recurrence_set: None, limit_freebusy_set: None })
|
CalendarData { comp: None, expand: Some(ExpandElement {
|
||||||
])),
|
start: <UtcDateTime as ValueDeserialize>::deserialize("20250426T220000Z").unwrap(),
|
||||||
|
end: <UtcDateTime as ValueDeserialize>::deserialize("20250503T220000Z").unwrap(),
|
||||||
|
}), limit_recurrence_set: None, limit_freebusy_set: None }
|
||||||
|
)),
|
||||||
|
], vec![])),
|
||||||
href: vec![
|
href: vec![
|
||||||
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
||||||
]
|
]
|
||||||
@@ -198,9 +209,12 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
report_request,
|
report_request,
|
||||||
ReportRequest::CalendarQuery(CalendarQueryRequest {
|
ReportRequest::CalendarQuery(CalendarQueryRequest {
|
||||||
prop: PropfindType::Prop(PropElement(vec![ReportPropName::Propname(Propname(
|
prop: rustical_dav::xml::PropfindType::Prop(PropElement(
|
||||||
"getetag".to_owned()
|
vec![CalendarObjectPropWrapperName::CalendarObject(
|
||||||
))])),
|
CalendarObjectPropName::Getetag
|
||||||
|
),],
|
||||||
|
vec![]
|
||||||
|
)),
|
||||||
filter: Some(FilterElement {
|
filter: Some(FilterElement {
|
||||||
comp_filter: CompFilterElement {
|
comp_filter: CompFilterElement {
|
||||||
is_not_defined: None,
|
is_not_defined: None,
|
||||||
@@ -238,6 +252,7 @@ mod tests {
|
|||||||
<D:prop>
|
<D:prop>
|
||||||
<D:getetag/>
|
<D:getetag/>
|
||||||
<D:displayname/>
|
<D:displayname/>
|
||||||
|
<D:invalid-prop/>
|
||||||
</D:prop>
|
</D:prop>
|
||||||
<D:href>/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b</D:href>
|
<D:href>/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b</D:href>
|
||||||
</calendar-multiget>
|
</calendar-multiget>
|
||||||
@@ -247,9 +262,9 @@ mod tests {
|
|||||||
report_request,
|
report_request,
|
||||||
ReportRequest::CalendarMultiget(CalendarMultigetRequest {
|
ReportRequest::CalendarMultiget(CalendarMultigetRequest {
|
||||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
||||||
ReportPropName::Propname(Propname("getetag".to_owned())),
|
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::Getetag),
|
||||||
ReportPropName::Propname(Propname("displayname".to_owned()))
|
CalendarObjectPropWrapperName::Common(CommonPropertiesPropName::Displayname),
|
||||||
])),
|
], vec![(Some(NamespaceOwned(Vec::from("DAV:"))), "invalid-prop".to_string())])),
|
||||||
href: vec![
|
href: vec![
|
||||||
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,26 +1,27 @@
|
|||||||
use super::ReportPropName;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Error,
|
Error,
|
||||||
calendar_object::resource::{CalendarObjectPropWrapper, CalendarObjectResource},
|
calendar_object::{
|
||||||
|
CalendarObjectPropWrapper, CalendarObjectPropWrapperName, resource::CalendarObjectResource,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use actix_web::{HttpRequest, http::StatusCode};
|
use http::StatusCode;
|
||||||
use rustical_dav::{
|
use rustical_dav::{
|
||||||
resource::Resource,
|
resource::{PrincipalUri, Resource},
|
||||||
xml::{
|
xml::{
|
||||||
MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest,
|
MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use rustical_store::{
|
use rustical_store::{
|
||||||
CalendarStore,
|
CalendarStore,
|
||||||
auth::User,
|
auth::Principal,
|
||||||
synctoken::{format_synctoken, parse_synctoken},
|
synctoken::{format_synctoken, parse_synctoken},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn handle_sync_collection<C: CalendarStore>(
|
pub async fn handle_sync_collection<C: CalendarStore>(
|
||||||
sync_collection: &SyncCollectionRequest<ReportPropName>,
|
sync_collection: &SyncCollectionRequest<CalendarObjectPropWrapperName>,
|
||||||
props: &[&str],
|
path: &str,
|
||||||
req: HttpRequest,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
principal: &str,
|
principal: &str,
|
||||||
cal_id: &str,
|
cal_id: &str,
|
||||||
cal_store: &C,
|
cal_store: &C,
|
||||||
@@ -32,22 +33,18 @@ pub async fn handle_sync_collection<C: CalendarStore>(
|
|||||||
|
|
||||||
let mut responses = Vec::new();
|
let mut responses = Vec::new();
|
||||||
for object in new_objects {
|
for object in new_objects {
|
||||||
let path = format!(
|
let path = format!("{}/{}.ics", path, object.get_id());
|
||||||
"{}/{}.ics",
|
|
||||||
req.path().trim_end_matches('/'),
|
|
||||||
object.get_id()
|
|
||||||
);
|
|
||||||
responses.push(
|
responses.push(
|
||||||
CalendarObjectResource {
|
CalendarObjectResource {
|
||||||
object,
|
object,
|
||||||
principal: principal.to_owned(),
|
principal: principal.to_owned(),
|
||||||
}
|
}
|
||||||
.propfind(&path, props, user, req.resource_map())?,
|
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
for object_id in deleted_objects {
|
for object_id in deleted_objects {
|
||||||
let path = format!("{}/{}.ics", req.path().trim_end_matches('/'), object_id);
|
let path = format!("{path}/{object_id}.ics");
|
||||||
responses.push(ResponseElement {
|
responses.push(ResponseElement {
|
||||||
href: path,
|
href: path,
|
||||||
status: Some(StatusCode::NOT_FOUND),
|
status: Some(StatusCode::NOT_FOUND),
|
||||||
|
|||||||
@@ -1,3 +1,9 @@
|
|||||||
pub mod methods;
|
pub mod methods;
|
||||||
pub mod prop;
|
pub mod prop;
|
||||||
pub mod resource;
|
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 derive_more::derive::{From, Into};
|
||||||
use rustical_store::calendar::CalendarObjectType;
|
use rustical_ical::CalendarObjectType;
|
||||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||||
|
use strum_macros::VariantArray;
|
||||||
|
|
||||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, From, Into)]
|
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, From, Into)]
|
||||||
pub struct SupportedCalendarComponent {
|
pub struct SupportedCalendarComponent {
|
||||||
@@ -58,39 +59,12 @@ pub struct SupportedCalendarData {
|
|||||||
calendar_data: CalendarData,
|
calendar_data: CalendarData,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
|
||||||
pub enum ReportMethod {
|
pub enum ReportMethod {
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
CalendarQuery,
|
CalendarQuery,
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
CalendarMultiget,
|
CalendarMultiget,
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
SyncCollection,
|
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,39 +1,26 @@
|
|||||||
use super::methods::mkcalendar::route_mkcalendar;
|
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData};
|
||||||
use super::methods::post::route_post;
|
|
||||||
use super::methods::report::route_report_calendar;
|
|
||||||
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData, SupportedReportSet};
|
|
||||||
use crate::Error;
|
use crate::Error;
|
||||||
use crate::calendar_object::resource::CalendarObjectResource;
|
use crate::calendar::prop::ReportMethod;
|
||||||
use crate::principal::PrincipalResource;
|
|
||||||
use actix_web::dev::ResourceMap;
|
|
||||||
use actix_web::http::Method;
|
|
||||||
use actix_web::web;
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use derive_more::derive::{From, Into};
|
use derive_more::derive::{From, Into};
|
||||||
|
use ical::IcalParser;
|
||||||
use rustical_dav::extensions::{
|
use rustical_dav::extensions::{
|
||||||
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
|
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
|
||||||
};
|
};
|
||||||
use rustical_dav::privileges::UserPrivilegeSet;
|
use rustical_dav::privileges::UserPrivilegeSet;
|
||||||
use rustical_dav::resource::{Resource, ResourceService};
|
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner, SupportedReportSet};
|
||||||
use rustical_dav_push::{DavPushExtension, DavPushExtensionProp};
|
use rustical_dav_push::{DavPushExtension, DavPushExtensionProp};
|
||||||
use rustical_store::auth::User;
|
use rustical_ical::CalDateTime;
|
||||||
use rustical_store::calendar::CalDateTime;
|
use rustical_store::Calendar;
|
||||||
use rustical_store::{Calendar, CalendarStore, SubscriptionStore};
|
use rustical_store::auth::Principal;
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants};
|
use rustical_xml::{EnumVariants, PropName};
|
||||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||||
use std::marker::PhantomData;
|
use serde::Deserialize;
|
||||||
use std::str::FromStr;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
#[xml(unit_variants_ident = "CalendarPropName")]
|
#[xml(unit_variants_ident = "CalendarPropName")]
|
||||||
pub enum CalendarProp {
|
pub enum CalendarProp {
|
||||||
// WebDAV (RFC 2518)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
|
||||||
Displayname(Option<String>),
|
|
||||||
|
|
||||||
// CalDAV (RFC 4791)
|
// CalDAV (RFC 4791)
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_ICAL")]
|
#[xml(ns = "rustical_dav::namespace::NS_ICAL")]
|
||||||
CalendarColor(Option<String>),
|
CalendarColor(Option<String>),
|
||||||
@@ -48,15 +35,15 @@ pub enum CalendarProp {
|
|||||||
CalendarTimezoneId(Option<String>),
|
CalendarTimezoneId(Option<String>),
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_ICAL")]
|
#[xml(ns = "rustical_dav::namespace::NS_ICAL")]
|
||||||
CalendarOrder(Option<i64>),
|
CalendarOrder(Option<i64>),
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
SupportedCalendarComponentSet(SupportedCalendarComponentSet),
|
SupportedCalendarComponentSet(SupportedCalendarComponentSet),
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
||||||
SupportedCalendarData(SupportedCalendarData),
|
SupportedCalendarData(SupportedCalendarData),
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
MaxResourceSize(i64),
|
MaxResourceSize(i64),
|
||||||
#[xml(skip_deserializing)]
|
#[xml(skip_deserializing)]
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
SupportedReportSet(SupportedReportSet),
|
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALENDARSERVER")]
|
#[xml(ns = "rustical_dav::namespace::NS_CALENDARSERVER")]
|
||||||
Source(Option<HrefElement>),
|
Source(Option<HrefElement>),
|
||||||
#[xml(skip_deserializing)]
|
#[xml(skip_deserializing)]
|
||||||
@@ -67,7 +54,7 @@ pub enum CalendarProp {
|
|||||||
MaxDateTime(String),
|
MaxDateTime(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
#[xml(unit_variants_ident = "CalendarPropWrapperName", untagged)]
|
#[xml(unit_variants_ident = "CalendarPropWrapperName", untagged)]
|
||||||
pub enum CalendarPropWrapper {
|
pub enum CalendarPropWrapper {
|
||||||
Calendar(CalendarProp),
|
Calendar(CalendarProp),
|
||||||
@@ -76,12 +63,18 @@ pub enum CalendarPropWrapper {
|
|||||||
Common(CommonPropertiesProp),
|
Common(CommonPropertiesProp),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, From, Into)]
|
#[derive(Clone, Debug, From, Into, Deserialize)]
|
||||||
pub struct CalendarResource {
|
pub struct CalendarResource {
|
||||||
pub cal: Calendar,
|
pub cal: Calendar,
|
||||||
pub read_only: bool,
|
pub read_only: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ResourceName for CalendarResource {
|
||||||
|
fn get_name(&self) -> String {
|
||||||
|
self.cal.id.to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<CalendarResource> for Calendar {
|
impl From<CalendarResource> for Calendar {
|
||||||
fn from(value: CalendarResource) -> Self {
|
fn from(value: CalendarResource) -> Self {
|
||||||
value.cal
|
value.cal
|
||||||
@@ -100,14 +93,14 @@ impl DavPushExtension for CalendarResource {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommonPropertiesExtension for CalendarResource {
|
|
||||||
type PrincipalResource = PrincipalResource;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resource for CalendarResource {
|
impl Resource for CalendarResource {
|
||||||
type Prop = CalendarPropWrapper;
|
type Prop = CalendarPropWrapper;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Principal = User;
|
type Principal = Principal;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
fn get_resourcetype(&self) -> Resourcetype {
|
||||||
if self.cal.subscription_url.is_none() {
|
if self.cal.subscription_url.is_none() {
|
||||||
@@ -128,15 +121,12 @@ impl Resource for CalendarResource {
|
|||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
prop: &CalendarPropWrapperName,
|
prop: &CalendarPropWrapperName,
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
) -> Result<Self::Prop, Self::Error> {
|
||||||
Ok(match prop {
|
Ok(match prop {
|
||||||
CalendarPropWrapperName::Calendar(prop) => CalendarPropWrapper::Calendar(match prop {
|
CalendarPropWrapperName::Calendar(prop) => CalendarPropWrapper::Calendar(match prop {
|
||||||
CalendarPropName::Displayname => {
|
|
||||||
CalendarProp::Displayname(self.cal.displayname.clone())
|
|
||||||
}
|
|
||||||
CalendarPropName::CalendarColor => {
|
CalendarPropName::CalendarColor => {
|
||||||
CalendarProp::CalendarColor(self.cal.color.clone())
|
CalendarProp::CalendarColor(self.cal.color.clone())
|
||||||
}
|
}
|
||||||
@@ -144,7 +134,9 @@ impl Resource for CalendarResource {
|
|||||||
CalendarProp::CalendarDescription(self.cal.description.clone())
|
CalendarProp::CalendarDescription(self.cal.description.clone())
|
||||||
}
|
}
|
||||||
CalendarPropName::CalendarTimezone => {
|
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
|
// chrono_tz uses the IANA database
|
||||||
CalendarPropName::TimezoneServiceSet => CalendarProp::TimezoneServiceSet(
|
CalendarPropName::TimezoneServiceSet => CalendarProp::TimezoneServiceSet(
|
||||||
@@ -164,16 +156,16 @@ impl Resource for CalendarResource {
|
|||||||
}
|
}
|
||||||
CalendarPropName::MaxResourceSize => CalendarProp::MaxResourceSize(10000000),
|
CalendarPropName::MaxResourceSize => CalendarProp::MaxResourceSize(10000000),
|
||||||
CalendarPropName::SupportedReportSet => {
|
CalendarPropName::SupportedReportSet => {
|
||||||
CalendarProp::SupportedReportSet(SupportedReportSet::default())
|
CalendarProp::SupportedReportSet(SupportedReportSet::all())
|
||||||
}
|
}
|
||||||
CalendarPropName::Source => CalendarProp::Source(
|
CalendarPropName::Source => CalendarProp::Source(
|
||||||
self.cal.subscription_url.to_owned().map(HrefElement::from),
|
self.cal.subscription_url.to_owned().map(HrefElement::from),
|
||||||
),
|
),
|
||||||
CalendarPropName::MinDateTime => {
|
CalendarPropName::MinDateTime => {
|
||||||
CalendarProp::MinDateTime(CalDateTime::Utc(DateTime::<Utc>::MIN_UTC).format())
|
CalendarProp::MinDateTime(CalDateTime::from(DateTime::<Utc>::MIN_UTC).format())
|
||||||
}
|
}
|
||||||
CalendarPropName::MaxDateTime => {
|
CalendarPropName::MaxDateTime => {
|
||||||
CalendarProp::MaxDateTime(CalDateTime::Utc(DateTime::<Utc>::MAX_UTC).format())
|
CalendarProp::MaxDateTime(CalDateTime::from(DateTime::<Utc>::MAX_UTC).format())
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
CalendarPropWrapperName::SyncToken(prop) => {
|
CalendarPropWrapperName::SyncToken(prop) => {
|
||||||
@@ -183,7 +175,7 @@ impl Resource for CalendarResource {
|
|||||||
CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?)
|
CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?)
|
||||||
}
|
}
|
||||||
CalendarPropWrapperName::Common(prop) => CalendarPropWrapper::Common(
|
CalendarPropWrapperName::Common(prop) => CalendarPropWrapper::Common(
|
||||||
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?,
|
CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -194,10 +186,6 @@ impl Resource for CalendarResource {
|
|||||||
}
|
}
|
||||||
match prop {
|
match prop {
|
||||||
CalendarPropWrapper::Calendar(prop) => match prop {
|
CalendarPropWrapper::Calendar(prop) => match prop {
|
||||||
CalendarProp::Displayname(displayname) => {
|
|
||||||
self.cal.displayname = displayname;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
CalendarProp::CalendarColor(color) => {
|
CalendarProp::CalendarColor(color) => {
|
||||||
self.cal.color = color;
|
self.cal.color = color;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -207,21 +195,42 @@ impl Resource for CalendarResource {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
CalendarProp::CalendarTimezone(timezone) => {
|
CalendarProp::CalendarTimezone(timezone) => {
|
||||||
// TODO: Ensure that timezone-id is also updated
|
if let Some(tz) = timezone {
|
||||||
self.cal.timezone = 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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
CalendarProp::TimezoneServiceSet(_) => Err(rustical_dav::Error::PropReadOnly),
|
CalendarProp::TimezoneServiceSet(_) => Err(rustical_dav::Error::PropReadOnly),
|
||||||
CalendarProp::CalendarTimezoneId(timezone_id) => {
|
CalendarProp::CalendarTimezoneId(timezone_id) => {
|
||||||
if let Some(tzid) = &timezone_id {
|
if let Some(tzid) = &timezone_id {
|
||||||
// Validate timezone id
|
if !vtimezones_rs::VTIMEZONES.contains_key(tzid) {
|
||||||
chrono_tz::Tz::from_str(tzid).map_err(|_| {
|
return Err(rustical_dav::Error::BadRequest(format!(
|
||||||
rustical_dav::Error::BadRequest(format!(
|
"Invalid timezone-id: {tzid}"
|
||||||
"Invalid timezone-id: {}",
|
)));
|
||||||
tzid
|
}
|
||||||
))
|
|
||||||
})?;
|
|
||||||
// TODO: Ensure that timezone is also updated (For now hope that clients play nice)
|
|
||||||
}
|
}
|
||||||
self.cal.timezone_id = timezone_id;
|
self.cal.timezone_id = timezone_id;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -254,10 +263,6 @@ impl Resource for CalendarResource {
|
|||||||
}
|
}
|
||||||
match prop {
|
match prop {
|
||||||
CalendarPropWrapperName::Calendar(prop) => match prop {
|
CalendarPropWrapperName::Calendar(prop) => match prop {
|
||||||
CalendarPropName::Displayname => {
|
|
||||||
self.cal.displayname = None;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
CalendarPropName::CalendarColor => {
|
CalendarPropName::CalendarColor => {
|
||||||
self.cal.color = None;
|
self.cal.color = None;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -266,15 +271,11 @@ impl Resource for CalendarResource {
|
|||||||
self.cal.description = None;
|
self.cal.description = None;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
CalendarPropName::CalendarTimezone => {
|
CalendarPropName::CalendarTimezone | CalendarPropName::CalendarTimezoneId => {
|
||||||
self.cal.timezone = None;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
CalendarPropName::TimezoneServiceSet => Err(rustical_dav::Error::PropReadOnly),
|
|
||||||
CalendarPropName::CalendarTimezoneId => {
|
|
||||||
self.cal.timezone_id = None;
|
self.cal.timezone_id = None;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
CalendarPropName::TimezoneServiceSet => Err(rustical_dav::Error::PropReadOnly),
|
||||||
CalendarPropName::CalendarOrder => {
|
CalendarPropName::CalendarOrder => {
|
||||||
self.cal.order = 0;
|
self.cal.order = 0;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -298,12 +299,25 @@ impl Resource for CalendarResource {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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> {
|
fn get_owner(&self) -> Option<&str> {
|
||||||
Some(&self.cal.principal)
|
Some(&self.cal.principal)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||||
if self.cal.subscription_url.is_some() || self.read_only {
|
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(
|
return Ok(UserPrivilegeSet::owner_read(
|
||||||
user.is_principal(&self.cal.principal),
|
user.is_principal(&self.cal.principal),
|
||||||
));
|
));
|
||||||
@@ -315,89 +329,14 @@ impl Resource for CalendarResource {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CalendarResourceService<C: CalendarStore, S: SubscriptionStore> {
|
#[cfg(test)]
|
||||||
cal_store: Arc<C>,
|
mod tests {
|
||||||
__phantom_sub: PhantomData<S>,
|
#[test]
|
||||||
}
|
fn test_tzdb_version() {
|
||||||
|
// Ensure that both chrono_tz and vzic_rs use the same tzdb version
|
||||||
impl<C: CalendarStore, S: SubscriptionStore> CalendarResourceService<C, S> {
|
assert_eq!(
|
||||||
pub fn new(cal_store: Arc<C>) -> Self {
|
chrono_tz::IANA_TZDB_VERSION,
|
||||||
Self {
|
vtimezones_rs::IANA_TZDB_VERSION
|
||||||
cal_store,
|
);
|
||||||
__phantom_sub: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourceService<C, S> {
|
|
||||||
type MemberType = CalendarObjectResource;
|
|
||||||
type PathComponents = (String, String); // principal, calendar_id
|
|
||||||
type Resource = CalendarResource;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
async fn get_resource(
|
|
||||||
&self,
|
|
||||||
(principal, cal_id): &Self::PathComponents,
|
|
||||||
) -> Result<Self::Resource, Error> {
|
|
||||||
let calendar = self.cal_store.get_calendar(principal, cal_id).await?;
|
|
||||||
Ok(CalendarResource {
|
|
||||||
cal: calendar,
|
|
||||||
read_only: self.cal_store.is_read_only(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_members(
|
|
||||||
&self,
|
|
||||||
(principal, cal_id): &Self::PathComponents,
|
|
||||||
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
|
|
||||||
Ok(self
|
|
||||||
.cal_store
|
|
||||||
.get_objects(principal, cal_id)
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.map(|object| {
|
|
||||||
(
|
|
||||||
format!("{}.ics", object.get_id()),
|
|
||||||
CalendarObjectResource {
|
|
||||||
object,
|
|
||||||
principal: principal.to_owned(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn save_resource(
|
|
||||||
&self,
|
|
||||||
(principal, cal_id): &Self::PathComponents,
|
|
||||||
file: Self::Resource,
|
|
||||||
) -> Result<(), Self::Error> {
|
|
||||||
self.cal_store
|
|
||||||
.update_calendar(principal.to_owned(), cal_id.to_owned(), file.into())
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_resource(
|
|
||||||
&self,
|
|
||||||
(principal, cal_id): &Self::PathComponents,
|
|
||||||
use_trashbin: bool,
|
|
||||||
) -> Result<(), Self::Error> {
|
|
||||||
self.cal_store
|
|
||||||
.delete_calendar(principal, cal_id, use_trashbin)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
|
|
||||||
let report_method = web::method(Method::from_str("REPORT").unwrap());
|
|
||||||
let mkcalendar_method = web::method(Method::from_str("MKCALENDAR").unwrap());
|
|
||||||
|
|
||||||
res.route(report_method.to(route_report_calendar::<C>))
|
|
||||||
.route(mkcalendar_method.to(route_mkcalendar::<C>))
|
|
||||||
.post(route_post::<C, S>)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
155
crates/caldav/src/calendar/service.rs
Normal file
155
crates/caldav/src/calendar/service.rs
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
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;
|
||||||
|
use crate::calendar_object::resource::CalendarObjectResource;
|
||||||
|
use crate::{CalDavPrincipalUri, Error};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use axum::Router;
|
||||||
|
use axum::extract::Request;
|
||||||
|
use axum::handler::Handler;
|
||||||
|
use axum::response::Response;
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||||
|
use rustical_store::auth::Principal;
|
||||||
|
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||||
|
use std::convert::Infallible;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tower::Service;
|
||||||
|
|
||||||
|
pub struct CalendarResourceService<C: CalendarStore, S: SubscriptionStore> {
|
||||||
|
pub(crate) cal_store: Arc<C>,
|
||||||
|
pub(crate) sub_store: Arc<S>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: CalendarStore, S: SubscriptionStore> Clone for CalendarResourceService<C, S> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
cal_store: self.cal_store.clone(),
|
||||||
|
sub_store: self.sub_store.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: CalendarStore, S: SubscriptionStore> CalendarResourceService<C, S> {
|
||||||
|
pub fn new(cal_store: Arc<C>, sub_store: Arc<S>) -> Self {
|
||||||
|
Self {
|
||||||
|
cal_store,
|
||||||
|
sub_store,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourceService<C, S> {
|
||||||
|
type MemberType = CalendarObjectResource;
|
||||||
|
type PathComponents = (String, String); // principal, calendar_id
|
||||||
|
type Resource = CalendarResource;
|
||||||
|
type Error = Error;
|
||||||
|
type Principal = Principal;
|
||||||
|
type PrincipalUri = CalDavPrincipalUri;
|
||||||
|
|
||||||
|
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, show_deleted)
|
||||||
|
.await?;
|
||||||
|
Ok(CalendarResource {
|
||||||
|
cal: calendar,
|
||||||
|
read_only: self.cal_store.is_read_only(cal_id),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_members(
|
||||||
|
&self,
|
||||||
|
(principal, cal_id): &Self::PathComponents,
|
||||||
|
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||||
|
Ok(self
|
||||||
|
.cal_store
|
||||||
|
.get_objects(principal, cal_id)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(|object| CalendarObjectResource {
|
||||||
|
object,
|
||||||
|
principal: principal.to_owned(),
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn save_resource(
|
||||||
|
&self,
|
||||||
|
(principal, cal_id): &Self::PathComponents,
|
||||||
|
file: Self::Resource,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
self.cal_store
|
||||||
|
.update_calendar(principal.to_owned(), cal_id.to_owned(), file.into())
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_resource(
|
||||||
|
&self,
|
||||||
|
(principal, cal_id): &Self::PathComponents,
|
||||||
|
use_trashbin: bool,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
self.cal_store
|
||||||
|
.delete_calendar(principal, cal_id, use_trashbin)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn axum_router<State: Send + Sync + Clone + 'static>(self) -> axum::Router<State> {
|
||||||
|
Router::new()
|
||||||
|
.nest(
|
||||||
|
"/{object_id}",
|
||||||
|
CalendarObjectResourceService::new(self.cal_store.clone()).axum_router(),
|
||||||
|
)
|
||||||
|
.route_service("/", self.axum_service())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: CalendarStore, S: SubscriptionStore> AxumMethods for CalendarResourceService<C, S> {
|
||||||
|
fn report() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(route_report_calendar::<C, S>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(route_get::<C, S>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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| {
|
||||||
|
let mut service = Handler::with_state(route_mkcalendar::<C, S>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mkcol() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(route_mkcalendar::<C, S>, state);
|
||||||
|
Box::pin(Service::call(&mut service, 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,74 +1,93 @@
|
|||||||
use crate::Error;
|
use crate::Error;
|
||||||
use actix_web::HttpRequest;
|
use crate::calendar_object::{CalendarObjectPathComponents, CalendarObjectResourceService};
|
||||||
use actix_web::HttpResponse;
|
use crate::error::Precondition;
|
||||||
use actix_web::http::header;
|
use axum::body::Body;
|
||||||
use actix_web::http::header::HeaderValue;
|
use axum::extract::{Path, State};
|
||||||
use actix_web::web::{Data, Path};
|
use axum::response::{IntoResponse, Response};
|
||||||
use rustical_store::auth::User;
|
use axum_extra::TypedHeader;
|
||||||
use rustical_store::{CalendarObject, CalendarStore};
|
use headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||||
|
use http::{HeaderMap, Method, StatusCode};
|
||||||
|
use rustical_ical::CalendarObject;
|
||||||
|
use rustical_store::CalendarStore;
|
||||||
|
use rustical_store::auth::Principal;
|
||||||
|
use std::str::FromStr;
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
use super::resource::CalendarObjectPathComponents;
|
#[instrument(skip(cal_store))]
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(store, root_span))]
|
|
||||||
pub async fn get_event<C: CalendarStore>(
|
pub async fn get_event<C: CalendarStore>(
|
||||||
path: Path<CalendarObjectPathComponents>,
|
Path(CalendarObjectPathComponents {
|
||||||
store: Data<C>,
|
|
||||||
user: User,
|
|
||||||
root_span: RootSpan,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let CalendarObjectPathComponents {
|
|
||||||
principal,
|
principal,
|
||||||
calendar_id,
|
calendar_id,
|
||||||
object_id,
|
object_id,
|
||||||
} = path.into_inner();
|
}): Path<CalendarObjectPathComponents>,
|
||||||
|
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
|
||||||
|
user: Principal,
|
||||||
|
method: Method,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Ok(HttpResponse::Unauthorized().body(""));
|
return Err(crate::Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let calendar = store.get_calendar(&principal, &calendar_id).await?;
|
let calendar = cal_store
|
||||||
|
.get_calendar(&principal, &calendar_id, false)
|
||||||
|
.await?;
|
||||||
if !user.is_principal(&calendar.principal) {
|
if !user.is_principal(&calendar.principal) {
|
||||||
return Ok(HttpResponse::Unauthorized().body(""));
|
return Err(crate::Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let event = store
|
let event = cal_store
|
||||||
.get_object(&principal, &calendar_id, &object_id)
|
.get_object(&principal, &calendar_id, &object_id, false)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(HttpResponse::Ok()
|
let mut resp = Response::builder().status(StatusCode::OK);
|
||||||
.insert_header(("ETag", event.get_etag()))
|
let hdrs = resp.headers_mut().unwrap();
|
||||||
.insert_header(("Content-Type", "text/calendar"))
|
hdrs.typed_insert(ETag::from_str(&event.get_etag()).unwrap());
|
||||||
.body(event.get_ics().to_owned()))
|
hdrs.typed_insert(ContentType::from_str("text/calendar").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(parent = root_span.id(), skip(store, req, root_span))]
|
#[instrument(skip(cal_store))]
|
||||||
pub async fn put_event<C: CalendarStore>(
|
pub async fn put_event<C: CalendarStore>(
|
||||||
path: Path<CalendarObjectPathComponents>,
|
Path(CalendarObjectPathComponents {
|
||||||
store: Data<C>,
|
|
||||||
body: String,
|
|
||||||
user: User,
|
|
||||||
req: HttpRequest,
|
|
||||||
root_span: RootSpan,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let CalendarObjectPathComponents {
|
|
||||||
principal,
|
principal,
|
||||||
calendar_id,
|
calendar_id,
|
||||||
object_id,
|
object_id,
|
||||||
} = path.into_inner();
|
}): Path<CalendarObjectPathComponents>,
|
||||||
|
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
|
||||||
|
user: Principal,
|
||||||
|
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
|
||||||
|
header_map: HeaderMap,
|
||||||
|
body: String,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Ok(HttpResponse::Unauthorized().body(""));
|
return Err(crate::Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let overwrite =
|
// https://github.com/hyperium/headers/issues/204
|
||||||
Some(&HeaderValue::from_static("*")) != req.headers().get(header::IF_NONE_MATCH);
|
if !header_map.contains_key("If-None-Match") {
|
||||||
|
if_none_match = None;
|
||||||
|
}
|
||||||
|
|
||||||
let object = CalendarObject::from_ics(object_id, body)?;
|
let overwrite = if let Some(TypedHeader(if_none_match)) = if_none_match {
|
||||||
store
|
if_none_match == IfNoneMatch::any()
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
};
|
||||||
|
|
||||||
|
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)
|
.put_object(principal, calendar_id, object, overwrite)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(HttpResponse::Created().body(""))
|
Ok(StatusCode::CREATED.into_response())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,2 +1,6 @@
|
|||||||
pub mod methods;
|
pub mod methods;
|
||||||
pub mod resource;
|
pub mod resource;
|
||||||
|
mod service;
|
||||||
|
pub use service::*;
|
||||||
|
mod prop;
|
||||||
|
pub use prop::*;
|
||||||
|
|||||||
45
crates/caldav/src/calendar_object/prop.rs
Normal file
45
crates/caldav/src/calendar_object/prop.rs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
use rustical_dav::extensions::CommonPropertiesProp;
|
||||||
|
use rustical_ical::UtcDateTime;
|
||||||
|
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
|
#[xml(unit_variants_ident = "CalendarObjectPropName")]
|
||||||
|
pub enum CalendarObjectProp {
|
||||||
|
// WebDAV (RFC 2518)
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
|
Getetag(String),
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
||||||
|
Getcontenttype(&'static str),
|
||||||
|
|
||||||
|
// CalDAV (RFC 4791)
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
|
#[xml(prop = "CalendarData")]
|
||||||
|
CalendarData(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
|
#[xml(unit_variants_ident = "CalendarObjectPropWrapperName", untagged)]
|
||||||
|
pub enum CalendarObjectPropWrapper {
|
||||||
|
CalendarObject(CalendarObjectProp),
|
||||||
|
Common(CommonPropertiesProp),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct ExpandElement {
|
||||||
|
#[xml(ty = "attr")]
|
||||||
|
pub(crate) start: UtcDateTime,
|
||||||
|
#[xml(ty = "attr")]
|
||||||
|
pub(crate) end: UtcDateTime,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Default, Eq, Hash)]
|
||||||
|
pub struct CalendarData {
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
|
pub(crate) comp: Option<()>,
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
|
pub(crate) expand: Option<ExpandElement>,
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
|
pub(crate) limit_recurrence_set: Option<()>,
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
|
pub(crate) limit_freebusy_set: Option<()>,
|
||||||
|
}
|
||||||
@@ -1,49 +1,14 @@
|
|||||||
use super::methods::{get_event, put_event};
|
use super::prop::*;
|
||||||
use crate::{Error, principal::PrincipalResource};
|
use crate::Error;
|
||||||
use actix_web::dev::ResourceMap;
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use derive_more::derive::{From, Into};
|
use derive_more::derive::{From, Into};
|
||||||
use rustical_dav::{
|
use rustical_dav::{
|
||||||
extensions::{CommonPropertiesExtension, CommonPropertiesProp},
|
extensions::CommonPropertiesExtension,
|
||||||
privileges::UserPrivilegeSet,
|
privileges::UserPrivilegeSet,
|
||||||
resource::{Resource, ResourceService},
|
resource::{PrincipalUri, Resource, ResourceName},
|
||||||
xml::Resourcetype,
|
xml::Resourcetype,
|
||||||
};
|
};
|
||||||
use rustical_store::{CalendarObject, CalendarStore, auth::User};
|
use rustical_ical::CalendarObject;
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
use rustical_store::auth::Principal;
|
||||||
use serde::Deserialize;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct CalendarObjectResourceService<C: CalendarStore> {
|
|
||||||
cal_store: Arc<C>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: CalendarStore> CalendarObjectResourceService<C> {
|
|
||||||
pub fn new(cal_store: Arc<C>) -> Self {
|
|
||||||
Self { cal_store }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "CalendarObjectPropName")]
|
|
||||||
pub enum CalendarObjectProp {
|
|
||||||
// WebDAV (RFC 2518)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
|
||||||
Getetag(String),
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
|
||||||
Getcontenttype(&'static str),
|
|
||||||
|
|
||||||
// CalDAV (RFC 4791)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
CalendarData(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "CalendarObjectPropWrapperName", untagged)]
|
|
||||||
pub enum CalendarObjectPropWrapper {
|
|
||||||
CalendarObject(CalendarObjectProp),
|
|
||||||
Common(CommonPropertiesProp),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, From, Into)]
|
#[derive(Clone, From, Into)]
|
||||||
pub struct CalendarObjectResource {
|
pub struct CalendarObjectResource {
|
||||||
@@ -51,14 +16,20 @@ pub struct CalendarObjectResource {
|
|||||||
pub principal: String,
|
pub principal: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommonPropertiesExtension for CalendarObjectResource {
|
impl ResourceName for CalendarObjectResource {
|
||||||
type PrincipalResource = PrincipalResource;
|
fn get_name(&self) -> String {
|
||||||
|
format!("{}.ics", self.object.get_id())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Resource for CalendarObjectResource {
|
impl Resource for CalendarObjectResource {
|
||||||
type Prop = CalendarObjectPropWrapper;
|
type Prop = CalendarObjectPropWrapper;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Principal = User;
|
type Principal = Principal;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
fn get_resourcetype(&self) -> Resourcetype {
|
||||||
Resourcetype(&[])
|
Resourcetype(&[])
|
||||||
@@ -66,8 +37,8 @@ impl Resource for CalendarObjectResource {
|
|||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
prop: &CalendarObjectPropWrapperName,
|
prop: &CalendarObjectPropWrapperName,
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
) -> Result<Self::Prop, Self::Error> {
|
||||||
Ok(match prop {
|
Ok(match prop {
|
||||||
@@ -76,8 +47,15 @@ impl Resource for CalendarObjectResource {
|
|||||||
CalendarObjectPropName::Getetag => {
|
CalendarObjectPropName::Getetag => {
|
||||||
CalendarObjectProp::Getetag(self.object.get_etag())
|
CalendarObjectProp::Getetag(self.object.get_etag())
|
||||||
}
|
}
|
||||||
CalendarObjectPropName::CalendarData => {
|
CalendarObjectPropName::CalendarData(CalendarData { expand, .. }) => {
|
||||||
CalendarObjectProp::CalendarData(self.object.get_ics().to_owned())
|
CalendarObjectProp::CalendarData(if let Some(expand) = expand.as_ref() {
|
||||||
|
self.object.expand_recurrence(
|
||||||
|
Some(expand.start.to_utc()),
|
||||||
|
Some(expand.end.to_utc()),
|
||||||
|
)?
|
||||||
|
} else {
|
||||||
|
self.object.get_ics().to_owned()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
CalendarObjectPropName::Getcontenttype => {
|
CalendarObjectPropName::Getcontenttype => {
|
||||||
CalendarObjectProp::Getcontenttype("text/calendar;charset=utf-8")
|
CalendarObjectProp::Getcontenttype("text/calendar;charset=utf-8")
|
||||||
@@ -85,11 +63,15 @@ impl Resource for CalendarObjectResource {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
CalendarObjectPropWrapperName::Common(prop) => CalendarObjectPropWrapper::Common(
|
CalendarObjectPropWrapperName::Common(prop) => CalendarObjectPropWrapper::Common(
|
||||||
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?,
|
CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_displayname(&self) -> Option<&str> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn get_owner(&self) -> Option<&str> {
|
fn get_owner(&self) -> Option<&str> {
|
||||||
Some(&self.principal)
|
Some(&self.principal)
|
||||||
}
|
}
|
||||||
@@ -98,63 +80,9 @@ impl Resource for CalendarObjectResource {
|
|||||||
Some(self.object.get_etag())
|
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(
|
Ok(UserPrivilegeSet::owner_only(
|
||||||
user.is_principal(&self.principal),
|
user.is_principal(&self.principal),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
|
||||||
pub struct CalendarObjectPathComponents {
|
|
||||||
pub principal: String,
|
|
||||||
pub calendar_id: String,
|
|
||||||
pub object_id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
|
|
||||||
type PathComponents = CalendarObjectPathComponents;
|
|
||||||
type Resource = CalendarObjectResource;
|
|
||||||
type MemberType = CalendarObjectResource;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
async fn get_resource(
|
|
||||||
&self,
|
|
||||||
CalendarObjectPathComponents {
|
|
||||||
principal,
|
|
||||||
calendar_id,
|
|
||||||
object_id,
|
|
||||||
}: &Self::PathComponents,
|
|
||||||
) -> Result<Self::Resource, Self::Error> {
|
|
||||||
let object = self
|
|
||||||
.cal_store
|
|
||||||
.get_object(principal, calendar_id, object_id)
|
|
||||||
.await?;
|
|
||||||
Ok(CalendarObjectResource {
|
|
||||||
object,
|
|
||||||
principal: principal.to_owned(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_resource(
|
|
||||||
&self,
|
|
||||||
CalendarObjectPathComponents {
|
|
||||||
principal,
|
|
||||||
calendar_id,
|
|
||||||
object_id,
|
|
||||||
}: &Self::PathComponents,
|
|
||||||
use_trashbin: bool,
|
|
||||||
) -> Result<(), Self::Error> {
|
|
||||||
self.cal_store
|
|
||||||
.delete_object(principal, calendar_id, object_id, use_trashbin)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
|
|
||||||
res.get(get_event::<C>).put(put_event::<C>)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
114
crates/caldav/src/calendar_object/service.rs
Normal file
114
crates/caldav/src/calendar_object/service.rs
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
use crate::{
|
||||||
|
CalDavPrincipalUri, Error,
|
||||||
|
calendar_object::{
|
||||||
|
methods::{get_event, put_event},
|
||||||
|
resource::CalendarObjectResource,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
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::Principal};
|
||||||
|
use serde::{Deserialize, Deserializer};
|
||||||
|
use std::{convert::Infallible, sync::Arc};
|
||||||
|
use tower::Service;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct CalendarObjectPathComponents {
|
||||||
|
pub principal: String,
|
||||||
|
pub calendar_id: String,
|
||||||
|
#[serde(deserialize_with = "deserialize_ics_name")]
|
||||||
|
pub object_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CalendarObjectResourceService<C: CalendarStore> {
|
||||||
|
pub(crate) cal_store: Arc<C>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: CalendarStore> Clone for CalendarObjectResourceService<C> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
cal_store: self.cal_store.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: CalendarStore> CalendarObjectResourceService<C> {
|
||||||
|
pub fn new(cal_store: Arc<C>) -> Self {
|
||||||
|
Self { cal_store }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
|
||||||
|
type PathComponents = CalendarObjectPathComponents;
|
||||||
|
type Resource = CalendarObjectResource;
|
||||||
|
type MemberType = CalendarObjectResource;
|
||||||
|
type Error = Error;
|
||||||
|
type Principal = Principal;
|
||||||
|
type PrincipalUri = CalDavPrincipalUri;
|
||||||
|
|
||||||
|
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||||
|
|
||||||
|
async fn get_resource(
|
||||||
|
&self,
|
||||||
|
CalendarObjectPathComponents {
|
||||||
|
principal,
|
||||||
|
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, show_deleted)
|
||||||
|
.await?;
|
||||||
|
Ok(CalendarObjectResource {
|
||||||
|
object,
|
||||||
|
principal: principal.to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_resource(
|
||||||
|
&self,
|
||||||
|
CalendarObjectPathComponents {
|
||||||
|
principal,
|
||||||
|
calendar_id,
|
||||||
|
object_id,
|
||||||
|
}: &Self::PathComponents,
|
||||||
|
use_trashbin: bool,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
self.cal_store
|
||||||
|
.delete_object(principal, calendar_id, object_id, use_trashbin)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: CalendarStore> AxumMethods for CalendarObjectResourceService<C> {
|
||||||
|
fn get() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(get_event::<C>, 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(put_event::<C>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_ics_name<'de, D>(deserializer: D) -> Result<String, D::Error>
|
||||||
|
where
|
||||||
|
D: Deserializer<'de>,
|
||||||
|
{
|
||||||
|
let name: String = Deserialize::deserialize(deserializer)?;
|
||||||
|
if let Some(object_id) = name.strip_suffix(".ics") {
|
||||||
|
Ok(object_id.to_owned())
|
||||||
|
} else {
|
||||||
|
Err(serde::de::Error::custom("Missing .ics extension"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
use crate::Error;
|
|
||||||
use crate::calendar::resource::CalendarResource;
|
|
||||||
use crate::principal::PrincipalResource;
|
|
||||||
use actix_web::dev::ResourceMap;
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp};
|
|
||||||
use rustical_dav::privileges::UserPrivilegeSet;
|
|
||||||
use rustical_dav::resource::{Resource, ResourceService};
|
|
||||||
use rustical_dav::xml::{Resourcetype, ResourcetypeInner};
|
|
||||||
use rustical_store::CalendarStore;
|
|
||||||
use rustical_store::auth::User;
|
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CalendarSetResource {
|
|
||||||
pub(crate) principal: String,
|
|
||||||
pub(crate) read_only: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
|
||||||
pub enum PrincipalPropWrapper {
|
|
||||||
Common(CommonPropertiesProp),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommonPropertiesExtension for CalendarSetResource {
|
|
||||||
type PrincipalResource = PrincipalResource;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resource for CalendarSetResource {
|
|
||||||
type Prop = PrincipalPropWrapper;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
|
||||||
Resourcetype(&[ResourcetypeInner(
|
|
||||||
Some(rustical_dav::namespace::NS_DAV),
|
|
||||||
"collection",
|
|
||||||
)])
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_prop(
|
|
||||||
&self,
|
|
||||||
rmap: &ResourceMap,
|
|
||||||
user: &User,
|
|
||||||
prop: &PrincipalPropWrapperName,
|
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
|
||||||
Ok(match prop {
|
|
||||||
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
|
||||||
<Self as CommonPropertiesExtension>::get_prop(self, rmap, 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))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct CalendarSetResourceService<C: CalendarStore> {
|
|
||||||
cal_store: Arc<C>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: CalendarStore> CalendarSetResourceService<C> {
|
|
||||||
pub fn new(cal_store: Arc<C>) -> Self {
|
|
||||||
Self { cal_store }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl<C: CalendarStore> ResourceService for CalendarSetResourceService<C> {
|
|
||||||
type PathComponents = (String,);
|
|
||||||
type MemberType = CalendarResource;
|
|
||||||
type Resource = CalendarSetResource;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
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(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_members(
|
|
||||||
&self,
|
|
||||||
(principal,): &Self::PathComponents,
|
|
||||||
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
|
|
||||||
let calendars = self.cal_store.get_calendars(principal).await?;
|
|
||||||
Ok(calendars
|
|
||||||
.into_iter()
|
|
||||||
.map(|cal| {
|
|
||||||
(
|
|
||||||
cal.id.to_owned(),
|
|
||||||
CalendarResource {
|
|
||||||
cal,
|
|
||||||
read_only: self.cal_store.is_read_only(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,34 @@
|
|||||||
use actix_web::{HttpResponse, http::StatusCode};
|
use axum::{
|
||||||
|
body::Body,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use headers::{ContentType, HeaderMapExt};
|
||||||
|
use http::StatusCode;
|
||||||
|
use rustical_xml::{XmlSerialize, XmlSerializeRoot};
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error, XmlSerialize)]
|
||||||
|
pub enum Precondition {
|
||||||
|
#[error("valid-calendar-data")]
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
|
ValidCalendarData,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for Precondition {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
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);
|
||||||
|
|
||||||
|
let error = rustical_dav::xml::ErrorElement(&self);
|
||||||
|
if let Err(err) = error.serialize_root(&mut writer) {
|
||||||
|
return rustical_dav::Error::from(err).into_response();
|
||||||
|
}
|
||||||
|
let mut res = Response::builder().status(StatusCode::PRECONDITION_FAILED);
|
||||||
|
res.headers_mut().unwrap().typed_insert(ContentType::xml());
|
||||||
|
res.body(Body::from(output)).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
#[error("Unauthorized")]
|
#[error("Unauthorized")]
|
||||||
@@ -23,32 +51,38 @@ pub enum Error {
|
|||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
XmlDecodeError(#[from] rustical_xml::XmlError),
|
XmlDecodeError(#[from] rustical_xml::XmlError),
|
||||||
|
|
||||||
|
#[error(transparent)]
|
||||||
|
IcalError(#[from] rustical_ical::Error),
|
||||||
|
|
||||||
|
#[error(transparent)]
|
||||||
|
PreconditionFailed(Precondition),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl actix_web::ResponseError for Error {
|
impl Error {
|
||||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
pub fn status_code(&self) -> StatusCode {
|
||||||
match self {
|
match self {
|
||||||
Error::StoreError(err) => match err {
|
Error::StoreError(err) => match err {
|
||||||
rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
|
rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
|
||||||
rustical_store::Error::InvalidData(_) => StatusCode::BAD_REQUEST,
|
|
||||||
rustical_store::Error::AlreadyExists => StatusCode::CONFLICT,
|
rustical_store::Error::AlreadyExists => StatusCode::CONFLICT,
|
||||||
rustical_store::Error::ParserError(_) => StatusCode::BAD_REQUEST,
|
|
||||||
rustical_store::Error::ReadOnly => StatusCode::FORBIDDEN,
|
rustical_store::Error::ReadOnly => StatusCode::FORBIDDEN,
|
||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
},
|
},
|
||||||
Error::ChronoParseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
Error::ChronoParseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
Error::DavError(err) => err.status_code(),
|
Error::DavError(err) => StatusCode::try_from(err.status_code().as_u16())
|
||||||
|
.expect("Just converting between versions"),
|
||||||
Error::Unauthorized => StatusCode::UNAUTHORIZED,
|
Error::Unauthorized => StatusCode::UNAUTHORIZED,
|
||||||
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
|
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
|
||||||
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
|
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
Error::NotFound => StatusCode::NOT_FOUND,
|
Error::NotFound => StatusCode::NOT_FOUND,
|
||||||
}
|
Error::IcalError(err) => err.status_code(),
|
||||||
}
|
Error::PreconditionFailed(_err) => StatusCode::PRECONDITION_FAILED,
|
||||||
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
|
|
||||||
error!("Error: {self}");
|
|
||||||
match self {
|
|
||||||
Error::DavError(err) => err.error_response(),
|
|
||||||
_ => HttpResponse::build(self.status_code()).body(self.to_string()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for Error {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
(self.status_code(), self.to_string()).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,99 +1,48 @@
|
|||||||
use actix_web::HttpResponse;
|
use axum::{Extension, Router};
|
||||||
use actix_web::dev::{HttpServiceFactory, ServiceResponse};
|
use derive_more::Constructor;
|
||||||
use actix_web::http::header::{self, HeaderName, HeaderValue};
|
use principal::PrincipalResourceService;
|
||||||
use actix_web::http::{Method, StatusCode};
|
use rustical_dav::resource::{PrincipalUri, ResourceService};
|
||||||
use actix_web::middleware::{ErrorHandlerResponse, ErrorHandlers};
|
|
||||||
use actix_web::web::{self, Data};
|
|
||||||
use calendar::resource::CalendarResourceService;
|
|
||||||
use calendar_object::resource::CalendarObjectResourceService;
|
|
||||||
use calendar_set::CalendarSetResourceService;
|
|
||||||
use principal::{PrincipalResource, PrincipalResourceService};
|
|
||||||
use rustical_dav::resource::{NamedRoute, ResourceService, ResourceServiceRoute};
|
|
||||||
use rustical_dav::resources::RootResourceService;
|
use rustical_dav::resources::RootResourceService;
|
||||||
use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider, User};
|
use rustical_store::auth::middleware::AuthenticationLayer;
|
||||||
use rustical_store::{AddressbookStore, CalendarStore, ContactBirthdayStore, SubscriptionStore};
|
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||||
|
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use subscription::subscription_resource;
|
|
||||||
|
|
||||||
pub mod calendar;
|
pub mod calendar;
|
||||||
pub mod calendar_object;
|
pub mod calendar_object;
|
||||||
pub mod calendar_set;
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod principal;
|
pub mod principal;
|
||||||
mod subscription;
|
|
||||||
|
|
||||||
pub use error::Error;
|
pub use error::Error;
|
||||||
|
|
||||||
pub fn caldav_service<
|
#[derive(Debug, Clone, Constructor)]
|
||||||
AP: AuthenticationProvider,
|
pub struct CalDavPrincipalUri(&'static str);
|
||||||
AS: AddressbookStore,
|
|
||||||
C: CalendarStore,
|
impl PrincipalUri for CalDavPrincipalUri {
|
||||||
S: SubscriptionStore,
|
fn principal_collection(&self) -> String {
|
||||||
>(
|
format!("{}/principal/", self.0)
|
||||||
|
}
|
||||||
|
fn principal_uri(&self, principal: &str) -> String {
|
||||||
|
format!("{}{}/", self.principal_collection(), principal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn caldav_router<AP: AuthenticationProvider, C: CalendarStore, S: SubscriptionStore>(
|
||||||
|
prefix: &'static str,
|
||||||
auth_provider: Arc<AP>,
|
auth_provider: Arc<AP>,
|
||||||
store: Arc<C>,
|
store: Arc<C>,
|
||||||
addr_store: Arc<AS>,
|
|
||||||
subscription_store: Arc<S>,
|
subscription_store: Arc<S>,
|
||||||
) -> impl HttpServiceFactory {
|
simplified_home_set: bool,
|
||||||
let birthday_store = Arc::new(ContactBirthdayStore::new(addr_store));
|
) -> Router {
|
||||||
|
Router::new().nest(
|
||||||
web::scope("")
|
prefix,
|
||||||
.wrap(AuthenticationMiddleware::new(auth_provider.clone()))
|
RootResourceService::<_, Principal, CalDavPrincipalUri>::new(PrincipalResourceService {
|
||||||
.wrap(
|
auth_provider: auth_provider.clone(),
|
||||||
ErrorHandlers::new().handler(StatusCode::METHOD_NOT_ALLOWED, |res| {
|
sub_store: subscription_store.clone(),
|
||||||
Ok(ErrorHandlerResponse::Response(
|
cal_store: store.clone(),
|
||||||
if res.request().method() == Method::OPTIONS {
|
simplified_home_set,
|
||||||
let mut response = HttpResponse::Ok();
|
})
|
||||||
response.insert_header((
|
.axum_router()
|
||||||
HeaderName::from_static("dav"),
|
.layer(AuthenticationLayer::new(auth_provider))
|
||||||
// https://datatracker.ietf.org/doc/html/rfc4918#section-18
|
.layer(Extension(CalDavPrincipalUri(prefix))),
|
||||||
HeaderValue::from_static(
|
)
|
||||||
"1, 3, access-control, calendar-access, extended-mkcol, calendar-no-timezone, webdav-push",
|
|
||||||
),
|
|
||||||
));
|
|
||||||
|
|
||||||
if let Some(allow) = res.headers().get(header::ALLOW) {
|
|
||||||
response.insert_header((header::ALLOW, allow.to_owned()));
|
|
||||||
}
|
|
||||||
ServiceResponse::new(res.into_parts().0, response.finish()).map_into_right_body()
|
|
||||||
} else {
|
|
||||||
res.map_into_left_body()
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.app_data(Data::from(store.clone()))
|
|
||||||
.app_data(Data::from(birthday_store.clone()))
|
|
||||||
.app_data(Data::from(subscription_store))
|
|
||||||
.service(RootResourceService::<PrincipalResource, User>::default().actix_resource())
|
|
||||||
.service(
|
|
||||||
web::scope("/principal").service(
|
|
||||||
web::scope("/{principal}")
|
|
||||||
.service(PrincipalResourceService{auth_provider, home_set: &[
|
|
||||||
("calendar", false), ("birthdays", true)
|
|
||||||
]}.actix_resource().name(PrincipalResource::route_name()))
|
|
||||||
.service(web::scope("/calendar")
|
|
||||||
.service(CalendarSetResourceService::new(store.clone()).actix_resource())
|
|
||||||
.service(
|
|
||||||
web::scope("/{calendar_id}")
|
|
||||||
.service(
|
|
||||||
ResourceServiceRoute(CalendarResourceService::<_, S>::new(store.clone()))
|
|
||||||
)
|
|
||||||
.service(web::scope("/{object_id}.ics").service(CalendarObjectResourceService::new(store.clone()).actix_resource()
|
|
||||||
))
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.service(web::scope("/birthdays")
|
|
||||||
.service(CalendarSetResourceService::new(birthday_store.clone()).actix_resource())
|
|
||||||
.service(
|
|
||||||
web::scope("/{calendar_id}")
|
|
||||||
.service(
|
|
||||||
ResourceServiceRoute(CalendarResourceService::<_, S>::new(birthday_store.clone()))
|
|
||||||
)
|
|
||||||
.service(web::scope("/{object_id}.ics").service(CalendarObjectResourceService::new(birthday_store.clone()).actix_resource()
|
|
||||||
))
|
|
||||||
)
|
|
||||||
)
|
|
||||||
),
|
|
||||||
).service(subscription_resource::<S>())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,74 +1,41 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::Error;
|
use crate::Error;
|
||||||
use crate::calendar_set::CalendarSetResource;
|
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||||
use actix_web::dev::ResourceMap;
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp};
|
|
||||||
use rustical_dav::privileges::UserPrivilegeSet;
|
use rustical_dav::privileges::UserPrivilegeSet;
|
||||||
use rustical_dav::resource::{NamedRoute, Resource, ResourceService};
|
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
use rustical_dav::xml::{
|
||||||
use rustical_store::auth::user::PrincipalType;
|
GroupMemberSet, GroupMembership, Resourcetype, ResourcetypeInner, SupportedReportSet,
|
||||||
use rustical_store::auth::{AuthenticationProvider, User};
|
};
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
use rustical_store::auth::Principal;
|
||||||
|
|
||||||
#[derive(Clone)]
|
mod service;
|
||||||
|
pub use service::*;
|
||||||
|
mod prop;
|
||||||
|
pub use prop::*;
|
||||||
|
#[cfg(test)]
|
||||||
|
pub mod tests;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
pub struct PrincipalResource {
|
pub struct PrincipalResource {
|
||||||
principal: User,
|
principal: Principal,
|
||||||
home_set: &'static [(&'static str, bool)],
|
members: Vec<String>,
|
||||||
|
// If true only return the principal as the calendar home set, otherwise also groups
|
||||||
|
simplified_home_set: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
impl ResourceName for PrincipalResource {
|
||||||
pub struct CalendarHomeSet(#[xml(ty = "untagged", flatten)] Vec<HrefElement>);
|
fn get_name(&self) -> String {
|
||||||
|
self.principal.id.to_owned()
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[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),
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
CalendarUserAddressSet(HrefElement),
|
|
||||||
|
|
||||||
// WebDAV Access Control (RFC 3744)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", rename = b"principal-URL")]
|
|
||||||
PrincipalUrl(HrefElement),
|
|
||||||
|
|
||||||
// CalDAV (RFC 4791)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
|
||||||
CalendarHomeSet(CalendarHomeSet),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
|
||||||
pub enum PrincipalPropWrapper {
|
|
||||||
Principal(PrincipalProp),
|
|
||||||
Common(CommonPropertiesProp),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PrincipalResource {
|
|
||||||
pub fn get_principal_url(rmap: &ResourceMap, principal: &str) -> String {
|
|
||||||
Self::get_url(rmap, vec![principal]).unwrap()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NamedRoute for PrincipalResource {
|
|
||||||
fn route_name() -> &'static str {
|
|
||||||
"caldav_principal"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommonPropertiesExtension for PrincipalResource {
|
|
||||||
type PrincipalResource = Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resource for PrincipalResource {
|
impl Resource for PrincipalResource {
|
||||||
type Prop = PrincipalPropWrapper;
|
type Prop = PrincipalPropWrapper;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Principal = User;
|
type Principal = Principal;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
fn get_resourcetype(&self) -> Resourcetype {
|
||||||
Resourcetype(&[
|
Resourcetype(&[
|
||||||
@@ -79,23 +46,11 @@ impl Resource for PrincipalResource {
|
|||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
prop: &PrincipalPropWrapperName,
|
prop: &PrincipalPropWrapperName,
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
) -> Result<Self::Prop, Self::Error> {
|
||||||
let principal_url = Self::get_url(rmap, vec![&self.principal.id]).unwrap();
|
let principal_url = puri.principal_uri(&self.principal.id);
|
||||||
|
|
||||||
let home_set = CalendarHomeSet(
|
|
||||||
user.memberships()
|
|
||||||
.into_iter()
|
|
||||||
.map(|principal| Self::get_url(rmap, vec![principal]).unwrap())
|
|
||||||
.flat_map(|principal_url| {
|
|
||||||
self.home_set.iter().map(move |&(home_name, _read_only)| {
|
|
||||||
HrefElement::new(format!("{}/{}", &principal_url, home_name))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(match prop {
|
Ok(match prop {
|
||||||
PrincipalPropWrapperName::Principal(prop) => {
|
PrincipalPropWrapperName::Principal(prop) => {
|
||||||
@@ -103,82 +58,71 @@ impl Resource for PrincipalResource {
|
|||||||
PrincipalPropName::CalendarUserType => {
|
PrincipalPropName::CalendarUserType => {
|
||||||
PrincipalProp::CalendarUserType(self.principal.principal_type.to_owned())
|
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 => {
|
PrincipalPropName::PrincipalUrl => {
|
||||||
PrincipalProp::PrincipalUrl(principal_url.into())
|
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 => {
|
PrincipalPropName::CalendarUserAddressSet => {
|
||||||
PrincipalProp::CalendarUserAddressSet(principal_url.into())
|
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(
|
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
||||||
<Self as CommonPropertiesExtension>::get_prop(self, rmap, user, prop)?,
|
<Self as CommonPropertiesExtension>::get_prop(self, puri, user, prop)?,
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_displayname(&self) -> Option<&str> {
|
||||||
|
Some(
|
||||||
|
self.principal
|
||||||
|
.displayname
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or(&self.principal.id),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn get_owner(&self) -> Option<&str> {
|
fn get_owner(&self) -> Option<&str> {
|
||||||
Some(&self.principal.id)
|
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_read(
|
Ok(UserPrivilegeSet::owner_only(
|
||||||
user.is_principal(&self.principal.id),
|
user.is_principal(&self.principal.id),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct PrincipalResourceService<AP: AuthenticationProvider> {
|
|
||||||
pub auth_provider: Arc<AP>,
|
|
||||||
pub home_set: &'static [(&'static str, bool)],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl<AP: AuthenticationProvider> ResourceService for PrincipalResourceService<AP> {
|
|
||||||
type PathComponents = (String,);
|
|
||||||
type MemberType = CalendarSetResource;
|
|
||||||
type Resource = PrincipalResource;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
async fn get_resource(
|
|
||||||
&self,
|
|
||||||
(principal,): &Self::PathComponents,
|
|
||||||
) -> Result<Self::Resource, Self::Error> {
|
|
||||||
let user = self
|
|
||||||
.auth_provider
|
|
||||||
.get_principal(principal)
|
|
||||||
.await?
|
|
||||||
.ok_or(crate::Error::NotFound)?;
|
|
||||||
Ok(PrincipalResource {
|
|
||||||
principal: user,
|
|
||||||
home_set: self.home_set,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_members(
|
|
||||||
&self,
|
|
||||||
(principal,): &Self::PathComponents,
|
|
||||||
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
|
|
||||||
Ok(self
|
|
||||||
.home_set
|
|
||||||
.iter()
|
|
||||||
.map(|&(set_name, read_only)| {
|
|
||||||
(
|
|
||||||
set_name.to_string(),
|
|
||||||
CalendarSetResource {
|
|
||||||
principal: principal.to_owned(),
|
|
||||||
read_only,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
52
crates/caldav/src/principal/prop.rs
Normal file
52
crates/caldav/src/principal/prop.rs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
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 {
|
||||||
|
// Scheduling Extensions to CalDAV (RFC 6638)
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
||||||
|
CalendarUserType(PrincipalType),
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||||
|
CalendarUserAddressSet(HrefElement),
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
Principal(PrincipalProp),
|
||||||
|
Common(CommonPropertiesProp),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(XmlSerialize, PartialEq, Clone, VariantArray)]
|
||||||
|
pub enum ReportMethod {
|
||||||
|
// We don't actually support principal-match
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
|
PrincipalMatch,
|
||||||
|
}
|
||||||
97
crates/caldav/src/principal/service.rs
Normal file
97
crates/caldav/src/principal/service.rs
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
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, Principal};
|
||||||
|
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct PrincipalResourceService<
|
||||||
|
AP: AuthenticationProvider,
|
||||||
|
S: SubscriptionStore,
|
||||||
|
CS: CalendarStore,
|
||||||
|
> {
|
||||||
|
pub(crate) auth_provider: Arc<AP>,
|
||||||
|
pub(crate) sub_store: Arc<S>,
|
||||||
|
pub(crate) cal_store: Arc<CS>,
|
||||||
|
// If true only return the principal as the calendar home set, otherwise also groups
|
||||||
|
pub(crate) simplified_home_set: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
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(),
|
||||||
|
simplified_home_set: self.simplified_home_set,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> ResourceService
|
||||||
|
for PrincipalResourceService<AP, S, CS>
|
||||||
|
{
|
||||||
|
type PathComponents = (String,);
|
||||||
|
type MemberType = CalendarResource;
|
||||||
|
type Resource = PrincipalResource;
|
||||||
|
type Error = Error;
|
||||||
|
type Principal = Principal;
|
||||||
|
type PrincipalUri = CalDavPrincipalUri;
|
||||||
|
|
||||||
|
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||||
|
|
||||||
|
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 {
|
||||||
|
members: self.auth_provider.list_members(&user.id).await?,
|
||||||
|
principal: user,
|
||||||
|
simplified_home_set: self.simplified_home_set,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
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_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> 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,30 +0,0 @@
|
|||||||
use actix_web::{
|
|
||||||
web::{self, Data, Path},
|
|
||||||
HttpResponse,
|
|
||||||
};
|
|
||||||
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>() -> actix_web::Resource {
|
|
||||||
web::resource("/subscription/{id}")
|
|
||||||
.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,18 +4,19 @@ version.workspace = true
|
|||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
description.workspace = true
|
description.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
license.workspace = true
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { workspace = true }
|
axum.workspace = true
|
||||||
|
axum-extra.workspace = true
|
||||||
|
tower.workspace = true
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
quick-xml = { workspace = true }
|
quick-xml = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
tracing-actix-web = { workspace = true }
|
|
||||||
futures-util = { workspace = true }
|
futures-util = { workspace = true }
|
||||||
derive_more = { workspace = true }
|
derive_more = { workspace = true }
|
||||||
actix-web-httpauth = { workspace = true }
|
|
||||||
base64 = { workspace = true }
|
base64 = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
@@ -26,3 +27,10 @@ chrono = { workspace = true }
|
|||||||
rustical_xml.workspace = true
|
rustical_xml.workspace = true
|
||||||
uuid.workspace = true
|
uuid.workspace = true
|
||||||
rustical_dav_push.workspace = true
|
rustical_dav_push.workspace = true
|
||||||
|
rustical_ical.workspace = true
|
||||||
|
http.workspace = true
|
||||||
|
tower-http.workspace = true
|
||||||
|
percent-encoding.workspace = true
|
||||||
|
ical.workspace = true
|
||||||
|
strum.workspace = true
|
||||||
|
strum_macros.workspace = true
|
||||||
|
|||||||
@@ -1,36 +1,38 @@
|
|||||||
use super::resource::AddressObjectPathComponents;
|
use super::AddressObjectPathComponents;
|
||||||
|
use super::AddressObjectResourceService;
|
||||||
use crate::Error;
|
use crate::Error;
|
||||||
use crate::addressbook::resource::AddressbookResource;
|
use crate::addressbook::resource::AddressbookResource;
|
||||||
use actix_web::HttpRequest;
|
use axum::body::Body;
|
||||||
use actix_web::HttpResponse;
|
use axum::extract::{Path, State};
|
||||||
use actix_web::http::header;
|
use axum::response::{IntoResponse, Response};
|
||||||
use actix_web::http::header::HeaderValue;
|
use axum_extra::TypedHeader;
|
||||||
use actix_web::web::{Data, Path};
|
use axum_extra::headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||||
|
use http::Method;
|
||||||
|
use http::{HeaderMap, StatusCode};
|
||||||
use rustical_dav::privileges::UserPrivilege;
|
use rustical_dav::privileges::UserPrivilege;
|
||||||
use rustical_dav::resource::Resource;
|
use rustical_dav::resource::Resource;
|
||||||
use rustical_store::auth::User;
|
use rustical_ical::AddressObject;
|
||||||
use rustical_store::{AddressObject, AddressbookStore};
|
use rustical_store::AddressbookStore;
|
||||||
|
use rustical_store::auth::Principal;
|
||||||
|
use std::str::FromStr;
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(store, root_span))]
|
#[instrument(skip(addr_store))]
|
||||||
pub async fn get_object<AS: AddressbookStore>(
|
pub async fn get_object<AS: AddressbookStore>(
|
||||||
path: Path<AddressObjectPathComponents>,
|
Path(AddressObjectPathComponents {
|
||||||
store: Data<AS>,
|
|
||||||
user: User,
|
|
||||||
root_span: RootSpan,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let AddressObjectPathComponents {
|
|
||||||
principal,
|
principal,
|
||||||
addressbook_id,
|
addressbook_id,
|
||||||
object_id,
|
object_id,
|
||||||
} = path.into_inner();
|
}): Path<AddressObjectPathComponents>,
|
||||||
|
State(AddressObjectResourceService { addr_store }): State<AddressObjectResourceService<AS>>,
|
||||||
|
user: Principal,
|
||||||
|
method: Method,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let addressbook = store
|
let addressbook = addr_store
|
||||||
.get_addressbook(&principal, &addressbook_id, false)
|
.get_addressbook(&principal, &addressbook_id, false)
|
||||||
.await?;
|
.await?;
|
||||||
let addressbook_resource = AddressbookResource(addressbook);
|
let addressbook_resource = AddressbookResource(addressbook);
|
||||||
@@ -41,42 +43,53 @@ pub async fn get_object<AS: AddressbookStore>(
|
|||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let object = store
|
let object = addr_store
|
||||||
.get_object(&principal, &addressbook_id, &object_id, false)
|
.get_object(&principal, &addressbook_id, &object_id, false)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(HttpResponse::Ok()
|
let mut resp = Response::builder().status(StatusCode::OK);
|
||||||
.insert_header(("ETag", object.get_etag()))
|
let hdrs = resp.headers_mut().unwrap();
|
||||||
.insert_header(("Content-Type", "text/vcard"))
|
hdrs.typed_insert(ETag::from_str(&object.get_etag()).unwrap());
|
||||||
.body(object.get_vcf().to_owned()))
|
hdrs.typed_insert(ContentType::from_str("text/vcard").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(parent = root_span.id(), skip(store, req, root_span))]
|
#[instrument(skip(addr_store, body))]
|
||||||
pub async fn put_object<AS: AddressbookStore>(
|
pub async fn put_object<AS: AddressbookStore>(
|
||||||
path: Path<AddressObjectPathComponents>,
|
Path(AddressObjectPathComponents {
|
||||||
store: Data<AS>,
|
|
||||||
body: String,
|
|
||||||
user: User,
|
|
||||||
req: HttpRequest,
|
|
||||||
root_span: RootSpan,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let AddressObjectPathComponents {
|
|
||||||
principal,
|
principal,
|
||||||
addressbook_id,
|
addressbook_id,
|
||||||
object_id,
|
object_id,
|
||||||
} = path.into_inner();
|
}): Path<AddressObjectPathComponents>,
|
||||||
|
State(AddressObjectResourceService { addr_store }): State<AddressObjectResourceService<AS>>,
|
||||||
|
user: Principal,
|
||||||
|
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
|
||||||
|
header_map: HeaderMap,
|
||||||
|
body: String,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let overwrite =
|
// https://github.com/hyperium/headers/issues/204
|
||||||
Some(&HeaderValue::from_static("*")) != req.headers().get(header::IF_NONE_MATCH);
|
if !header_map.contains_key("If-None-Match") {
|
||||||
|
if_none_match = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let overwrite = if let Some(TypedHeader(if_none_match)) = if_none_match {
|
||||||
|
if_none_match == IfNoneMatch::any()
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
};
|
||||||
|
|
||||||
let object = AddressObject::from_vcf(object_id, body)?;
|
let object = AddressObject::from_vcf(object_id, body)?;
|
||||||
store
|
addr_store
|
||||||
.put_object(principal, addressbook_id, object, overwrite)
|
.put_object(principal, addressbook_id, object, overwrite)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(HttpResponse::Created().finish())
|
Ok(StatusCode::CREATED.into_response())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,2 +1,6 @@
|
|||||||
pub mod methods;
|
pub mod methods;
|
||||||
pub mod resource;
|
pub mod resource;
|
||||||
|
mod service;
|
||||||
|
pub use service::*;
|
||||||
|
mod prop;
|
||||||
|
pub use prop::*;
|
||||||
|
|||||||
23
crates/carddav/src/address_object/prop.rs
Normal file
23
crates/carddav/src/address_object/prop.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
use rustical_dav::extensions::CommonPropertiesProp;
|
||||||
|
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
|
#[xml(unit_variants_ident = "AddressObjectPropName")]
|
||||||
|
pub enum AddressObjectProp {
|
||||||
|
// WebDAV (RFC 2518)
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
|
Getetag(String),
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
||||||
|
Getcontenttype(&'static str),
|
||||||
|
|
||||||
|
// CalDAV (RFC 4791)
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||||
|
AddressData(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
|
#[xml(unit_variants_ident = "AddressObjectPropWrapperName", untagged)]
|
||||||
|
pub enum AddressObjectPropWrapper {
|
||||||
|
AddressObject(AddressObjectProp),
|
||||||
|
Common(CommonPropertiesProp),
|
||||||
|
}
|
||||||
@@ -1,45 +1,19 @@
|
|||||||
use crate::{Error, principal::PrincipalResource};
|
use crate::{
|
||||||
use actix_web::dev::ResourceMap;
|
Error,
|
||||||
use async_trait::async_trait;
|
address_object::{
|
||||||
use derive_more::derive::{Constructor, From, Into};
|
AddressObjectProp, AddressObjectPropName, AddressObjectPropWrapper,
|
||||||
|
AddressObjectPropWrapperName,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use derive_more::derive::{From, Into};
|
||||||
use rustical_dav::{
|
use rustical_dav::{
|
||||||
extensions::{CommonPropertiesExtension, CommonPropertiesProp},
|
extensions::CommonPropertiesExtension,
|
||||||
privileges::UserPrivilegeSet,
|
privileges::UserPrivilegeSet,
|
||||||
resource::{Resource, ResourceService},
|
resource::{PrincipalUri, Resource, ResourceName},
|
||||||
xml::Resourcetype,
|
xml::Resourcetype,
|
||||||
};
|
};
|
||||||
use rustical_store::{AddressObject, AddressbookStore, auth::User};
|
use rustical_ical::AddressObject;
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
use rustical_store::auth::Principal;
|
||||||
use serde::Deserialize;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use super::methods::{get_object, put_object};
|
|
||||||
|
|
||||||
#[derive(Constructor)]
|
|
||||||
pub struct AddressObjectResourceService<AS: AddressbookStore> {
|
|
||||||
addr_store: Arc<AS>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "AddressObjectPropName")]
|
|
||||||
pub enum AddressObjectProp {
|
|
||||||
// WebDAV (RFC 2518)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
|
||||||
Getetag(String),
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
|
||||||
Getcontenttype(&'static str),
|
|
||||||
|
|
||||||
// CalDAV (RFC 4791)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
|
||||||
AddressData(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "AddressObjectPropWrapperName", untagged)]
|
|
||||||
pub enum AddressObjectPropWrapper {
|
|
||||||
AddressObject(AddressObjectProp),
|
|
||||||
Common(CommonPropertiesProp),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, From, Into)]
|
#[derive(Clone, From, Into)]
|
||||||
pub struct AddressObjectResource {
|
pub struct AddressObjectResource {
|
||||||
@@ -47,14 +21,20 @@ pub struct AddressObjectResource {
|
|||||||
pub principal: String,
|
pub principal: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommonPropertiesExtension for AddressObjectResource {
|
impl ResourceName for AddressObjectResource {
|
||||||
type PrincipalResource = PrincipalResource;
|
fn get_name(&self) -> String {
|
||||||
|
format!("{}.vcf", self.object.get_id())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Resource for AddressObjectResource {
|
impl Resource for AddressObjectResource {
|
||||||
type Prop = AddressObjectPropWrapper;
|
type Prop = AddressObjectPropWrapper;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Principal = User;
|
type Principal = Principal;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
fn get_resourcetype(&self) -> Resourcetype {
|
||||||
Resourcetype(&[])
|
Resourcetype(&[])
|
||||||
@@ -62,8 +42,8 @@ impl Resource for AddressObjectResource {
|
|||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
prop: &AddressObjectPropWrapperName,
|
prop: &AddressObjectPropWrapperName,
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
) -> Result<Self::Prop, Self::Error> {
|
||||||
Ok(match prop {
|
Ok(match prop {
|
||||||
@@ -81,11 +61,15 @@ impl Resource for AddressObjectResource {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
AddressObjectPropWrapperName::Common(prop) => AddressObjectPropWrapper::Common(
|
AddressObjectPropWrapperName::Common(prop) => AddressObjectPropWrapper::Common(
|
||||||
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?,
|
CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_displayname(&self) -> Option<&str> {
|
||||||
|
self.object.get_full_name()
|
||||||
|
}
|
||||||
|
|
||||||
fn get_owner(&self) -> Option<&str> {
|
fn get_owner(&self) -> Option<&str> {
|
||||||
Some(&self.principal)
|
Some(&self.principal)
|
||||||
}
|
}
|
||||||
@@ -94,63 +78,9 @@ impl Resource for AddressObjectResource {
|
|||||||
Some(self.object.get_etag())
|
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(
|
Ok(UserPrivilegeSet::owner_only(
|
||||||
user.is_principal(&self.principal),
|
user.is_principal(&self.principal),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
|
||||||
pub struct AddressObjectPathComponents {
|
|
||||||
pub principal: String,
|
|
||||||
pub addressbook_id: String,
|
|
||||||
pub object_id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS> {
|
|
||||||
type PathComponents = AddressObjectPathComponents;
|
|
||||||
type Resource = AddressObjectResource;
|
|
||||||
type MemberType = AddressObjectResource;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
async fn get_resource(
|
|
||||||
&self,
|
|
||||||
AddressObjectPathComponents {
|
|
||||||
principal,
|
|
||||||
addressbook_id,
|
|
||||||
object_id,
|
|
||||||
}: &Self::PathComponents,
|
|
||||||
) -> Result<Self::Resource, Self::Error> {
|
|
||||||
let object = self
|
|
||||||
.addr_store
|
|
||||||
.get_object(principal, addressbook_id, object_id, false)
|
|
||||||
.await?;
|
|
||||||
Ok(AddressObjectResource {
|
|
||||||
object,
|
|
||||||
principal: principal.to_owned(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_resource(
|
|
||||||
&self,
|
|
||||||
AddressObjectPathComponents {
|
|
||||||
principal,
|
|
||||||
addressbook_id,
|
|
||||||
object_id,
|
|
||||||
}: &Self::PathComponents,
|
|
||||||
use_trashbin: bool,
|
|
||||||
) -> Result<(), Self::Error> {
|
|
||||||
self.addr_store
|
|
||||||
.delete_object(principal, addressbook_id, object_id, use_trashbin)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
|
|
||||||
res.get(get_object::<AS>).put(put_object::<AS>)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
106
crates/carddav/src/address_object/service.rs
Normal file
106
crates/carddav/src/address_object/service.rs
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
use super::methods::{get_object, put_object};
|
||||||
|
use crate::{CardDavPrincipalUri, Error, address_object::resource::AddressObjectResource};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
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::Principal};
|
||||||
|
use serde::{Deserialize, Deserializer};
|
||||||
|
use std::{convert::Infallible, sync::Arc};
|
||||||
|
use tower::Service;
|
||||||
|
|
||||||
|
#[derive(Constructor)]
|
||||||
|
pub struct AddressObjectResourceService<AS: AddressbookStore> {
|
||||||
|
pub(crate) addr_store: Arc<AS>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<AS: AddressbookStore> Clone for AddressObjectResourceService<AS> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
addr_store: self.addr_store.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct AddressObjectPathComponents {
|
||||||
|
pub principal: String,
|
||||||
|
pub addressbook_id: String,
|
||||||
|
#[serde(deserialize_with = "deserialize_vcf_name")]
|
||||||
|
pub object_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS> {
|
||||||
|
type PathComponents = AddressObjectPathComponents;
|
||||||
|
type Resource = AddressObjectResource;
|
||||||
|
type MemberType = AddressObjectResource;
|
||||||
|
type Error = Error;
|
||||||
|
type Principal = Principal;
|
||||||
|
type PrincipalUri = CardDavPrincipalUri;
|
||||||
|
|
||||||
|
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||||
|
|
||||||
|
async fn get_resource(
|
||||||
|
&self,
|
||||||
|
AddressObjectPathComponents {
|
||||||
|
principal,
|
||||||
|
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, show_deleted)
|
||||||
|
.await?;
|
||||||
|
Ok(AddressObjectResource {
|
||||||
|
object,
|
||||||
|
principal: principal.to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_resource(
|
||||||
|
&self,
|
||||||
|
AddressObjectPathComponents {
|
||||||
|
principal,
|
||||||
|
addressbook_id,
|
||||||
|
object_id,
|
||||||
|
}: &Self::PathComponents,
|
||||||
|
use_trashbin: bool,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
self.addr_store
|
||||||
|
.delete_object(principal, addressbook_id, object_id, use_trashbin)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<AS: AddressbookStore> AxumMethods for AddressObjectResourceService<AS> {
|
||||||
|
fn get() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(get_object::<AS>, 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(put_object::<AS>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_vcf_name<'de, D>(deserializer: D) -> Result<String, D::Error>
|
||||||
|
where
|
||||||
|
D: Deserializer<'de>,
|
||||||
|
{
|
||||||
|
let name: String = Deserialize::deserialize(deserializer)?;
|
||||||
|
if let Some(object_id) = name.strip_suffix(".vcf") {
|
||||||
|
Ok(object_id.to_owned())
|
||||||
|
} else {
|
||||||
|
Err(serde::de::Error::custom("Missing .vcf extension"))
|
||||||
|
}
|
||||||
|
}
|
||||||
64
crates/carddav/src/addressbook/methods/get.rs
Normal file
64
crates/carddav/src/addressbook/methods/get.rs
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
use crate::Error;
|
||||||
|
use crate::addressbook::AddressbookResourceService;
|
||||||
|
use crate::addressbook::resource::AddressbookResource;
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::response::Response;
|
||||||
|
use axum_extra::headers::{ContentType, HeaderMapExt};
|
||||||
|
use http::{HeaderValue, Method, StatusCode, header};
|
||||||
|
use percent_encoding::{CONTROLS, utf8_percent_encode};
|
||||||
|
use rustical_dav::privileges::UserPrivilege;
|
||||||
|
use rustical_dav::resource::Resource;
|
||||||
|
use rustical_ical::AddressObject;
|
||||||
|
use rustical_store::auth::Principal;
|
||||||
|
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||||
|
use std::str::FromStr;
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
|
#[instrument(skip(addr_store))]
|
||||||
|
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: Principal,
|
||||||
|
method: Method,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
|
if !user.is_principal(&principal) {
|
||||||
|
return Err(Error::Unauthorized);
|
||||||
|
}
|
||||||
|
|
||||||
|
let addressbook = addr_store
|
||||||
|
.get_addressbook(&principal, &addressbook_id, false)
|
||||||
|
.await?;
|
||||||
|
let addressbook_resource = AddressbookResource(addressbook);
|
||||||
|
if !addressbook_resource
|
||||||
|
.get_user_privileges(&user)?
|
||||||
|
.has(&UserPrivilege::Read)
|
||||||
|
{
|
||||||
|
return Err(Error::Unauthorized);
|
||||||
|
}
|
||||||
|
|
||||||
|
let objects = addr_store.get_objects(&principal, &addressbook_id).await?;
|
||||||
|
let vcf = objects
|
||||||
|
.iter()
|
||||||
|
.map(AddressObject::get_vcf)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\r\n");
|
||||||
|
|
||||||
|
let mut resp = Response::builder().status(StatusCode::OK);
|
||||||
|
let hdrs = resp.headers_mut().unwrap();
|
||||||
|
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
|
||||||
|
let filename = format!("{principal}_{addressbook_id}.vcf");
|
||||||
|
let filename = utf8_percent_encode(&filename, CONTROLS);
|
||||||
|
hdrs.insert(
|
||||||
|
header::CONTENT_DISPOSITION,
|
||||||
|
HeaderValue::from_str(&format!(
|
||||||
|
"attachement; filename*=UTF-8''{filename}; filename={filename}",
|
||||||
|
))
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
if matches!(method, Method::HEAD) {
|
||||||
|
Ok(resp.body(Body::empty()).unwrap())
|
||||||
|
} else {
|
||||||
|
Ok(resp.body(Body::new(vcf)).unwrap())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
use crate::Error;
|
use crate::{Error, addressbook::AddressbookResourceService};
|
||||||
use actix_web::web::Path;
|
use axum::{
|
||||||
use actix_web::{HttpResponse, web::Data};
|
extract::{Path, State},
|
||||||
use rustical_store::{Addressbook, AddressbookStore, auth::User};
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use http::StatusCode;
|
||||||
|
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::Principal};
|
||||||
use rustical_xml::{XmlDeserialize, XmlDocument, XmlRootTag};
|
use rustical_xml::{XmlDeserialize, XmlDocument, XmlRootTag};
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||||
pub struct Resourcetype {
|
pub struct Resourcetype {
|
||||||
@@ -39,21 +41,21 @@ struct MkcolRequest {
|
|||||||
set: PropElement<MkcolAddressbookProp>,
|
set: PropElement<MkcolAddressbookProp>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(store, root_span))]
|
#[instrument(skip(addr_store))]
|
||||||
pub async fn route_mkcol<AS: AddressbookStore>(
|
pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
|
||||||
path: Path<(String, String)>,
|
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||||
|
user: Principal,
|
||||||
|
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||||
body: String,
|
body: String,
|
||||||
user: User,
|
) -> Result<Response, Error> {
|
||||||
store: Data<AS>,
|
|
||||||
root_span: RootSpan,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let (principal, addressbook_id) = path.into_inner();
|
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let request = MkcolRequest::parse_str(&body)?;
|
let mut request = MkcolRequest::parse_str(&body)?.set.prop;
|
||||||
let request = request.set.prop;
|
if let Some("") = request.displayname.as_deref() {
|
||||||
|
request.displayname = None
|
||||||
|
}
|
||||||
|
|
||||||
let addressbook = Addressbook {
|
let addressbook = Addressbook {
|
||||||
id: addressbook_id.to_owned(),
|
id: addressbook_id.to_owned(),
|
||||||
@@ -65,7 +67,7 @@ pub async fn route_mkcol<AS: AddressbookStore>(
|
|||||||
push_topic: uuid::Uuid::new_v4().to_string(),
|
push_topic: uuid::Uuid::new_v4().to_string(),
|
||||||
};
|
};
|
||||||
|
|
||||||
match store
|
match addr_store
|
||||||
.get_addressbook(&principal, &addressbook_id, true)
|
.get_addressbook(&principal, &addressbook_id, true)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
@@ -74,7 +76,11 @@ pub async fn route_mkcol<AS: AddressbookStore>(
|
|||||||
}
|
}
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
// oh no, there's a conflict
|
// oh no, there's a conflict
|
||||||
return Ok(HttpResponse::Conflict().body("An addressbook already exists at this URI"));
|
return Ok((
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
"An addressbook already exists at this URI",
|
||||||
|
)
|
||||||
|
.into_response());
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
// some other error
|
// some other error
|
||||||
@@ -82,17 +88,8 @@ pub async fn route_mkcol<AS: AddressbookStore>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match store.insert_addressbook(addressbook).await {
|
addr_store.insert_addressbook(addressbook).await?;
|
||||||
// TODO: The spec says we should return a mkcol-response.
|
Ok(StatusCode::CREATED.into_response())
|
||||||
// However, it works without one but breaks on iPadOS when using an empty one :)
|
|
||||||
Ok(()) => Ok(HttpResponse::Created()
|
|
||||||
.insert_header(("Cache-Control", "no-cache"))
|
|
||||||
.body("")),
|
|
||||||
Err(err) => {
|
|
||||||
dbg!(err.to_string());
|
|
||||||
Err(err.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
pub mod get;
|
||||||
pub mod mkcol;
|
pub mod mkcol;
|
||||||
pub mod post;
|
pub mod post;
|
||||||
|
pub mod put;
|
||||||
pub mod report;
|
pub mod report;
|
||||||
|
|||||||
@@ -1,32 +1,40 @@
|
|||||||
use crate::Error;
|
use crate::Error;
|
||||||
use actix_web::http::header;
|
use crate::addressbook::AddressbookResourceService;
|
||||||
use actix_web::web::{Data, Path};
|
use crate::addressbook::resource::AddressbookResource;
|
||||||
use actix_web::{HttpRequest, HttpResponse};
|
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_dav_push::register::PushRegister;
|
||||||
use rustical_store::auth::User;
|
use rustical_store::auth::Principal;
|
||||||
use rustical_store::{AddressbookStore, Subscription, SubscriptionStore};
|
use rustical_store::{AddressbookStore, Subscription, SubscriptionStore};
|
||||||
use rustical_xml::XmlDocument;
|
use rustical_xml::XmlDocument;
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(store, subscription_store, root_span, req))]
|
#[instrument(skip(resource_service))]
|
||||||
pub async fn route_post<A: AddressbookStore, S: SubscriptionStore>(
|
pub async fn route_post<AS: AddressbookStore, S: SubscriptionStore>(
|
||||||
path: Path<(String, String)>,
|
Path((principal, addr_id)): Path<(String, String)>,
|
||||||
|
user: Principal,
|
||||||
|
State(resource_service): State<AddressbookResourceService<AS, S>>,
|
||||||
body: String,
|
body: String,
|
||||||
user: User,
|
) -> Result<Response, Error> {
|
||||||
store: Data<A>,
|
|
||||||
subscription_store: Data<S>,
|
|
||||||
root_span: RootSpan,
|
|
||||||
req: HttpRequest,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let (principal, addressbook_id) = path.into_inner();
|
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let addressbook = store
|
let addressbook = resource_service
|
||||||
.get_addressbook(&principal, &addressbook_id, false)
|
.addr_store
|
||||||
|
.get_addressbook(&principal, &addr_id, false)
|
||||||
.await?;
|
.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 request = PushRegister::parse_str(&body)?;
|
||||||
let sub_id = uuid::Uuid::new_v4().to_string();
|
let sub_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
|
||||||
@@ -43,7 +51,7 @@ pub async fn route_post<A: AddressbookStore, S: SubscriptionStore>(
|
|||||||
.web_push_subscription
|
.web_push_subscription
|
||||||
.push_resource
|
.push_resource
|
||||||
.to_owned(),
|
.to_owned(),
|
||||||
topic: addressbook.push_topic,
|
topic: addressbook_resource.0.push_topic,
|
||||||
expiration: expires.naive_local(),
|
expiration: expires.naive_local(),
|
||||||
public_key: request
|
public_key: request
|
||||||
.subscription
|
.subscription
|
||||||
@@ -57,15 +65,22 @@ pub async fn route_post<A: AddressbookStore, S: SubscriptionStore>(
|
|||||||
.ty,
|
.ty,
|
||||||
auth_secret: request.subscription.web_push_subscription.auth_secret,
|
auth_secret: request.subscription.web_push_subscription.auth_secret,
|
||||||
};
|
};
|
||||||
subscription_store.upsert_subscription(subscription).await?;
|
resource_service
|
||||||
|
.sub_store
|
||||||
|
.upsert_subscription(subscription)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let location = req
|
// TODO: make nicer
|
||||||
.resource_map()
|
let location = format!("/push_subscription/{sub_id}");
|
||||||
.url_for(&req, "subscription", &[sub_id])
|
Ok((
|
||||||
.unwrap();
|
StatusCode::CREATED,
|
||||||
|
HeaderMap::from_iter([
|
||||||
Ok(HttpResponse::Created()
|
(header::LOCATION, HeaderValue::from_str(&location).unwrap()),
|
||||||
.append_header((header::LOCATION, location.to_string()))
|
(
|
||||||
.append_header((header::EXPIRES, expires.to_rfc2822()))
|
header::EXPIRES,
|
||||||
.finish())
|
HeaderValue::from_str(&expires.to_rfc2822()).unwrap(),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.into_response())
|
||||||
}
|
}
|
||||||
|
|||||||
47
crates/carddav/src/addressbook/methods/put.rs
Normal file
47
crates/carddav/src/addressbook/methods/put.rs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
use crate::Error;
|
||||||
|
use crate::addressbook::AddressbookResourceService;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::{
|
||||||
|
extract::{Path, State},
|
||||||
|
response::Response,
|
||||||
|
};
|
||||||
|
use http::StatusCode;
|
||||||
|
use ical::VcardParser;
|
||||||
|
use rustical_ical::AddressObject;
|
||||||
|
use rustical_store::Addressbook;
|
||||||
|
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: Principal,
|
||||||
|
body: String,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
|
if !user.is_principal(&principal) {
|
||||||
|
return Err(Error::Unauthorized);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut objects = vec![];
|
||||||
|
for object in VcardParser::new(body.as_bytes()) {
|
||||||
|
let object = object.map_err(rustical_ical::Error::from)?;
|
||||||
|
objects.push(AddressObject::try_from(object)?);
|
||||||
|
}
|
||||||
|
|
||||||
|
let addressbook = Addressbook {
|
||||||
|
id: addressbook_id.clone(),
|
||||||
|
principal: principal.clone(),
|
||||||
|
displayname: None,
|
||||||
|
description: None,
|
||||||
|
deleted_at: None,
|
||||||
|
synctoken: Default::default(),
|
||||||
|
push_topic: uuid::Uuid::new_v4().to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
addr_store
|
||||||
|
.import_addressbook(principal.clone(), addressbook, objects)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(StatusCode::CREATED.into_response())
|
||||||
|
}
|
||||||
@@ -1,17 +1,16 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Error,
|
Error,
|
||||||
address_object::resource::{AddressObjectPropWrapper, AddressObjectResource},
|
address_object::{
|
||||||
};
|
AddressObjectPropWrapper, AddressObjectPropWrapperName, resource::AddressObjectResource,
|
||||||
use actix_web::{
|
},
|
||||||
HttpRequest,
|
|
||||||
dev::{Path, ResourceDef},
|
|
||||||
http::StatusCode,
|
|
||||||
};
|
};
|
||||||
|
use http::StatusCode;
|
||||||
use rustical_dav::{
|
use rustical_dav::{
|
||||||
resource::Resource,
|
resource::{PrincipalUri, Resource},
|
||||||
xml::{MultistatusElement, PropfindType, multistatus::ResponseElement},
|
xml::{MultistatusElement, PropfindType, multistatus::ResponseElement},
|
||||||
};
|
};
|
||||||
use rustical_store::{AddressObject, AddressbookStore, auth::User};
|
use rustical_ical::AddressObject;
|
||||||
|
use rustical_store::{AddressbookStore, auth::Principal};
|
||||||
use rustical_xml::XmlDeserialize;
|
use rustical_xml::XmlDeserialize;
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||||
@@ -19,7 +18,7 @@ use rustical_xml::XmlDeserialize;
|
|||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
pub struct AddressbookMultigetRequest {
|
pub struct AddressbookMultigetRequest {
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", ty = "untagged")]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV", ty = "untagged")]
|
||||||
pub(crate) prop: PropfindType,
|
pub(crate) prop: PropfindType<AddressObjectPropWrapperName>,
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", flatten)]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV", flatten)]
|
||||||
pub(crate) href: Vec<String>,
|
pub(crate) href: Vec<String>,
|
||||||
}
|
}
|
||||||
@@ -31,54 +30,58 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
|
|||||||
addressbook_id: &str,
|
addressbook_id: &str,
|
||||||
store: &AS,
|
store: &AS,
|
||||||
) -> Result<(Vec<AddressObject>, Vec<String>), Error> {
|
) -> Result<(Vec<AddressObject>, Vec<String>), Error> {
|
||||||
let resource_def = ResourceDef::prefix(path).join(&ResourceDef::new("/{object_id}.vcf"));
|
|
||||||
|
|
||||||
let mut result = vec![];
|
let mut result = vec![];
|
||||||
let mut not_found = vec![];
|
let mut not_found = vec![];
|
||||||
|
|
||||||
for href in &addressbook_multiget.href {
|
for href in &addressbook_multiget.href {
|
||||||
let mut path = Path::new(href.as_str());
|
if let Some(filename) = href.strip_prefix(path) {
|
||||||
if !resource_def.capture_match_info(&mut path) {
|
let filename = filename.trim_start_matches("/");
|
||||||
|
if let Some(object_id) = filename.strip_suffix(".vcf") {
|
||||||
|
match store
|
||||||
|
.get_object(principal, addressbook_id, object_id, false)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(object) => result.push(object),
|
||||||
|
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
|
||||||
|
Err(err) => return Err(err.into()),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
not_found.push(href.to_owned());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
not_found.push(href.to_owned());
|
not_found.push(href.to_owned());
|
||||||
continue;
|
continue;
|
||||||
};
|
}
|
||||||
let object_id = path.get("object_id").unwrap();
|
|
||||||
match store
|
|
||||||
.get_object(principal, addressbook_id, object_id, false)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(object) => result.push(object),
|
|
||||||
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
|
|
||||||
// TODO: Maybe add error handling on a per-object basis
|
|
||||||
Err(err) => return Err(err.into()),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok((result, not_found))
|
Ok((result, not_found))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
|
pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
|
||||||
addr_multiget: &AddressbookMultigetRequest,
|
addr_multiget: &AddressbookMultigetRequest,
|
||||||
props: &[&str],
|
prop: &PropfindType<AddressObjectPropWrapperName>,
|
||||||
req: HttpRequest,
|
path: &str,
|
||||||
user: &User,
|
puri: &impl PrincipalUri,
|
||||||
|
user: &Principal,
|
||||||
principal: &str,
|
principal: &str,
|
||||||
cal_id: &str,
|
cal_id: &str,
|
||||||
addr_store: &AS,
|
addr_store: &AS,
|
||||||
) -> Result<MultistatusElement<AddressObjectPropWrapper, String>, Error> {
|
) -> Result<MultistatusElement<AddressObjectPropWrapper, String>, Error> {
|
||||||
let (objects, not_found) =
|
let (objects, not_found) =
|
||||||
get_objects_addressbook_multiget(addr_multiget, req.path(), principal, cal_id, addr_store)
|
get_objects_addressbook_multiget(addr_multiget, path, principal, cal_id, addr_store)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let mut responses = Vec::new();
|
let mut responses = Vec::new();
|
||||||
for object in objects {
|
for object in objects {
|
||||||
let path = format!("{}/{}.vcf", req.path(), object.get_id());
|
let path = format!("{}/{}.vcf", path, object.get_id());
|
||||||
responses.push(
|
responses.push(
|
||||||
AddressObjectResource {
|
AddressObjectResource {
|
||||||
object,
|
object,
|
||||||
principal: principal.to_owned(),
|
principal: principal.to_owned(),
|
||||||
}
|
}
|
||||||
.propfind(&path, props, user, req.resource_map())?,
|
.propfind(&path, prop, None, puri, user)?,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
use crate::Error;
|
use crate::{
|
||||||
use actix_web::{
|
CardDavPrincipalUri, Error, address_object::AddressObjectPropWrapperName,
|
||||||
HttpRequest, Responder,
|
addressbook::AddressbookResourceService,
|
||||||
web::{Data, Path},
|
|
||||||
};
|
};
|
||||||
use addressbook_multiget::{AddressbookMultigetRequest, handle_addressbook_multiget};
|
use addressbook_multiget::{AddressbookMultigetRequest, handle_addressbook_multiget};
|
||||||
use rustical_dav::xml::{PropElement, PropfindType, sync_collection::SyncCollectionRequest};
|
use axum::{
|
||||||
use rustical_store::{AddressbookStore, auth::User};
|
Extension,
|
||||||
|
extract::{OriginalUri, Path, State},
|
||||||
|
response::IntoResponse,
|
||||||
|
};
|
||||||
|
use rustical_dav::xml::{PropfindType, sync_collection::SyncCollectionRequest};
|
||||||
|
use rustical_store::{AddressbookStore, SubscriptionStore, auth::Principal};
|
||||||
use rustical_xml::{XmlDeserialize, XmlDocument};
|
use rustical_xml::{XmlDeserialize, XmlDocument};
|
||||||
use sync_collection::handle_sync_collection;
|
use sync_collection::handle_sync_collection;
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
@@ -18,53 +22,40 @@ pub(crate) enum ReportRequest {
|
|||||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||||
AddressbookMultiget(AddressbookMultigetRequest),
|
AddressbookMultiget(AddressbookMultigetRequest),
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
SyncCollection(SyncCollectionRequest),
|
SyncCollection(SyncCollectionRequest<AddressObjectPropWrapperName>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ReportRequest {
|
impl ReportRequest {
|
||||||
fn props(&self) -> Vec<&str> {
|
fn props(&self) -> &PropfindType<AddressObjectPropWrapperName> {
|
||||||
let prop_element = match self {
|
match self {
|
||||||
ReportRequest::AddressbookMultiget(AddressbookMultigetRequest { prop, .. }) => prop,
|
ReportRequest::AddressbookMultiget(AddressbookMultigetRequest { prop, .. }) => prop,
|
||||||
ReportRequest::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
|
ReportRequest::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
|
||||||
};
|
|
||||||
|
|
||||||
match prop_element {
|
|
||||||
PropfindType::Allprop => {
|
|
||||||
vec!["allprop"]
|
|
||||||
}
|
|
||||||
PropfindType::Propname => {
|
|
||||||
vec!["propname"]
|
|
||||||
}
|
|
||||||
PropfindType::Prop(PropElement(prop_tags)) => prop_tags
|
|
||||||
.iter()
|
|
||||||
.map(|propname| propname.0.as_str())
|
|
||||||
.collect(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(skip(req, addr_store))]
|
#[instrument(skip(addr_store))]
|
||||||
pub async fn route_report_addressbook<AS: AddressbookStore>(
|
pub async fn route_report_addressbook<AS: AddressbookStore, S: SubscriptionStore>(
|
||||||
path: Path<(String, String)>,
|
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||||
|
user: Principal,
|
||||||
|
OriginalUri(uri): OriginalUri,
|
||||||
|
Extension(puri): Extension<CardDavPrincipalUri>,
|
||||||
|
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||||
body: String,
|
body: String,
|
||||||
user: User,
|
) -> Result<impl IntoResponse, Error> {
|
||||||
req: HttpRequest,
|
|
||||||
addr_store: Data<AS>,
|
|
||||||
) -> Result<impl Responder, Error> {
|
|
||||||
let (principal, addressbook_id) = path.into_inner();
|
|
||||||
if !user.is_principal(&principal) {
|
if !user.is_principal(&principal) {
|
||||||
return Err(Error::Unauthorized);
|
return Err(Error::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let request = ReportRequest::parse_str(&body)?;
|
let request = ReportRequest::parse_str(&body)?;
|
||||||
let props = request.props();
|
|
||||||
|
|
||||||
Ok(match &request {
|
Ok(match &request {
|
||||||
ReportRequest::AddressbookMultiget(addr_multiget) => {
|
ReportRequest::AddressbookMultiget(addr_multiget) => {
|
||||||
handle_addressbook_multiget(
|
handle_addressbook_multiget(
|
||||||
addr_multiget,
|
addr_multiget,
|
||||||
&props,
|
request.props(),
|
||||||
req,
|
uri.path(),
|
||||||
|
&puri,
|
||||||
&user,
|
&user,
|
||||||
&principal,
|
&principal,
|
||||||
&addressbook_id,
|
&addressbook_id,
|
||||||
@@ -75,8 +66,8 @@ pub async fn route_report_addressbook<AS: AddressbookStore>(
|
|||||||
ReportRequest::SyncCollection(sync_collection) => {
|
ReportRequest::SyncCollection(sync_collection) => {
|
||||||
handle_sync_collection(
|
handle_sync_collection(
|
||||||
sync_collection,
|
sync_collection,
|
||||||
&props,
|
uri.path(),
|
||||||
req,
|
&puri,
|
||||||
&user,
|
&user,
|
||||||
&principal,
|
&principal,
|
||||||
&addressbook_id,
|
&addressbook_id,
|
||||||
@@ -89,9 +80,9 @@ pub async fn route_report_addressbook<AS: AddressbookStore>(
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use rustical_dav::xml::{PropElement, Propname, sync_collection::SyncLevel};
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::address_object::AddressObjectPropName;
|
||||||
|
use rustical_dav::xml::{PropElement, sync_collection::SyncLevel};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_xml_sync_collection() {
|
fn test_xml_sync_collection() {
|
||||||
@@ -112,9 +103,12 @@ mod tests {
|
|||||||
ReportRequest::SyncCollection(SyncCollectionRequest {
|
ReportRequest::SyncCollection(SyncCollectionRequest {
|
||||||
sync_token: "".to_owned(),
|
sync_token: "".to_owned(),
|
||||||
sync_level: SyncLevel::One,
|
sync_level: SyncLevel::One,
|
||||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![Propname(
|
prop: rustical_dav::xml::PropfindType::Prop(PropElement(
|
||||||
"getetag".to_owned()
|
vec![AddressObjectPropWrapperName::AddressObject(
|
||||||
)])),
|
AddressObjectPropName::Getetag
|
||||||
|
)],
|
||||||
|
vec![]
|
||||||
|
)),
|
||||||
limit: None
|
limit: None
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -137,9 +131,13 @@ mod tests {
|
|||||||
report_request,
|
report_request,
|
||||||
ReportRequest::AddressbookMultiget(AddressbookMultigetRequest {
|
ReportRequest::AddressbookMultiget(AddressbookMultigetRequest {
|
||||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
||||||
Propname("getetag".to_owned()),
|
AddressObjectPropWrapperName::AddressObject(
|
||||||
Propname("address-data".to_owned())
|
AddressObjectPropName::Getetag
|
||||||
])),
|
),
|
||||||
|
AddressObjectPropWrapperName::AddressObject(
|
||||||
|
AddressObjectPropName::AddressData
|
||||||
|
),
|
||||||
|
], vec![])),
|
||||||
href: vec![
|
href: vec![
|
||||||
"/carddav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
"/carddav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,25 +1,27 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Error,
|
Error,
|
||||||
address_object::resource::{AddressObjectPropWrapper, AddressObjectResource},
|
address_object::{
|
||||||
|
AddressObjectPropWrapper, AddressObjectPropWrapperName, resource::AddressObjectResource,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use actix_web::{HttpRequest, http::StatusCode};
|
use http::StatusCode;
|
||||||
use rustical_dav::{
|
use rustical_dav::{
|
||||||
resource::Resource,
|
resource::{PrincipalUri, Resource},
|
||||||
xml::{
|
xml::{
|
||||||
MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest,
|
MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use rustical_store::{
|
use rustical_store::{
|
||||||
AddressbookStore,
|
AddressbookStore,
|
||||||
auth::User,
|
auth::Principal,
|
||||||
synctoken::{format_synctoken, parse_synctoken},
|
synctoken::{format_synctoken, parse_synctoken},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn handle_sync_collection<AS: AddressbookStore>(
|
pub async fn handle_sync_collection<AS: AddressbookStore>(
|
||||||
sync_collection: &SyncCollectionRequest,
|
sync_collection: &SyncCollectionRequest<AddressObjectPropWrapperName>,
|
||||||
props: &[&str],
|
path: &str,
|
||||||
req: HttpRequest,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
principal: &str,
|
principal: &str,
|
||||||
addressbook_id: &str,
|
addressbook_id: &str,
|
||||||
addr_store: &AS,
|
addr_store: &AS,
|
||||||
@@ -31,22 +33,18 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
|
|||||||
|
|
||||||
let mut responses = Vec::new();
|
let mut responses = Vec::new();
|
||||||
for object in new_objects {
|
for object in new_objects {
|
||||||
let path = format!(
|
let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object.get_id());
|
||||||
"{}/{}.vcf",
|
|
||||||
req.path().trim_end_matches('/'),
|
|
||||||
object.get_id()
|
|
||||||
);
|
|
||||||
responses.push(
|
responses.push(
|
||||||
AddressObjectResource {
|
AddressObjectResource {
|
||||||
object,
|
object,
|
||||||
principal: principal.to_owned(),
|
principal: principal.to_owned(),
|
||||||
}
|
}
|
||||||
.propfind(&path, props, user, req.resource_map())?,
|
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
for object_id in deleted_objects {
|
for object_id in deleted_objects {
|
||||||
let path = format!("{}/{}.vcf", req.path().trim_end_matches('/'), object_id);
|
let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object_id);
|
||||||
responses.push(ResponseElement {
|
responses.push(ResponseElement {
|
||||||
href: path,
|
href: path,
|
||||||
status: Some(StatusCode::NOT_FOUND),
|
status: Some(StatusCode::NOT_FOUND),
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
pub mod methods;
|
pub mod methods;
|
||||||
pub mod prop;
|
pub mod prop;
|
||||||
pub mod resource;
|
pub mod resource;
|
||||||
|
mod service;
|
||||||
|
pub use service::*;
|
||||||
|
|||||||
@@ -1,4 +1,33 @@
|
|||||||
use rustical_xml::XmlSerialize;
|
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 {
|
||||||
|
// 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_DAV", skip_deserializing)]
|
||||||
|
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
|
MaxResourceSize(i64),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
|
#[xml(unit_variants_ident = "AddressbookPropWrapperName", untagged)]
|
||||||
|
pub enum AddressbookPropWrapper {
|
||||||
|
Addressbook(AddressbookProp),
|
||||||
|
SyncToken(SyncTokenExtensionProp),
|
||||||
|
DavPush(DavPushExtensionProp),
|
||||||
|
Common(CommonPropertiesProp),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||||
pub struct AddressDataType {
|
pub struct AddressDataType {
|
||||||
@@ -31,37 +60,10 @@ impl Default for SupportedAddressData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
|
||||||
pub enum ReportMethod {
|
pub enum ReportMethod {
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||||
AddressbookMultiget,
|
AddressbookMultiget,
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||||
SyncCollection,
|
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,73 +1,26 @@
|
|||||||
use super::methods::mkcol::route_mkcol;
|
use super::prop::SupportedAddressData;
|
||||||
use super::methods::post::route_post;
|
|
||||||
use super::methods::report::route_report_addressbook;
|
|
||||||
use super::prop::{SupportedAddressData, SupportedReportSet};
|
|
||||||
use crate::Error;
|
use crate::Error;
|
||||||
use crate::address_object::resource::AddressObjectResource;
|
use crate::addressbook::prop::{
|
||||||
use crate::principal::PrincipalResource;
|
AddressbookProp, AddressbookPropName, AddressbookPropWrapper, AddressbookPropWrapperName,
|
||||||
use actix_web::dev::ResourceMap;
|
|
||||||
use actix_web::http::Method;
|
|
||||||
use actix_web::web;
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use derive_more::derive::{From, Into};
|
|
||||||
use rustical_dav::extensions::{
|
|
||||||
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
|
|
||||||
};
|
};
|
||||||
|
use derive_more::derive::{From, Into};
|
||||||
|
use rustical_dav::extensions::{CommonPropertiesExtension, SyncTokenExtension};
|
||||||
use rustical_dav::privileges::UserPrivilegeSet;
|
use rustical_dav::privileges::UserPrivilegeSet;
|
||||||
use rustical_dav::resource::{Resource, ResourceService};
|
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, DavPushExtensionProp};
|
use rustical_dav_push::DavPushExtension;
|
||||||
use rustical_store::auth::User;
|
use rustical_store::Addressbook;
|
||||||
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore};
|
use rustical_store::auth::Principal;
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
|
||||||
use std::marker::PhantomData;
|
|
||||||
use std::str::FromStr;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct AddressbookResourceService<AS: AddressbookStore, S: SubscriptionStore> {
|
|
||||||
addr_store: Arc<AS>,
|
|
||||||
__phantom_sub: PhantomData<S>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<A: AddressbookStore, S: SubscriptionStore> AddressbookResourceService<A, S> {
|
|
||||||
pub fn new(addr_store: Arc<A>) -> Self {
|
|
||||||
Self {
|
|
||||||
addr_store,
|
|
||||||
__phantom_sub: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[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")]
|
|
||||||
MaxResourceSize(i64),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "AddressbookPropWrapperName", untagged)]
|
|
||||||
pub enum AddressbookPropWrapper {
|
|
||||||
Addressbook(AddressbookProp),
|
|
||||||
SyncToken(SyncTokenExtensionProp),
|
|
||||||
DavPush(DavPushExtensionProp),
|
|
||||||
Common(CommonPropertiesProp),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, From, Into)]
|
#[derive(Clone, Debug, From, Into)]
|
||||||
pub struct AddressbookResource(pub(crate) Addressbook);
|
pub struct AddressbookResource(pub(crate) Addressbook);
|
||||||
|
|
||||||
|
impl ResourceName for AddressbookResource {
|
||||||
|
fn get_name(&self) -> String {
|
||||||
|
self.0.id.to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl SyncTokenExtension for AddressbookResource {
|
impl SyncTokenExtension for AddressbookResource {
|
||||||
fn get_synctoken(&self) -> String {
|
fn get_synctoken(&self) -> String {
|
||||||
self.0.format_synctoken()
|
self.0.format_synctoken()
|
||||||
@@ -80,14 +33,14 @@ impl DavPushExtension for AddressbookResource {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommonPropertiesExtension for AddressbookResource {
|
|
||||||
type PrincipalResource = PrincipalResource;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resource for AddressbookResource {
|
impl Resource for AddressbookResource {
|
||||||
type Prop = AddressbookPropWrapper;
|
type Prop = AddressbookPropWrapper;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Principal = User;
|
type Principal = Principal;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
fn get_resourcetype(&self) -> Resourcetype {
|
||||||
Resourcetype(&[
|
Resourcetype(&[
|
||||||
@@ -98,21 +51,18 @@ impl Resource for AddressbookResource {
|
|||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
prop: &AddressbookPropWrapperName,
|
prop: &AddressbookPropWrapperName,
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
) -> Result<Self::Prop, Self::Error> {
|
||||||
Ok(match prop {
|
Ok(match prop {
|
||||||
AddressbookPropWrapperName::Addressbook(prop) => {
|
AddressbookPropWrapperName::Addressbook(prop) => {
|
||||||
AddressbookPropWrapper::Addressbook(match prop {
|
AddressbookPropWrapper::Addressbook(match prop {
|
||||||
AddressbookPropName::Displayname => {
|
|
||||||
AddressbookProp::Displayname(self.0.displayname.clone())
|
|
||||||
}
|
|
||||||
AddressbookPropName::MaxResourceSize => {
|
AddressbookPropName::MaxResourceSize => {
|
||||||
AddressbookProp::MaxResourceSize(10000000)
|
AddressbookProp::MaxResourceSize(10000000)
|
||||||
}
|
}
|
||||||
AddressbookPropName::SupportedReportSet => {
|
AddressbookPropName::SupportedReportSet => {
|
||||||
AddressbookProp::SupportedReportSet(SupportedReportSet::default())
|
AddressbookProp::SupportedReportSet(SupportedReportSet::all())
|
||||||
}
|
}
|
||||||
AddressbookPropName::AddressbookDescription => {
|
AddressbookPropName::AddressbookDescription => {
|
||||||
AddressbookProp::AddressbookDescription(self.0.description.to_owned())
|
AddressbookProp::AddressbookDescription(self.0.description.to_owned())
|
||||||
@@ -130,7 +80,7 @@ impl Resource for AddressbookResource {
|
|||||||
AddressbookPropWrapper::DavPush(<Self as DavPushExtension>::get_prop(self, prop)?)
|
AddressbookPropWrapper::DavPush(<Self as DavPushExtension>::get_prop(self, prop)?)
|
||||||
}
|
}
|
||||||
AddressbookPropWrapperName::Common(prop) => AddressbookPropWrapper::Common(
|
AddressbookPropWrapperName::Common(prop) => AddressbookPropWrapper::Common(
|
||||||
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?,
|
CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -138,10 +88,6 @@ impl Resource for AddressbookResource {
|
|||||||
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
|
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
|
||||||
match prop {
|
match prop {
|
||||||
AddressbookPropWrapper::Addressbook(prop) => match prop {
|
AddressbookPropWrapper::Addressbook(prop) => match prop {
|
||||||
AddressbookProp::Displayname(displayname) => {
|
|
||||||
self.0.displayname = displayname;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
AddressbookProp::AddressbookDescription(description) => {
|
AddressbookProp::AddressbookDescription(description) => {
|
||||||
self.0.description = description;
|
self.0.description = description;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -162,10 +108,6 @@ impl Resource for AddressbookResource {
|
|||||||
) -> Result<(), rustical_dav::Error> {
|
) -> Result<(), rustical_dav::Error> {
|
||||||
match prop {
|
match prop {
|
||||||
AddressbookPropWrapperName::Addressbook(prop) => match prop {
|
AddressbookPropWrapperName::Addressbook(prop) => match prop {
|
||||||
AddressbookPropName::Displayname => {
|
|
||||||
self.0.displayname = None;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
AddressbookPropName::AddressbookDescription => {
|
AddressbookPropName::AddressbookDescription => {
|
||||||
self.0.description = None;
|
self.0.description = None;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -184,88 +126,21 @@ 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> {
|
fn get_owner(&self) -> Option<&str> {
|
||||||
Some(&self.0.principal)
|
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(
|
Ok(UserPrivilegeSet::owner_only(
|
||||||
user.is_principal(&self.0.principal),
|
user.is_principal(&self.0.principal),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
|
|
||||||
for AddressbookResourceService<AS, S>
|
|
||||||
{
|
|
||||||
type MemberType = AddressObjectResource;
|
|
||||||
type PathComponents = (String, String); // principal, addressbook_id
|
|
||||||
type Resource = AddressbookResource;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
async fn get_resource(
|
|
||||||
&self,
|
|
||||||
(principal, addressbook_id): &Self::PathComponents,
|
|
||||||
) -> Result<Self::Resource, Error> {
|
|
||||||
let addressbook = self
|
|
||||||
.addr_store
|
|
||||||
.get_addressbook(principal, addressbook_id, false)
|
|
||||||
.await
|
|
||||||
.map_err(|_e| Error::NotFound)?;
|
|
||||||
Ok(addressbook.into())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_members(
|
|
||||||
&self,
|
|
||||||
(principal, addressbook_id): &Self::PathComponents,
|
|
||||||
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
|
|
||||||
Ok(self
|
|
||||||
.addr_store
|
|
||||||
.get_objects(principal, addressbook_id)
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.map(|object| {
|
|
||||||
(
|
|
||||||
format!("{}.vcf", object.get_id()),
|
|
||||||
AddressObjectResource {
|
|
||||||
object,
|
|
||||||
principal: principal.to_owned(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn save_resource(
|
|
||||||
&self,
|
|
||||||
(principal, addressbook_id): &Self::PathComponents,
|
|
||||||
file: Self::Resource,
|
|
||||||
) -> Result<(), Self::Error> {
|
|
||||||
self.addr_store
|
|
||||||
.update_addressbook(principal.to_owned(), addressbook_id.to_owned(), file.into())
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_resource(
|
|
||||||
&self,
|
|
||||||
(principal, addressbook_id): &Self::PathComponents,
|
|
||||||
use_trashbin: bool,
|
|
||||||
) -> Result<(), Self::Error> {
|
|
||||||
self.addr_store
|
|
||||||
.delete_addressbook(principal, addressbook_id, use_trashbin)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
|
|
||||||
let mkcol_method = web::method(Method::from_str("MKCOL").unwrap());
|
|
||||||
let report_method = web::method(Method::from_str("REPORT").unwrap());
|
|
||||||
res.route(mkcol_method.to(route_mkcol::<AS>))
|
|
||||||
.route(report_method.to(route_report_addressbook::<AS>))
|
|
||||||
.post(route_post::<AS, S>)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
155
crates/carddav/src/addressbook/service.rs
Normal file
155
crates/carddav/src/addressbook/service.rs
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
use super::methods::mkcol::route_mkcol;
|
||||||
|
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};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use axum::Router;
|
||||||
|
use axum::extract::Request;
|
||||||
|
use axum::handler::Handler;
|
||||||
|
use axum::response::Response;
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||||
|
use rustical_store::auth::Principal;
|
||||||
|
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||||
|
use std::convert::Infallible;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tower::Service;
|
||||||
|
|
||||||
|
pub struct AddressbookResourceService<AS: AddressbookStore, S: SubscriptionStore> {
|
||||||
|
pub(crate) addr_store: Arc<AS>,
|
||||||
|
pub(crate) sub_store: Arc<S>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: AddressbookStore, S: SubscriptionStore> AddressbookResourceService<A, S> {
|
||||||
|
pub fn new(addr_store: Arc<A>, sub_store: Arc<S>) -> Self {
|
||||||
|
Self {
|
||||||
|
addr_store,
|
||||||
|
sub_store,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: AddressbookStore, S: SubscriptionStore> Clone for AddressbookResourceService<A, S> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
addr_store: self.addr_store.clone(),
|
||||||
|
sub_store: self.sub_store.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
|
||||||
|
for AddressbookResourceService<AS, S>
|
||||||
|
{
|
||||||
|
type MemberType = AddressObjectResource;
|
||||||
|
type PathComponents = (String, String); // principal, addressbook_id
|
||||||
|
type Resource = AddressbookResource;
|
||||||
|
type Error = Error;
|
||||||
|
type Principal = Principal;
|
||||||
|
type PrincipalUri = CardDavPrincipalUri;
|
||||||
|
|
||||||
|
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, show_deleted)
|
||||||
|
.await
|
||||||
|
.map_err(|_e| Error::NotFound)?;
|
||||||
|
Ok(addressbook.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_members(
|
||||||
|
&self,
|
||||||
|
(principal, addressbook_id): &Self::PathComponents,
|
||||||
|
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||||
|
Ok(self
|
||||||
|
.addr_store
|
||||||
|
.get_objects(principal, addressbook_id)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(|object| AddressObjectResource {
|
||||||
|
object,
|
||||||
|
principal: principal.to_owned(),
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn save_resource(
|
||||||
|
&self,
|
||||||
|
(principal, addressbook_id): &Self::PathComponents,
|
||||||
|
file: Self::Resource,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
self.addr_store
|
||||||
|
.update_addressbook(principal.to_owned(), addressbook_id.to_owned(), file.into())
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_resource(
|
||||||
|
&self,
|
||||||
|
(principal, addressbook_id): &Self::PathComponents,
|
||||||
|
use_trashbin: bool,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
self.addr_store
|
||||||
|
.delete_addressbook(principal, addressbook_id, use_trashbin)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn axum_router<State: Send + Sync + Clone + 'static>(self) -> Router<State> {
|
||||||
|
Router::new()
|
||||||
|
.nest(
|
||||||
|
"/{object_id}",
|
||||||
|
AddressObjectResourceService::new(self.addr_store.clone()).axum_router(),
|
||||||
|
)
|
||||||
|
.route_service("/", self.axum_service())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<AS: AddressbookStore, S: SubscriptionStore> AxumMethods for AddressbookResourceService<AS, S> {
|
||||||
|
fn report() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(route_report_addressbook::<AS, S>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(route_get::<AS, S>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mkcol() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||||
|
Some(|state, req| {
|
||||||
|
let mut service = Handler::with_state(route_mkcol::<AS, S>, state);
|
||||||
|
Box::pin(Service::call(&mut service, req))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
use actix_web::{HttpResponse, http::StatusCode};
|
use axum::response::IntoResponse;
|
||||||
|
use http::StatusCode;
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
@@ -23,16 +24,17 @@ pub enum Error {
|
|||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
XmlDecodeError(#[from] rustical_xml::XmlError),
|
XmlDecodeError(#[from] rustical_xml::XmlError),
|
||||||
|
|
||||||
|
#[error(transparent)]
|
||||||
|
IcalError(#[from] rustical_ical::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl actix_web::ResponseError for Error {
|
impl Error {
|
||||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
pub fn status_code(&self) -> StatusCode {
|
||||||
match self {
|
match self {
|
||||||
Error::StoreError(err) => match err {
|
Error::StoreError(err) => match err {
|
||||||
rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
|
rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
|
||||||
rustical_store::Error::InvalidData(_) => StatusCode::BAD_REQUEST,
|
|
||||||
rustical_store::Error::AlreadyExists => StatusCode::CONFLICT,
|
rustical_store::Error::AlreadyExists => StatusCode::CONFLICT,
|
||||||
rustical_store::Error::ParserError(_) => StatusCode::BAD_REQUEST,
|
|
||||||
rustical_store::Error::ReadOnly => StatusCode::FORBIDDEN,
|
rustical_store::Error::ReadOnly => StatusCode::FORBIDDEN,
|
||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
},
|
},
|
||||||
@@ -42,13 +44,13 @@ impl actix_web::ResponseError for Error {
|
|||||||
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
|
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
|
||||||
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
|
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
Error::NotFound => StatusCode::NOT_FOUND,
|
Error::NotFound => StatusCode::NOT_FOUND,
|
||||||
}
|
Self::IcalError(err) => err.status_code(),
|
||||||
}
|
|
||||||
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
|
|
||||||
error!("Error: {self}");
|
|
||||||
match self {
|
|
||||||
Error::DavError(err) => err.error_response(),
|
|
||||||
_ => HttpResponse::build(self.status_code()).body(self.to_string()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for Error {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
(self.status_code(), self.to_string()).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,22 +1,15 @@
|
|||||||
use actix_web::{
|
use axum::response::Redirect;
|
||||||
HttpResponse,
|
use axum::routing::any;
|
||||||
dev::{HttpServiceFactory, ServiceResponse},
|
use axum::{Extension, Router};
|
||||||
http::{
|
use derive_more::Constructor;
|
||||||
Method, StatusCode,
|
|
||||||
header::{self, HeaderName, HeaderValue},
|
|
||||||
},
|
|
||||||
middleware::{ErrorHandlerResponse, ErrorHandlers},
|
|
||||||
web::{self, Data},
|
|
||||||
};
|
|
||||||
use address_object::resource::AddressObjectResourceService;
|
|
||||||
use addressbook::resource::AddressbookResourceService;
|
|
||||||
pub use error::Error;
|
pub use error::Error;
|
||||||
use principal::{PrincipalResource, PrincipalResourceService};
|
use principal::PrincipalResourceService;
|
||||||
use rustical_dav::resource::{NamedRoute, ResourceService};
|
use rustical_dav::resource::{PrincipalUri, ResourceService};
|
||||||
use rustical_dav::resources::RootResourceService;
|
use rustical_dav::resources::RootResourceService;
|
||||||
|
use rustical_store::auth::middleware::AuthenticationLayer;
|
||||||
use rustical_store::{
|
use rustical_store::{
|
||||||
AddressbookStore, SubscriptionStore,
|
AddressbookStore, SubscriptionStore,
|
||||||
auth::{AuthenticationMiddleware, AuthenticationProvider, User},
|
auth::{AuthenticationProvider, Principal},
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -25,61 +18,41 @@ pub mod addressbook;
|
|||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod principal;
|
pub mod principal;
|
||||||
|
|
||||||
pub fn carddav_service<AP: AuthenticationProvider, A: AddressbookStore, S: SubscriptionStore>(
|
#[derive(Debug, Clone, Constructor)]
|
||||||
|
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!("{}{}/", self.principal_collection(), principal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn carddav_router<AP: AuthenticationProvider, A: AddressbookStore, S: SubscriptionStore>(
|
||||||
|
prefix: &'static str,
|
||||||
auth_provider: Arc<AP>,
|
auth_provider: Arc<AP>,
|
||||||
store: Arc<A>,
|
store: Arc<A>,
|
||||||
subscription_store: Arc<S>,
|
subscription_store: Arc<S>,
|
||||||
) -> impl HttpServiceFactory {
|
) -> Router {
|
||||||
web::scope("")
|
let principal_service = PrincipalResourceService::new(
|
||||||
.wrap(AuthenticationMiddleware::new(auth_provider.clone()))
|
store.clone(),
|
||||||
.wrap(
|
auth_provider.clone(),
|
||||||
ErrorHandlers::new().handler(StatusCode::METHOD_NOT_ALLOWED, |res| {
|
subscription_store.clone(),
|
||||||
Ok(ErrorHandlerResponse::Response(
|
);
|
||||||
if res.request().method() == Method::OPTIONS {
|
Router::new()
|
||||||
let mut response = HttpResponse::Ok();
|
.nest(
|
||||||
response.insert_header((
|
prefix,
|
||||||
HeaderName::from_static("dav"),
|
RootResourceService::<_, Principal, CardDavPrincipalUri>::new(
|
||||||
// https://datatracker.ietf.org/doc/html/rfc4918#section-18
|
principal_service.clone(),
|
||||||
HeaderValue::from_static(
|
)
|
||||||
"1, 3, access-control, addressbook, extended-mkcol, webdav-push",
|
.axum_router()
|
||||||
),
|
.layer(AuthenticationLayer::new(auth_provider))
|
||||||
));
|
.layer(Extension(CardDavPrincipalUri(prefix))),
|
||||||
|
|
||||||
if let Some(allow) = res.headers().get(header::ALLOW) {
|
|
||||||
response.insert_header((header::ALLOW, allow.to_owned()));
|
|
||||||
}
|
|
||||||
ServiceResponse::new(res.into_parts().0, response.finish())
|
|
||||||
.map_into_right_body()
|
|
||||||
} else {
|
|
||||||
res.map_into_left_body()
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}),
|
|
||||||
)
|
)
|
||||||
.app_data(Data::from(store.clone()))
|
.route(
|
||||||
.app_data(Data::from(subscription_store))
|
"/.well-known/carddav",
|
||||||
.service(RootResourceService::<PrincipalResource, User>::default().actix_resource())
|
any(async || Redirect::permanent(prefix)),
|
||||||
.service(
|
|
||||||
web::scope("/principal").service(
|
|
||||||
web::scope("/{principal}")
|
|
||||||
.service(
|
|
||||||
PrincipalResourceService::new(store.clone(), auth_provider)
|
|
||||||
.actix_resource()
|
|
||||||
.name(PrincipalResource::route_name()),
|
|
||||||
)
|
|
||||||
.service(
|
|
||||||
web::scope("/{addressbook_id}")
|
|
||||||
.service(
|
|
||||||
AddressbookResourceService::<A, S>::new(store.clone())
|
|
||||||
.actix_resource(),
|
|
||||||
)
|
|
||||||
.service(
|
|
||||||
web::scope("/{object_id}.vcf").service(
|
|
||||||
AddressObjectResourceService::<A>::new(store.clone())
|
|
||||||
.actix_resource(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,83 +1,37 @@
|
|||||||
use crate::Error;
|
use crate::Error;
|
||||||
use crate::addressbook::resource::AddressbookResource;
|
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||||
use actix_web::dev::ResourceMap;
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp};
|
|
||||||
use rustical_dav::privileges::UserPrivilegeSet;
|
use rustical_dav::privileges::UserPrivilegeSet;
|
||||||
use rustical_dav::resource::{NamedRoute, Resource, ResourceService};
|
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
use rustical_dav::xml::{
|
||||||
use rustical_store::AddressbookStore;
|
GroupMemberSet, GroupMembership, HrefElement, Resourcetype, ResourcetypeInner,
|
||||||
use rustical_store::auth::{AuthenticationProvider, User};
|
};
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
use rustical_store::auth::Principal;
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct PrincipalResourceService<A: AddressbookStore, AP: AuthenticationProvider> {
|
mod service;
|
||||||
addr_store: Arc<A>,
|
pub use service::*;
|
||||||
auth_provider: Arc<AP>,
|
mod prop;
|
||||||
}
|
pub use prop::*;
|
||||||
|
|
||||||
impl<A: AddressbookStore, AP: AuthenticationProvider> PrincipalResourceService<A, AP> {
|
|
||||||
pub fn new(addr_store: Arc<A>, auth_provider: Arc<AP>) -> Self {
|
|
||||||
Self {
|
|
||||||
addr_store,
|
|
||||||
auth_provider,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct PrincipalResource {
|
pub struct PrincipalResource {
|
||||||
principal: User,
|
principal: Principal,
|
||||||
|
members: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
impl ResourceName for PrincipalResource {
|
||||||
pub struct AddressbookHomeSet(#[xml(ty = "untagged", flatten)] Vec<HrefElement>);
|
fn get_name(&self) -> String {
|
||||||
|
self.principal.id.to_owned()
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[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),
|
|
||||||
|
|
||||||
// CardDAV (RFC 6352)
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
|
||||||
AddressbookHomeSet(AddressbookHomeSet),
|
|
||||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
|
||||||
PrincipalAddress(Option<HrefElement>),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, EnumUnitVariants)]
|
|
||||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
|
||||||
pub enum PrincipalPropWrapper {
|
|
||||||
Principal(PrincipalProp),
|
|
||||||
Common(CommonPropertiesProp),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PrincipalResource {
|
|
||||||
pub fn get_principal_url(rmap: &ResourceMap, principal: &str) -> String {
|
|
||||||
Self::get_url(rmap, vec![principal]).unwrap()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NamedRoute for PrincipalResource {
|
|
||||||
fn route_name() -> &'static str {
|
|
||||||
"carddav_principal"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommonPropertiesExtension for PrincipalResource {
|
|
||||||
type PrincipalResource = Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resource for PrincipalResource {
|
impl Resource for PrincipalResource {
|
||||||
type Prop = PrincipalPropWrapper;
|
type Prop = PrincipalPropWrapper;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Principal = User;
|
type Principal = Principal;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
fn get_resourcetype(&self) -> Resourcetype {
|
||||||
Resourcetype(&[
|
Resourcetype(&[
|
||||||
@@ -88,84 +42,72 @@ impl Resource for PrincipalResource {
|
|||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
puri: &impl PrincipalUri,
|
||||||
user: &User,
|
user: &Principal,
|
||||||
prop: &PrincipalPropWrapperName,
|
prop: &PrincipalPropWrapperName,
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
) -> Result<Self::Prop, Self::Error> {
|
||||||
let principal_href = HrefElement::new(Self::get_principal_url(rmap, &self.principal.id));
|
let principal_href = HrefElement::new(puri.principal_uri(&self.principal.id));
|
||||||
|
|
||||||
let home_set = AddressbookHomeSet(
|
|
||||||
user.memberships()
|
|
||||||
.into_iter()
|
|
||||||
.map(|principal| Self::get_url(rmap, vec![principal]).unwrap())
|
|
||||||
.map(HrefElement::new)
|
|
||||||
.collect(),
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(match prop {
|
Ok(match prop {
|
||||||
PrincipalPropWrapperName::Principal(prop) => {
|
PrincipalPropWrapperName::Principal(prop) => {
|
||||||
PrincipalPropWrapper::Principal(match 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::PrincipalUrl => PrincipalProp::PrincipalUrl(principal_href),
|
||||||
PrincipalPropName::AddressbookHomeSet => {
|
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::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())
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
||||||
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?,
|
CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_displayname(&self) -> Option<&str> {
|
||||||
|
Some(
|
||||||
|
self.principal
|
||||||
|
.displayname
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or(&self.principal.id),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn get_owner(&self) -> Option<&str> {
|
fn get_owner(&self) -> Option<&str> {
|
||||||
Some(&self.principal.id)
|
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(
|
Ok(UserPrivilegeSet::owner_only(
|
||||||
user.is_principal(&self.principal.id),
|
user.is_principal(&self.principal.id),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl<A: AddressbookStore, AP: AuthenticationProvider> ResourceService
|
|
||||||
for PrincipalResourceService<A, AP>
|
|
||||||
{
|
|
||||||
type PathComponents = (String,);
|
|
||||||
type MemberType = AddressbookResource;
|
|
||||||
type Resource = PrincipalResource;
|
|
||||||
type Error = Error;
|
|
||||||
type Principal = User;
|
|
||||||
|
|
||||||
async fn get_resource(
|
|
||||||
&self,
|
|
||||||
(principal,): &Self::PathComponents,
|
|
||||||
) -> Result<Self::Resource, Self::Error> {
|
|
||||||
let user = self
|
|
||||||
.auth_provider
|
|
||||||
.get_principal(principal)
|
|
||||||
.await?
|
|
||||||
.ok_or(crate::Error::NotFound)?;
|
|
||||||
Ok(PrincipalResource { principal: user })
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_members(
|
|
||||||
&self,
|
|
||||||
(principal,): &Self::PathComponents,
|
|
||||||
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
|
|
||||||
let addressbooks = self.addr_store.get_addressbooks(principal).await?;
|
|
||||||
Ok(addressbooks
|
|
||||||
.into_iter()
|
|
||||||
.map(|addressbook| (addressbook.id.to_owned(), addressbook.into()))
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
38
crates/carddav/src/principal/prop.rs
Normal file
38
crates/carddav/src/principal/prop.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use rustical_dav::{
|
||||||
|
extensions::CommonPropertiesProp,
|
||||||
|
xml::{GroupMemberSet, GroupMembership, HrefElement},
|
||||||
|
};
|
||||||
|
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||||
|
|
||||||
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||||
|
#[xml(unit_variants_ident = "PrincipalPropName")]
|
||||||
|
pub enum PrincipalProp {
|
||||||
|
// 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")]
|
||||||
|
AddressbookHomeSet(AddressbookHomeSet),
|
||||||
|
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||||
|
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 {
|
||||||
|
Principal(PrincipalProp),
|
||||||
|
Common(CommonPropertiesProp),
|
||||||
|
}
|
||||||
100
crates/carddav/src/principal/service.rs
Normal file
100
crates/carddav/src/principal/service.rs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
use crate::addressbook::AddressbookResourceService;
|
||||||
|
use crate::addressbook::resource::AddressbookResource;
|
||||||
|
use crate::principal::PrincipalResource;
|
||||||
|
use crate::{CardDavPrincipalUri, Error};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use axum::Router;
|
||||||
|
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||||
|
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||||
|
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub struct PrincipalResourceService<
|
||||||
|
A: AddressbookStore,
|
||||||
|
AP: AuthenticationProvider,
|
||||||
|
S: SubscriptionStore,
|
||||||
|
> {
|
||||||
|
addr_store: Arc<A>,
|
||||||
|
auth_provider: Arc<AP>,
|
||||||
|
sub_store: Arc<S>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> Clone
|
||||||
|
for PrincipalResourceService<A, AP, S>
|
||||||
|
{
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
addr_store: self.addr_store.clone(),
|
||||||
|
auth_provider: self.auth_provider.clone(),
|
||||||
|
sub_store: self.sub_store.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore>
|
||||||
|
PrincipalResourceService<A, AP, S>
|
||||||
|
{
|
||||||
|
pub fn new(addr_store: Arc<A>, auth_provider: Arc<AP>, sub_store: Arc<S>) -> Self {
|
||||||
|
Self {
|
||||||
|
addr_store,
|
||||||
|
auth_provider,
|
||||||
|
sub_store,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> ResourceService
|
||||||
|
for PrincipalResourceService<A, AP, S>
|
||||||
|
{
|
||||||
|
type PathComponents = (String,);
|
||||||
|
type MemberType = AddressbookResource;
|
||||||
|
type Resource = PrincipalResource;
|
||||||
|
type Error = Error;
|
||||||
|
type Principal = Principal;
|
||||||
|
type PrincipalUri = CardDavPrincipalUri;
|
||||||
|
|
||||||
|
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||||
|
|
||||||
|
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 {
|
||||||
|
members: self.auth_provider.list_members(&user.id).await?,
|
||||||
|
principal: user,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_members(
|
||||||
|
&self,
|
||||||
|
(principal,): &Self::PathComponents,
|
||||||
|
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||||
|
let addressbooks = self.addr_store.get_addressbooks(principal).await?;
|
||||||
|
Ok(addressbooks
|
||||||
|
.into_iter()
|
||||||
|
.map(AddressbookResource::from)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn axum_router<State: Send + Sync + Clone + 'static>(self) -> Router<State> {
|
||||||
|
Router::new()
|
||||||
|
.nest(
|
||||||
|
"/{addressbook_id}",
|
||||||
|
AddressbookResourceService::new(self.addr_store.clone(), self.sub_store.clone())
|
||||||
|
.axum_router(),
|
||||||
|
)
|
||||||
|
.route_service("/", self.axum_service())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> AxumMethods
|
||||||
|
for PrincipalResourceService<A, AP, S>
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -4,11 +4,15 @@ version.workspace = true
|
|||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
description.workspace = true
|
description.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
license.workspace = true
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
axum.workspace = true
|
||||||
|
tower.workspace = true
|
||||||
|
axum-extra.workspace = true
|
||||||
|
|
||||||
rustical_xml.workspace = true
|
rustical_xml.workspace = true
|
||||||
actix-web.workspace = true
|
|
||||||
async-trait.workspace = true
|
async-trait.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
quick-xml.workspace = true
|
quick-xml.workspace = true
|
||||||
@@ -18,5 +22,9 @@ itertools.workspace = true
|
|||||||
log.workspace = true
|
log.workspace = true
|
||||||
derive_more.workspace = true
|
derive_more.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
tracing-actix-web.workspace = true
|
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
|
http.workspace = true
|
||||||
|
headers.workspace = true
|
||||||
|
strum.workspace = true
|
||||||
|
matchit.workspace = true
|
||||||
|
matchit-serde.workspace = true
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use actix_web::{http::StatusCode, HttpResponse};
|
use http::StatusCode;
|
||||||
use rustical_xml::XmlError;
|
use rustical_xml::XmlError;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
@@ -25,10 +25,16 @@ pub enum Error {
|
|||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
IOError(#[from] std::io::Error),
|
IOError(#[from] std::io::Error),
|
||||||
|
|
||||||
|
#[error("Precondition Failed")]
|
||||||
|
PreconditionFailed,
|
||||||
|
|
||||||
|
#[error("Forbidden")]
|
||||||
|
Forbidden,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl actix_web::error::ResponseError for Error {
|
impl Error {
|
||||||
fn status_code(&self) -> StatusCode {
|
pub fn status_code(&self) -> StatusCode {
|
||||||
match self {
|
match self {
|
||||||
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
|
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
Self::NotFound => StatusCode::NOT_FOUND,
|
Self::NotFound => StatusCode::NOT_FOUND,
|
||||||
@@ -44,17 +50,25 @@ impl actix_web::error::ResponseError for Error {
|
|||||||
_ => StatusCode::BAD_REQUEST,
|
_ => StatusCode::BAD_REQUEST,
|
||||||
},
|
},
|
||||||
Error::PropReadOnly => StatusCode::CONFLICT,
|
Error::PropReadOnly => StatusCode::CONFLICT,
|
||||||
|
Error::PreconditionFailed => StatusCode::PRECONDITION_FAILED,
|
||||||
Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
}
|
Self::Forbidden => StatusCode::FORBIDDEN,
|
||||||
}
|
|
||||||
|
|
||||||
fn error_response(&self) -> HttpResponse {
|
|
||||||
error!("Error: {self}");
|
|
||||||
match self {
|
|
||||||
Error::Unauthorized => HttpResponse::build(self.status_code())
|
|
||||||
.append_header(("WWW-Authenticate", "Basic"))
|
|
||||||
.body(self.to_string()),
|
|
||||||
_ => HttpResponse::build(self.status_code()).body(self.to_string()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl axum::response::IntoResponse for Error {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
use axum::body::Body;
|
||||||
|
|
||||||
|
let mut resp = axum::response::Response::builder().status(self.status_code());
|
||||||
|
if matches!(&self, &Error::Unauthorized) {
|
||||||
|
resp.headers_mut()
|
||||||
|
.expect("This must always work")
|
||||||
|
.insert("WWW-Authenticate", "Basic".parse().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
resp.body(Body::new(self.to_string()))
|
||||||
|
.expect("This should always work")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Principal,
|
Principal,
|
||||||
privileges::UserPrivilegeSet,
|
privileges::UserPrivilegeSet,
|
||||||
resource::{NamedRoute, Resource},
|
resource::{PrincipalUri, Resource},
|
||||||
xml::{HrefElement, Resourcetype},
|
xml::{HrefElement, Resourcetype},
|
||||||
};
|
};
|
||||||
use actix_web::dev::ResourceMap;
|
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumUnitVariants, EnumVariants)]
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, PropName, EnumVariants)]
|
||||||
#[xml(unit_variants_ident = "CommonPropertiesPropName")]
|
#[xml(unit_variants_ident = "CommonPropertiesPropName")]
|
||||||
pub enum CommonPropertiesProp {
|
pub enum CommonPropertiesProp {
|
||||||
// WebDAV (RFC 2518)
|
// WebDAV (RFC 2518)
|
||||||
#[xml(skip_deserializing)]
|
#[xml(skip_deserializing)]
|
||||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||||
Resourcetype(Resourcetype),
|
Resourcetype(Resourcetype),
|
||||||
|
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||||
|
Displayname(Option<String>),
|
||||||
|
|
||||||
// WebDAV Current Principal Extension (RFC 5397)
|
// WebDAV Current Principal Extension (RFC 5397)
|
||||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||||
@@ -28,11 +29,9 @@ pub enum CommonPropertiesProp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub trait CommonPropertiesExtension: Resource {
|
pub trait CommonPropertiesExtension: Resource {
|
||||||
type PrincipalResource: NamedRoute;
|
|
||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
principal_uri: &impl PrincipalUri,
|
||||||
principal: &Self::Principal,
|
principal: &Self::Principal,
|
||||||
prop: &CommonPropertiesPropName,
|
prop: &CommonPropertiesPropName,
|
||||||
) -> Result<CommonPropertiesProp, <Self as Resource>::Error> {
|
) -> Result<CommonPropertiesProp, <Self as Resource>::Error> {
|
||||||
@@ -40,31 +39,37 @@ pub trait CommonPropertiesExtension: Resource {
|
|||||||
CommonPropertiesPropName::Resourcetype => {
|
CommonPropertiesPropName::Resourcetype => {
|
||||||
CommonPropertiesProp::Resourcetype(self.get_resourcetype())
|
CommonPropertiesProp::Resourcetype(self.get_resourcetype())
|
||||||
}
|
}
|
||||||
|
CommonPropertiesPropName::Displayname => {
|
||||||
|
CommonPropertiesProp::Displayname(self.get_displayname().map(|s| s.to_string()))
|
||||||
|
}
|
||||||
CommonPropertiesPropName::CurrentUserPrincipal => {
|
CommonPropertiesPropName::CurrentUserPrincipal => {
|
||||||
CommonPropertiesProp::CurrentUserPrincipal(
|
CommonPropertiesProp::CurrentUserPrincipal(
|
||||||
Self::PrincipalResource::get_url(rmap, [&principal.get_id()])
|
principal_uri.principal_uri(principal.get_id()).into(),
|
||||||
.unwrap()
|
|
||||||
.into(),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
CommonPropertiesPropName::CurrentUserPrivilegeSet => {
|
CommonPropertiesPropName::CurrentUserPrivilegeSet => {
|
||||||
CommonPropertiesProp::CurrentUserPrivilegeSet(self.get_user_privileges(principal)?)
|
CommonPropertiesProp::CurrentUserPrivilegeSet(self.get_user_privileges(principal)?)
|
||||||
}
|
}
|
||||||
CommonPropertiesPropName::Owner => {
|
CommonPropertiesPropName::Owner => CommonPropertiesProp::Owner(
|
||||||
CommonPropertiesProp::Owner(self.get_owner().map(|owner| {
|
self.get_owner()
|
||||||
Self::PrincipalResource::get_url(rmap, [owner])
|
.map(|owner| principal_uri.principal_uri(owner).into()),
|
||||||
.unwrap()
|
),
|
||||||
.into()
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_prop(&self, _prop: CommonPropertiesProp) -> Result<(), crate::Error> {
|
fn set_prop(&mut self, prop: CommonPropertiesProp) -> Result<(), crate::Error> {
|
||||||
Err(crate::Error::PropReadOnly)
|
match prop {
|
||||||
|
CommonPropertiesProp::Displayname(name) => self.set_displayname(name),
|
||||||
|
_ => Err(crate::Error::PropReadOnly),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove_prop(&self, _prop: &CommonPropertiesPropName) -> Result<(), crate::Error> {
|
fn remove_prop(&mut self, prop: &CommonPropertiesPropName) -> Result<(), crate::Error> {
|
||||||
Err(crate::Error::PropReadOnly)
|
match prop {
|
||||||
|
CommonPropertiesPropName::Displayname => self.set_displayname(None),
|
||||||
|
_ => Err(crate::Error::PropReadOnly),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<R: Resource> CommonPropertiesExtension for R {}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||||
|
|
||||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumUnitVariants, EnumVariants)]
|
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, PropName, EnumVariants)]
|
||||||
#[xml(unit_variants_ident = "SyncTokenExtensionPropName")]
|
#[xml(unit_variants_ident = "SyncTokenExtensionPropName")]
|
||||||
pub enum SyncTokenExtensionProp {
|
pub enum SyncTokenExtensionProp {
|
||||||
// Collection Synchronization (RFC 6578)
|
// Collection Synchronization (RFC 6578)
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
use actix_web::{FromRequest, HttpRequest, ResponseError, http::StatusCode};
|
use axum::{
|
||||||
use futures_util::future::{Ready, err, ok};
|
body::Body,
|
||||||
|
extract::{FromRequestParts, OptionalFromRequestParts},
|
||||||
|
response::IntoResponse,
|
||||||
|
};
|
||||||
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlError};
|
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlError};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
@@ -7,9 +10,12 @@ use thiserror::Error;
|
|||||||
#[error("Invalid Depth header")]
|
#[error("Invalid Depth header")]
|
||||||
pub struct InvalidDepthHeader;
|
pub struct InvalidDepthHeader;
|
||||||
|
|
||||||
impl ResponseError for InvalidDepthHeader {
|
impl IntoResponse for InvalidDepthHeader {
|
||||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
fn into_response(self) -> axum::response::Response {
|
||||||
StatusCode::BAD_REQUEST
|
axum::response::Response::builder()
|
||||||
|
.status(axum::http::StatusCode::BAD_REQUEST)
|
||||||
|
.body(Body::empty())
|
||||||
|
.expect("this always works")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,23 +63,32 @@ impl TryFrom<&[u8]> for Depth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromRequest for Depth {
|
impl<S: Send + Sync> OptionalFromRequestParts<S> for Depth {
|
||||||
type Error = InvalidDepthHeader;
|
type Rejection = InvalidDepthHeader;
|
||||||
type Future = Ready<Result<Self, Self::Error>>;
|
|
||||||
|
|
||||||
fn extract(req: &HttpRequest) -> Self::Future {
|
async fn from_request_parts(
|
||||||
if let Some(depth_header) = req.headers().get("Depth") {
|
parts: &mut axum::http::request::Parts,
|
||||||
match depth_header.as_bytes().try_into() {
|
_state: &S,
|
||||||
Ok(depth) => ok(depth),
|
) -> Result<Option<Self>, Self::Rejection> {
|
||||||
Err(e) => err(e),
|
if let Some(depth_header) = parts.headers.get("Depth") {
|
||||||
}
|
Ok(Some(depth_header.as_bytes().try_into()?))
|
||||||
} else {
|
} else {
|
||||||
// default depth
|
Ok(None)
|
||||||
ok(Depth::Zero)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn from_request(req: &HttpRequest, _payload: &mut actix_web::dev::Payload) -> Self::Future {
|
impl<S: Send + Sync> FromRequestParts<S> for Depth {
|
||||||
Self::extract(req)
|
type Rejection = InvalidDepthHeader;
|
||||||
|
|
||||||
|
async fn from_request_parts(
|
||||||
|
parts: &mut axum::http::request::Parts,
|
||||||
|
_state: &S,
|
||||||
|
) -> Result<Self, Self::Rejection> {
|
||||||
|
if let Some(depth_header) = parts.headers.get("Depth") {
|
||||||
|
depth_header.as_bytes().try_into()
|
||||||
|
} else {
|
||||||
|
Ok(Self::Zero)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
use actix_web::{FromRequest, HttpRequest, ResponseError, http::StatusCode};
|
use axum::{body::Body, extract::FromRequestParts, response::IntoResponse};
|
||||||
use futures_util::future::{Ready, err, ok};
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
#[error("Invalid Overwrite header")]
|
#[error("Invalid Overwrite header")]
|
||||||
pub struct InvalidOverwriteHeader;
|
pub struct InvalidOverwriteHeader;
|
||||||
|
|
||||||
impl ResponseError for InvalidOverwriteHeader {
|
impl IntoResponse for InvalidOverwriteHeader {
|
||||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
fn into_response(self) -> axum::response::Response {
|
||||||
StatusCode::BAD_REQUEST
|
axum::response::Response::builder()
|
||||||
|
.status(axum::http::StatusCode::BAD_REQUEST)
|
||||||
|
.body(Body::new("Invalid Overwrite header".to_string()))
|
||||||
|
.expect("this always works")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,6 +27,21 @@ impl Overwrite {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<S: Send + Sync> FromRequestParts<S> for Overwrite {
|
||||||
|
type Rejection = InvalidOverwriteHeader;
|
||||||
|
|
||||||
|
async fn from_request_parts(
|
||||||
|
parts: &mut axum::http::request::Parts,
|
||||||
|
_state: &S,
|
||||||
|
) -> Result<Self, Self::Rejection> {
|
||||||
|
if let Some(overwrite_header) = parts.headers.get("Overwrite") {
|
||||||
|
overwrite_header.as_bytes().try_into()
|
||||||
|
} else {
|
||||||
|
Ok(Self::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl TryFrom<&[u8]> for Overwrite {
|
impl TryFrom<&[u8]> for Overwrite {
|
||||||
type Error = InvalidOverwriteHeader;
|
type Error = InvalidOverwriteHeader;
|
||||||
|
|
||||||
@@ -36,24 +53,3 @@ impl TryFrom<&[u8]> for Overwrite {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromRequest for Overwrite {
|
|
||||||
type Error = InvalidOverwriteHeader;
|
|
||||||
type Future = Ready<Result<Self, Self::Error>>;
|
|
||||||
|
|
||||||
fn extract(req: &HttpRequest) -> Self::Future {
|
|
||||||
if let Some(overwrite_header) = req.headers().get("Overwrite") {
|
|
||||||
match overwrite_header.as_bytes().try_into() {
|
|
||||||
Ok(depth) => ok(depth),
|
|
||||||
Err(e) => err(e),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// default depth
|
|
||||||
ok(Overwrite::F)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_request(req: &HttpRequest, _payload: &mut actix_web::dev::Payload) -> Self::Future {
|
|
||||||
Self::extract(req)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,10 +6,8 @@ pub mod privileges;
|
|||||||
pub mod resource;
|
pub mod resource;
|
||||||
pub mod resources;
|
pub mod resources;
|
||||||
pub mod xml;
|
pub mod xml;
|
||||||
|
|
||||||
use actix_web::FromRequest;
|
|
||||||
pub use error::Error;
|
pub use error::Error;
|
||||||
|
|
||||||
pub trait Principal: std::fmt::Debug + Clone + FromRequest + 'static {
|
pub trait Principal: std::fmt::Debug + Clone + Send + Sync + 'static {
|
||||||
fn get_id(&self) -> &str;
|
fn get_id(&self) -> &str;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
|
use itertools::Itertools;
|
||||||
use quick_xml::name::Namespace;
|
use quick_xml::name::Namespace;
|
||||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||||
use std::collections::{HashMap, HashSet};
|
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 {
|
pub enum UserPrivilege {
|
||||||
Read,
|
Read,
|
||||||
Write,
|
Write,
|
||||||
@@ -15,12 +17,12 @@ pub enum UserPrivilege {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl XmlSerialize for UserPrivilegeSet {
|
impl XmlSerialize for UserPrivilegeSet {
|
||||||
fn serialize<W: std::io::Write>(
|
fn serialize(
|
||||||
&self,
|
&self,
|
||||||
ns: Option<Namespace>,
|
ns: Option<Namespace>,
|
||||||
tag: Option<&[u8]>,
|
tag: Option<&[u8]>,
|
||||||
namespaces: &HashMap<Namespace, &[u8]>,
|
namespaces: &HashMap<Namespace, &[u8]>,
|
||||||
writer: &mut quick_xml::Writer<W>,
|
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||||
) -> std::io::Result<()> {
|
) -> std::io::Result<()> {
|
||||||
#[derive(XmlSerialize)]
|
#[derive(XmlSerialize)]
|
||||||
pub struct FakeUserPrivilegeSet {
|
pub struct FakeUserPrivilegeSet {
|
||||||
@@ -29,12 +31,11 @@ impl XmlSerialize for UserPrivilegeSet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FakeUserPrivilegeSet {
|
FakeUserPrivilegeSet {
|
||||||
privileges: self.privileges.iter().cloned().collect(),
|
privileges: self.privileges.iter().cloned().sorted().collect(),
|
||||||
}
|
}
|
||||||
.serialize(ns, tag, namespaces, writer)
|
.serialize(ns, tag, namespaces, writer)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(refining_impl_trait)]
|
|
||||||
fn attributes<'a>(&self) -> Option<Vec<quick_xml::events::attributes::Attribute<'a>>> {
|
fn attributes<'a>(&self) -> Option<Vec<quick_xml::events::attributes::Attribute<'a>>> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -47,6 +48,12 @@ pub struct UserPrivilegeSet {
|
|||||||
|
|
||||||
impl UserPrivilegeSet {
|
impl UserPrivilegeSet {
|
||||||
pub fn has(&self, privilege: &UserPrivilege) -> bool {
|
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)
|
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 {
|
pub fn read_only() -> Self {
|
||||||
Self {
|
Self {
|
||||||
privileges: HashSet::from([
|
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 {
|
impl<const N: usize> From<[UserPrivilege; N]> for UserPrivilegeSet {
|
||||||
|
|||||||
73
crates/dav/src/resource/axum_methods.rs
Normal file
73
crates/dav/src/resource/axum_methods.rs
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
use axum::{extract::Request, response::Response};
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
use headers::Allow;
|
||||||
|
use http::Method;
|
||||||
|
use std::{convert::Infallible, str::FromStr};
|
||||||
|
|
||||||
|
pub type MethodFunction<State> =
|
||||||
|
fn(State, Request) -> BoxFuture<'static, Result<Response, Infallible>>;
|
||||||
|
|
||||||
|
pub trait AxumMethods: Sized + Send + Sync + 'static {
|
||||||
|
#[inline]
|
||||||
|
fn report() -> Option<MethodFunction<Self>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn get() -> Option<MethodFunction<Self>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn post() -> Option<MethodFunction<Self>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn mkcol() -> Option<MethodFunction<Self>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn mkcalendar() -> Option<MethodFunction<Self>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn put() -> Option<MethodFunction<Self>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn allow_header() -> Allow {
|
||||||
|
let mut allow = vec![
|
||||||
|
Method::from_str("PROPFIND").unwrap(),
|
||||||
|
Method::from_str("PROPPATCH").unwrap(),
|
||||||
|
Method::from_str("COPY").unwrap(),
|
||||||
|
Method::from_str("MOVE").unwrap(),
|
||||||
|
Method::DELETE,
|
||||||
|
Method::OPTIONS,
|
||||||
|
];
|
||||||
|
if Self::report().is_some() {
|
||||||
|
allow.push(Method::from_str("REPORT").unwrap());
|
||||||
|
}
|
||||||
|
if Self::get().is_some() {
|
||||||
|
allow.push(Method::GET);
|
||||||
|
allow.push(Method::HEAD);
|
||||||
|
}
|
||||||
|
if Self::post().is_some() {
|
||||||
|
allow.push(Method::POST);
|
||||||
|
}
|
||||||
|
if Self::mkcol().is_some() {
|
||||||
|
allow.push(Method::from_str("MKCOL").unwrap());
|
||||||
|
}
|
||||||
|
if Self::mkcalendar().is_some() {
|
||||||
|
allow.push(Method::from_str("MKCALENDAR").unwrap());
|
||||||
|
}
|
||||||
|
if Self::put().is_some() {
|
||||||
|
allow.push(Method::PUT);
|
||||||
|
}
|
||||||
|
|
||||||
|
allow.into_iter().collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
120
crates/dav/src/resource/axum_service.rs
Normal file
120
crates/dav/src/resource/axum_service.rs
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
use super::methods::{axum_route_propfind, axum_route_proppatch};
|
||||||
|
use crate::resource::{
|
||||||
|
ResourceService,
|
||||||
|
axum_methods::AxumMethods,
|
||||||
|
methods::{axum_route_copy, axum_route_move},
|
||||||
|
};
|
||||||
|
use axum::{
|
||||||
|
body::Body,
|
||||||
|
extract::FromRequestParts,
|
||||||
|
handler::Handler,
|
||||||
|
http::{Request, Response},
|
||||||
|
response::IntoResponse,
|
||||||
|
};
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
use headers::HeaderMapExt;
|
||||||
|
use http::{HeaderValue, StatusCode};
|
||||||
|
use std::convert::Infallible;
|
||||||
|
use tower::Service;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AxumService<RS: ResourceService + AxumMethods> {
|
||||||
|
resource_service: RS,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<RS: ResourceService + AxumMethods> AxumService<RS> {
|
||||||
|
pub fn new(resource_service: RS) -> Self {
|
||||||
|
Self { resource_service }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<RS: ResourceService + AxumMethods + Clone + Send + Sync> Service<Request<Body>>
|
||||||
|
for AxumService<RS>
|
||||||
|
where
|
||||||
|
RS::Error: IntoResponse + Send + Sync + 'static,
|
||||||
|
RS::Principal: FromRequestParts<RS>,
|
||||||
|
{
|
||||||
|
type Error = Infallible;
|
||||||
|
type Response = Response<Body>;
|
||||||
|
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn poll_ready(
|
||||||
|
&mut self,
|
||||||
|
_cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<(), Self::Error>> {
|
||||||
|
Ok(()).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn call(&mut self, req: Request<Body>) -> Self::Future {
|
||||||
|
use crate::resource::methods::axum_route_delete;
|
||||||
|
let mut propfind_service =
|
||||||
|
Handler::with_state(axum_route_propfind::<RS>, self.resource_service.clone());
|
||||||
|
let mut proppatch_service =
|
||||||
|
Handler::with_state(axum_route_proppatch::<RS>, self.resource_service.clone());
|
||||||
|
let mut delete_service =
|
||||||
|
Handler::with_state(axum_route_delete::<RS>, self.resource_service.clone());
|
||||||
|
let mut move_service =
|
||||||
|
Handler::with_state(axum_route_move::<RS>, self.resource_service.clone());
|
||||||
|
let mut copy_service =
|
||||||
|
Handler::with_state(axum_route_copy::<RS>, self.resource_service.clone());
|
||||||
|
let mut options_service = Handler::with_state(route_options::<RS>, ());
|
||||||
|
match req.method().as_str() {
|
||||||
|
"PROPFIND" => return Box::pin(Service::call(&mut propfind_service, req)),
|
||||||
|
"PROPPATCH" => return Box::pin(Service::call(&mut proppatch_service, req)),
|
||||||
|
"DELETE" => return Box::pin(Service::call(&mut delete_service, req)),
|
||||||
|
"OPTIONS" => return Box::pin(Service::call(&mut options_service, req)),
|
||||||
|
"MOVE" => return Box::pin(Service::call(&mut move_service, req)),
|
||||||
|
"COPY" => return Box::pin(Service::call(&mut copy_service, req)),
|
||||||
|
"REPORT" => {
|
||||||
|
if let Some(svc) = RS::report() {
|
||||||
|
return svc(self.resource_service.clone(), req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"GET" | "HEAD" => {
|
||||||
|
if let Some(svc) = RS::get() {
|
||||||
|
return svc(self.resource_service.clone(), req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"POST" => {
|
||||||
|
if let Some(svc) = RS::post() {
|
||||||
|
return svc(self.resource_service.clone(), req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"MKCOL" => {
|
||||||
|
if let Some(svc) = RS::mkcol() {
|
||||||
|
return svc(self.resource_service.clone(), req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"MKCALENDAR" => {
|
||||||
|
if let Some(svc) = RS::mkcalendar() {
|
||||||
|
return svc(self.resource_service.clone(), req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"PUT" => {
|
||||||
|
if let Some(svc) = RS::put() {
|
||||||
|
return svc(self.resource_service.clone(), req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
};
|
||||||
|
Box::pin(async move {
|
||||||
|
Ok(Response::builder()
|
||||||
|
.status(StatusCode::METHOD_NOT_ALLOWED)
|
||||||
|
.body(Body::from("Method not allowed"))
|
||||||
|
.unwrap())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
headers.typed_insert(RS::allow_header());
|
||||||
|
resp.body(Body::empty()).unwrap()
|
||||||
|
}
|
||||||
54
crates/dav/src/resource/methods/copy.rs
Normal file
54
crates/dav/src/resource/methods/copy.rs
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
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,))]
|
||||||
|
pub(crate) async fn axum_route_copy<R: ResourceService>(
|
||||||
|
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> {
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,50 +2,72 @@ use crate::Error;
|
|||||||
use crate::privileges::UserPrivilege;
|
use crate::privileges::UserPrivilege;
|
||||||
use crate::resource::Resource;
|
use crate::resource::Resource;
|
||||||
use crate::resource::ResourceService;
|
use crate::resource::ResourceService;
|
||||||
use actix_web::HttpRequest;
|
use axum::extract::{Path, State};
|
||||||
use actix_web::HttpResponse;
|
use axum_extra::TypedHeader;
|
||||||
use actix_web::Responder;
|
use headers::{IfMatch, IfNoneMatch};
|
||||||
use actix_web::http::header::IfMatch;
|
use http::HeaderMap;
|
||||||
use actix_web::http::header::IfNoneMatch;
|
|
||||||
use actix_web::web;
|
|
||||||
use actix_web::web::Data;
|
|
||||||
use actix_web::web::Path;
|
|
||||||
use tracing::instrument;
|
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
|
pub(crate) async fn axum_route_delete<R: ResourceService>(
|
||||||
pub async fn route_delete<R: ResourceService>(
|
Path(path): Path<R::PathComponents>,
|
||||||
path: Path<R::PathComponents>,
|
State(resource_service): State<R>,
|
||||||
req: HttpRequest,
|
|
||||||
principal: R::Principal,
|
principal: R::Principal,
|
||||||
resource_service: Data<R>,
|
mut if_match: Option<TypedHeader<IfMatch>>,
|
||||||
root_span: RootSpan,
|
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
|
||||||
if_match: web::Header<IfMatch>,
|
header_map: HeaderMap,
|
||||||
if_none_match: web::Header<IfNoneMatch>,
|
) -> Result<(), R::Error> {
|
||||||
) -> Result<impl Responder, R::Error> {
|
// https://github.com/hyperium/headers/issues/204
|
||||||
let no_trash = req
|
if !header_map.contains_key("If-Match") {
|
||||||
.headers()
|
if_match = None;
|
||||||
|
}
|
||||||
|
if !header_map.contains_key("If-None-Match") {
|
||||||
|
if_none_match = None;
|
||||||
|
}
|
||||||
|
let no_trash = header_map
|
||||||
.get("X-No-Trashbin")
|
.get("X-No-Trashbin")
|
||||||
.map(|val| matches!(val.to_str(), Ok("1")))
|
.map(|val| matches!(val.to_str(), Ok("1")))
|
||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
|
route_delete(
|
||||||
|
&path,
|
||||||
|
&principal,
|
||||||
|
&resource_service,
|
||||||
|
no_trash,
|
||||||
|
if_match.map(|hdr| hdr.0),
|
||||||
|
if_none_match.map(|hdr| hdr.0),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
let resource = resource_service.get_resource(&path).await?;
|
pub async fn route_delete<R: ResourceService>(
|
||||||
|
path_components: &R::PathComponents,
|
||||||
|
principal: &R::Principal,
|
||||||
|
resource_service: &R,
|
||||||
|
no_trash: bool,
|
||||||
|
if_match: Option<IfMatch>,
|
||||||
|
if_none_match: Option<IfNoneMatch>,
|
||||||
|
) -> Result<(), R::Error> {
|
||||||
|
let resource = resource_service.get_resource(path_components, true).await?;
|
||||||
|
|
||||||
let privileges = resource.get_user_privileges(&principal)?;
|
// Kind of a bodge since we don't get unbind from the parent
|
||||||
if !privileges.has(&UserPrivilege::Write) {
|
let privileges = resource.get_user_privileges(principal)?;
|
||||||
|
if !privileges.has(&UserPrivilege::WriteProperties) {
|
||||||
return Err(Error::Unauthorized.into());
|
return Err(Error::Unauthorized.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
if !resource.satisfies_if_match(&if_match) {
|
if let Some(if_match) = if_match {
|
||||||
// Precondition failed
|
dbg!(&if_match);
|
||||||
return Ok(HttpResponse::PreconditionFailed().finish());
|
if !resource.satisfies_if_match(&if_match) {
|
||||||
|
// Precondition failed
|
||||||
|
return Err(crate::Error::PreconditionFailed.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if resource.satisfies_if_none_match(&if_none_match) {
|
if let Some(if_none_match) = if_none_match {
|
||||||
// Precondition failed
|
if resource.satisfies_if_none_match(&if_none_match) {
|
||||||
return Ok(HttpResponse::PreconditionFailed().finish());
|
// Precondition failed
|
||||||
|
return Err(crate::Error::PreconditionFailed.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
resource_service
|
||||||
resource_service.delete_resource(&path, !no_trash).await?;
|
.delete_resource(path_components, !no_trash)
|
||||||
|
.await?;
|
||||||
Ok(HttpResponse::Ok().body(""))
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
|
mod copy;
|
||||||
mod delete;
|
mod delete;
|
||||||
|
mod mv;
|
||||||
mod propfind;
|
mod propfind;
|
||||||
mod proppatch;
|
mod proppatch;
|
||||||
|
|
||||||
pub(crate) use delete::route_delete;
|
pub(crate) use copy::axum_route_copy;
|
||||||
pub(crate) use propfind::route_propfind;
|
pub(crate) use delete::axum_route_delete;
|
||||||
pub(crate) use proppatch::route_proppatch;
|
pub(crate) use mv::axum_route_move;
|
||||||
|
pub(crate) use propfind::axum_route_propfind;
|
||||||
|
pub(crate) use proppatch::axum_route_proppatch;
|
||||||
|
|||||||
54
crates/dav/src/resource/methods/mv.rs
Normal file
54
crates/dav/src/resource/methods/mv.rs
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
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,))]
|
||||||
|
pub(crate) async fn axum_route_move<R: ResourceService>(
|
||||||
|
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> {
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,71 +1,83 @@
|
|||||||
use crate::Error;
|
use crate::Error;
|
||||||
use crate::header::Depth;
|
use crate::header::Depth;
|
||||||
use crate::privileges::UserPrivilege;
|
use crate::privileges::UserPrivilege;
|
||||||
|
use crate::resource::PrincipalUri;
|
||||||
use crate::resource::Resource;
|
use crate::resource::Resource;
|
||||||
|
use crate::resource::ResourceName;
|
||||||
use crate::resource::ResourceService;
|
use crate::resource::ResourceService;
|
||||||
use crate::xml::MultistatusElement;
|
use crate::xml::MultistatusElement;
|
||||||
use crate::xml::PropElement;
|
use axum::extract::{Extension, OriginalUri, Path, State};
|
||||||
use crate::xml::PropfindElement;
|
|
||||||
use crate::xml::PropfindType;
|
|
||||||
use actix_web::HttpRequest;
|
|
||||||
use actix_web::web::Data;
|
|
||||||
use actix_web::web::Path;
|
|
||||||
use rustical_xml::XmlDocument;
|
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
|
type RSMultistatus<R> = MultistatusElement<
|
||||||
#[allow(clippy::type_complexity)]
|
<<R as ResourceService>::Resource as Resource>::Prop,
|
||||||
pub(crate) async fn route_propfind<R: ResourceService>(
|
<<R as ResourceService>::MemberType as Resource>::Prop,
|
||||||
path: Path<R::PathComponents>,
|
>;
|
||||||
body: String,
|
|
||||||
req: HttpRequest,
|
#[instrument(skip(path, resource_service, puri))]
|
||||||
user: R::Principal,
|
pub(crate) async fn axum_route_propfind<R: ResourceService>(
|
||||||
|
Path(path): Path<R::PathComponents>,
|
||||||
|
State(resource_service): State<R>,
|
||||||
depth: Depth,
|
depth: Depth,
|
||||||
root_span: RootSpan,
|
principal: R::Principal,
|
||||||
resource_service: Data<R>,
|
uri: OriginalUri,
|
||||||
) -> Result<
|
Extension(puri): Extension<R::PrincipalUri>,
|
||||||
MultistatusElement<<R::Resource as Resource>::Prop, <R::MemberType as Resource>::Prop>,
|
body: String,
|
||||||
R::Error,
|
) -> Result<RSMultistatus<R>, R::Error> {
|
||||||
> {
|
route_propfind::<R>(
|
||||||
let resource = resource_service.get_resource(&path).await?;
|
&path,
|
||||||
let privileges = resource.get_user_privileges(&user)?;
|
uri.path(),
|
||||||
|
&body,
|
||||||
|
&principal,
|
||||||
|
&depth,
|
||||||
|
&resource_service,
|
||||||
|
&puri,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn route_propfind<R: ResourceService>(
|
||||||
|
path_components: &R::PathComponents,
|
||||||
|
path: &str,
|
||||||
|
body: &str,
|
||||||
|
principal: &R::Principal,
|
||||||
|
depth: &Depth,
|
||||||
|
resource_service: &R,
|
||||||
|
puri: &impl PrincipalUri,
|
||||||
|
) -> Result<RSMultistatus<R>, R::Error> {
|
||||||
|
let resource = resource_service
|
||||||
|
.get_resource(path_components, false)
|
||||||
|
.await?;
|
||||||
|
let privileges = resource.get_user_privileges(principal)?;
|
||||||
if !privileges.has(&UserPrivilege::Read) {
|
if !privileges.has(&UserPrivilege::Read) {
|
||||||
return Err(Error::Unauthorized.into());
|
return Err(Error::Unauthorized.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
// A request body is optional. If empty we MUST return all props
|
// A request body is optional. If empty we MUST return all props
|
||||||
let propfind: PropfindElement = if !body.is_empty() {
|
let propfind_self = R::Resource::parse_propfind(body).map_err(Error::XmlError)?;
|
||||||
PropfindElement::parse_str(&body).map_err(Error::XmlError)?
|
let propfind_member = R::MemberType::parse_propfind(body).map_err(Error::XmlError)?;
|
||||||
} else {
|
|
||||||
PropfindElement {
|
|
||||||
prop: PropfindType::Allprop,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// TODO: respect namespaces?
|
|
||||||
let props = match &propfind.prop {
|
|
||||||
PropfindType::Allprop => vec!["allprop"],
|
|
||||||
PropfindType::Propname => vec!["propname"],
|
|
||||||
PropfindType::Prop(PropElement(prop_tags)) => prop_tags
|
|
||||||
.iter()
|
|
||||||
.map(|propname| propname.0.as_str())
|
|
||||||
.collect(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut member_responses = Vec::new();
|
let mut member_responses = Vec::new();
|
||||||
if depth != Depth::Zero {
|
if depth != &Depth::Zero {
|
||||||
for (subpath, member) in resource_service.get_members(&path).await? {
|
// TODO: authorization check for member resources
|
||||||
|
for member in resource_service.get_members(path_components).await? {
|
||||||
member_responses.push(member.propfind(
|
member_responses.push(member.propfind(
|
||||||
&format!("{}/{}", req.path().trim_end_matches('/'), subpath),
|
&format!("{}/{}", path.trim_end_matches('/'), member.get_name()),
|
||||||
&props,
|
&propfind_member.prop,
|
||||||
&user,
|
propfind_member.include.as_ref(),
|
||||||
req.resource_map(),
|
puri,
|
||||||
|
principal,
|
||||||
)?);
|
)?);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let response = resource.propfind(req.path(), &props, &user, req.resource_map())?;
|
let response = resource.propfind(
|
||||||
|
path,
|
||||||
|
&propfind_self.prop,
|
||||||
|
propfind_self.include.as_ref(),
|
||||||
|
puri,
|
||||||
|
principal,
|
||||||
|
)?;
|
||||||
|
|
||||||
Ok(MultistatusElement {
|
Ok(MultistatusElement {
|
||||||
responses: vec![response],
|
responses: vec![response],
|
||||||
|
|||||||
@@ -5,18 +5,16 @@ use crate::resource::ResourceService;
|
|||||||
use crate::xml::MultistatusElement;
|
use crate::xml::MultistatusElement;
|
||||||
use crate::xml::TagList;
|
use crate::xml::TagList;
|
||||||
use crate::xml::multistatus::{PropstatElement, PropstatWrapper, ResponseElement};
|
use crate::xml::multistatus::{PropstatElement, PropstatWrapper, ResponseElement};
|
||||||
use actix_web::http::StatusCode;
|
use axum::extract::{OriginalUri, Path, State};
|
||||||
use actix_web::web::Data;
|
use http::StatusCode;
|
||||||
use actix_web::{HttpRequest, web::Path};
|
|
||||||
use quick_xml::name::Namespace;
|
use quick_xml::name::Namespace;
|
||||||
use rustical_xml::EnumUnitVariants;
|
use rustical_xml::NamespaceOwned;
|
||||||
|
use rustical_xml::PropName;
|
||||||
use rustical_xml::Unparsed;
|
use rustical_xml::Unparsed;
|
||||||
use rustical_xml::XmlDeserialize;
|
use rustical_xml::XmlDeserialize;
|
||||||
use rustical_xml::XmlDocument;
|
use rustical_xml::XmlDocument;
|
||||||
use rustical_xml::XmlRootTag;
|
use rustical_xml::XmlRootTag;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use tracing::instrument;
|
|
||||||
use tracing_actix_web::RootSpan;
|
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug)]
|
#[derive(XmlDeserialize, Clone, Debug)]
|
||||||
#[xml(untagged)]
|
#[xml(untagged)]
|
||||||
@@ -28,21 +26,21 @@ enum SetPropertyPropWrapper<T: XmlDeserialize> {
|
|||||||
// We are <prop>
|
// We are <prop>
|
||||||
#[derive(XmlDeserialize, Clone, Debug)]
|
#[derive(XmlDeserialize, Clone, Debug)]
|
||||||
struct SetPropertyPropWrapperWrapper<T: XmlDeserialize>(
|
struct SetPropertyPropWrapperWrapper<T: XmlDeserialize>(
|
||||||
#[xml(ty = "untagged")] SetPropertyPropWrapper<T>,
|
#[xml(ty = "untagged", flatten)] Vec<SetPropertyPropWrapper<T>>,
|
||||||
);
|
);
|
||||||
|
|
||||||
// We are <set>
|
// We are <set>
|
||||||
#[derive(XmlDeserialize, Clone, Debug)]
|
#[derive(XmlDeserialize, Clone, Debug)]
|
||||||
struct SetPropertyElement<T: XmlDeserialize> {
|
struct SetPropertyElement<T: XmlDeserialize> {
|
||||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||||
prop: T,
|
prop: SetPropertyPropWrapperWrapper<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug)]
|
#[derive(XmlDeserialize, Clone, Debug)]
|
||||||
struct TagName(#[xml(ty = "tag_name")] String);
|
struct TagName(#[xml(ty = "tag_name")] String);
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug)]
|
#[derive(XmlDeserialize, Clone, Debug)]
|
||||||
struct PropertyElement(#[xml(ty = "untagged")] TagName);
|
struct PropertyElement(#[xml(ty = "untagged", flatten)] Vec<TagName>);
|
||||||
|
|
||||||
#[derive(XmlDeserialize, Clone, Debug)]
|
#[derive(XmlDeserialize, Clone, Debug)]
|
||||||
struct RemovePropertyElement {
|
struct RemovePropertyElement {
|
||||||
@@ -63,24 +61,33 @@ enum Operation<T: XmlDeserialize> {
|
|||||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||||
struct PropertyupdateElement<T: XmlDeserialize>(#[xml(ty = "untagged", flatten)] Vec<Operation<T>>);
|
struct PropertyupdateElement<T: XmlDeserialize>(#[xml(ty = "untagged", flatten)] Vec<Operation<T>>);
|
||||||
|
|
||||||
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
|
pub(crate) async fn axum_route_proppatch<R: ResourceService>(
|
||||||
pub(crate) async fn route_proppatch<R: ResourceService>(
|
Path(path): Path<R::PathComponents>,
|
||||||
path: Path<R::PathComponents>,
|
State(resource_service): State<R>,
|
||||||
body: String,
|
|
||||||
req: HttpRequest,
|
|
||||||
principal: R::Principal,
|
principal: R::Principal,
|
||||||
root_span: RootSpan,
|
uri: OriginalUri,
|
||||||
resource_service: Data<R>,
|
body: String,
|
||||||
) -> Result<MultistatusElement<String, String>, R::Error> {
|
) -> Result<MultistatusElement<String, String>, R::Error> {
|
||||||
let href = req.path().to_owned();
|
route_proppatch(&path, uri.path(), &body, &principal, &resource_service).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn route_proppatch<R: ResourceService>(
|
||||||
|
path_components: &R::PathComponents,
|
||||||
|
path: &str,
|
||||||
|
body: &str,
|
||||||
|
principal: &R::Principal,
|
||||||
|
resource_service: &R,
|
||||||
|
) -> Result<MultistatusElement<String, String>, R::Error> {
|
||||||
|
let href = path.to_owned();
|
||||||
|
|
||||||
// Extract operations
|
// Extract operations
|
||||||
let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>>(
|
let PropertyupdateElement::<<R::Resource as Resource>::Prop>(operations) =
|
||||||
operations,
|
XmlDocument::parse_str(body).map_err(Error::XmlError)?;
|
||||||
) = XmlDocument::parse_str(&body).map_err(Error::XmlError)?;
|
|
||||||
|
|
||||||
let mut resource = resource_service.get_resource(&path).await?;
|
let mut resource = resource_service
|
||||||
let privileges = resource.get_user_privileges(&principal)?;
|
.get_resource(path_components, false)
|
||||||
|
.await?;
|
||||||
|
let privileges = resource.get_user_privileges(principal)?;
|
||||||
if !privileges.has(&UserPrivilege::Write) {
|
if !privileges.has(&UserPrivilege::Write) {
|
||||||
return Err(Error::Unauthorized.into());
|
return Err(Error::Unauthorized.into());
|
||||||
}
|
}
|
||||||
@@ -92,66 +99,72 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
|
|||||||
for operation in operations.into_iter() {
|
for operation in operations.into_iter() {
|
||||||
match operation {
|
match operation {
|
||||||
Operation::Set(SetPropertyElement {
|
Operation::Set(SetPropertyElement {
|
||||||
prop: SetPropertyPropWrapperWrapper(property),
|
prop: SetPropertyPropWrapperWrapper(properties),
|
||||||
}) => {
|
}) => {
|
||||||
match property {
|
for property in properties {
|
||||||
SetPropertyPropWrapper::Valid(prop) => {
|
match property {
|
||||||
let propname: <<R::Resource as Resource>::Prop as EnumUnitVariants>::UnitVariants = prop.clone().into();
|
SetPropertyPropWrapper::Valid(prop) => {
|
||||||
let (ns, propname): (Option<Namespace>, &str) = propname.into();
|
let propname: <<R::Resource as Resource>::Prop as PropName>::Names =
|
||||||
match resource.set_prop(prop) {
|
prop.clone().into();
|
||||||
Ok(()) => props_ok.push((ns, propname.to_owned())),
|
let (ns, propname): (Option<Namespace>, &str) = propname.into();
|
||||||
Err(Error::PropReadOnly) => {
|
match resource.set_prop(prop) {
|
||||||
props_conflict.push((ns, propname.to_owned()))
|
Ok(()) => props_ok
|
||||||
}
|
.push((ns.map(NamespaceOwned::from), propname.to_owned())),
|
||||||
Err(err) => return Err(err.into()),
|
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();
|
}
|
||||||
|
SetPropertyPropWrapper::Invalid(invalid) => {
|
||||||
|
let propname = invalid.tag_name();
|
||||||
|
|
||||||
if let Some(full_propname) = <R::Resource as Resource>::list_props()
|
if let Some(full_propname) = <R::Resource as Resource>::list_props()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find_map(|(ns, tag)| {
|
.find_map(|(ns, tag)| {
|
||||||
if tag == propname.as_str() {
|
if tag == propname.as_str() {
|
||||||
Some((ns, tag.to_owned()))
|
Some((ns.map(NamespaceOwned::from), tag.to_owned()))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
// This happens in following cases:
|
// This happens in following cases:
|
||||||
// - read-only properties with #[serde(skip_deserializing)]
|
// - read-only properties with #[serde(skip_deserializing)]
|
||||||
// - internal properties
|
// - internal properties
|
||||||
props_conflict.push(full_propname)
|
props_conflict.push(full_propname)
|
||||||
} else {
|
} else {
|
||||||
props_not_found.push((None, propname));
|
props_not_found.push((None, propname));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Operation::Remove(remove_el) => {
|
Operation::Remove(remove_el) => {
|
||||||
let propname = remove_el.prop.0.0;
|
for tagname in remove_el.prop.0 {
|
||||||
match <<R::Resource as Resource>::Prop as EnumUnitVariants>::UnitVariants::from_str(
|
let propname = tagname.0;
|
||||||
&propname,
|
match <<R::Resource as Resource>::Prop as PropName>::Names::from_str(&propname)
|
||||||
) {
|
{
|
||||||
Ok(prop) => match resource.remove_prop(&prop) {
|
Ok(prop) => match resource.remove_prop(&prop) {
|
||||||
Ok(()) => props_ok.push((None, propname)),
|
Ok(()) => props_ok.push((None, propname)),
|
||||||
Err(Error::PropReadOnly) => props_conflict.push({
|
Err(Error::PropReadOnly) => props_conflict.push({
|
||||||
let (ns, tag) = prop.into();
|
let (ns, tag) = prop.into();
|
||||||
(ns, tag.to_owned())
|
(ns.map(NamespaceOwned::from), tag.to_owned())
|
||||||
}),
|
}),
|
||||||
Err(err) => return Err(err.into()),
|
Err(err) => return Err(err.into()),
|
||||||
},
|
},
|
||||||
// I guess removing a nonexisting property should be successful :)
|
// I guess removing a nonexisting property should be successful :)
|
||||||
Err(_) => props_ok.push((None, propname)),
|
Err(_) => props_ok.push((None, propname)),
|
||||||
};
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if props_not_found.is_empty() && props_conflict.is_empty() {
|
if props_not_found.is_empty() && props_conflict.is_empty() {
|
||||||
// Only save if no errors occured
|
// Only save if no errors occured
|
||||||
resource_service.save_resource(&path, resource).await?;
|
resource_service
|
||||||
|
.save_resource(path_components, resource)
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(MultistatusElement {
|
Ok(MultistatusElement {
|
||||||
|
|||||||
@@ -1,21 +1,27 @@
|
|||||||
|
use crate::Principal;
|
||||||
use crate::privileges::UserPrivilegeSet;
|
use crate::privileges::UserPrivilegeSet;
|
||||||
use crate::xml::Resourcetype;
|
|
||||||
use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper};
|
use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper};
|
||||||
|
use crate::xml::{PropElement, PropfindElement, PropfindType, Resourcetype};
|
||||||
use crate::xml::{TagList, multistatus::ResponseElement};
|
use crate::xml::{TagList, multistatus::ResponseElement};
|
||||||
use crate::{Error, Principal};
|
use headers::{ETag, IfMatch, IfNoneMatch};
|
||||||
use actix_web::dev::ResourceMap;
|
use http::StatusCode;
|
||||||
use actix_web::http::header::{EntityTag, IfMatch, IfNoneMatch};
|
|
||||||
use actix_web::{ResponseError, http::StatusCode};
|
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use quick_xml::name::Namespace;
|
use quick_xml::name::Namespace;
|
||||||
pub use resource_service::ResourceService;
|
pub use resource_service::ResourceService;
|
||||||
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
|
use rustical_xml::{
|
||||||
|
EnumVariants, NamespaceOwned, PropName, XmlDeserialize, XmlDocument, XmlSerialize,
|
||||||
|
};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
mod axum_methods;
|
||||||
|
mod axum_service;
|
||||||
mod methods;
|
mod methods;
|
||||||
|
mod principal_uri;
|
||||||
mod resource_service;
|
mod resource_service;
|
||||||
|
|
||||||
pub use resource_service::*;
|
pub use axum_methods::{AxumMethods, MethodFunction};
|
||||||
|
pub use axum_service::AxumService;
|
||||||
|
pub use principal_uri::PrincipalUri;
|
||||||
|
|
||||||
pub trait ResourceProp: XmlSerialize + XmlDeserialize {}
|
pub trait ResourceProp: XmlSerialize + XmlDeserialize {}
|
||||||
impl<T: XmlSerialize + XmlDeserialize> ResourceProp for T {}
|
impl<T: XmlSerialize + XmlDeserialize> ResourceProp for T {}
|
||||||
@@ -23,11 +29,17 @@ impl<T: XmlSerialize + XmlDeserialize> ResourceProp for T {}
|
|||||||
pub trait ResourcePropName: FromStr {}
|
pub trait ResourcePropName: FromStr {}
|
||||||
impl<T: FromStr> ResourcePropName for T {}
|
impl<T: FromStr> ResourcePropName for T {}
|
||||||
|
|
||||||
pub trait Resource: Clone + 'static {
|
pub trait ResourceName {
|
||||||
type Prop: ResourceProp + PartialEq + Clone + EnumVariants + EnumUnitVariants;
|
fn get_name(&self) -> String;
|
||||||
type Error: ResponseError + From<crate::Error>;
|
}
|
||||||
|
|
||||||
|
pub trait Resource: Clone + Send + 'static {
|
||||||
|
type Prop: ResourceProp + PartialEq + Clone + EnumVariants + PropName + Send;
|
||||||
|
type Error: From<crate::Error>;
|
||||||
type Principal: Principal;
|
type Principal: Principal;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool;
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype;
|
fn get_resourcetype(&self) -> Resourcetype;
|
||||||
|
|
||||||
fn list_props() -> Vec<(Option<Namespace<'static>>, &'static str)> {
|
fn list_props() -> Vec<(Option<Namespace<'static>>, &'static str)> {
|
||||||
@@ -36,19 +48,21 @@ pub trait Resource: Clone + 'static {
|
|||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
principal_uri: &impl PrincipalUri,
|
||||||
principal: &Self::Principal,
|
principal: &Self::Principal,
|
||||||
prop: &<Self::Prop as EnumUnitVariants>::UnitVariants,
|
prop: &<Self::Prop as PropName>::Names,
|
||||||
) -> Result<Self::Prop, Self::Error>;
|
) -> Result<Self::Prop, Self::Error>;
|
||||||
|
|
||||||
fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), crate::Error> {
|
fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), crate::Error> {
|
||||||
Err(crate::Error::PropReadOnly)
|
Err(crate::Error::PropReadOnly)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove_prop(
|
fn remove_prop(&mut self, _prop: &<Self::Prop as PropName>::Names) -> Result<(), crate::Error> {
|
||||||
&mut self,
|
Err(crate::Error::PropReadOnly)
|
||||||
_prop: &<Self::Prop as EnumUnitVariants>::UnitVariants,
|
}
|
||||||
) -> Result<(), crate::Error> {
|
|
||||||
|
fn get_displayname(&self) -> Option<&str>;
|
||||||
|
fn set_displayname(&mut self, _name: Option<String>) -> Result<(), crate::Error> {
|
||||||
Err(crate::Error::PropReadOnly)
|
Err(crate::Error::PropReadOnly)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,34 +75,26 @@ pub trait Resource: Clone + 'static {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn satisfies_if_match(&self, if_match: &IfMatch) -> bool {
|
fn satisfies_if_match(&self, if_match: &IfMatch) -> bool {
|
||||||
match if_match {
|
if let Some(etag) = self.get_etag() {
|
||||||
IfMatch::Any => true,
|
if let Ok(etag) = ETag::from_str(&etag) {
|
||||||
// This is not nice but if the header doesn't exist, actix just gives us an empty
|
if_match.precondition_passes(&etag)
|
||||||
// IfMatch::Items header
|
} else {
|
||||||
IfMatch::Items(items) if items.is_empty() => true,
|
if_match.is_any()
|
||||||
IfMatch::Items(items) => {
|
|
||||||
if let Some(etag) = self.get_etag() {
|
|
||||||
let etag = EntityTag::new_strong(etag.to_owned());
|
|
||||||
return items.iter().any(|item| item.strong_eq(&etag));
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if_match.is_any()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn satisfies_if_none_match(&self, if_none_match: &IfNoneMatch) -> bool {
|
fn satisfies_if_none_match(&self, if_none_match: &IfNoneMatch) -> bool {
|
||||||
match if_none_match {
|
if let Some(etag) = self.get_etag() {
|
||||||
IfNoneMatch::Any => false,
|
if let Ok(etag) = ETag::from_str(&etag) {
|
||||||
// This is not nice but if the header doesn't exist, actix just gives us an empty
|
if_none_match.precondition_passes(&etag)
|
||||||
// IfNoneMatch::Items header
|
} else {
|
||||||
IfNoneMatch::Items(items) if items.is_empty() => false,
|
if_none_match != &IfNoneMatch::any()
|
||||||
IfNoneMatch::Items(items) => {
|
|
||||||
if let Some(etag) = self.get_etag() {
|
|
||||||
let etag = EntityTag::new_strong(etag.to_owned());
|
|
||||||
return items.iter().all(|item| item.strong_ne(&etag));
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if_none_match != &IfNoneMatch::any()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,64 +103,71 @@ pub trait Resource: Clone + 'static {
|
|||||||
principal: &Self::Principal,
|
principal: &Self::Principal,
|
||||||
) -> Result<UserPrivilegeSet, Self::Error>;
|
) -> 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(
|
fn propfind(
|
||||||
&self,
|
&self,
|
||||||
path: &str,
|
path: &str,
|
||||||
props: &[&str],
|
prop: &PropfindType<<Self::Prop as PropName>::Names>,
|
||||||
|
include: Option<&PropElement<<Self::Prop as PropName>::Names>>,
|
||||||
|
principal_uri: &impl PrincipalUri,
|
||||||
principal: &Self::Principal,
|
principal: &Self::Principal,
|
||||||
rmap: &ResourceMap,
|
|
||||||
) -> Result<ResponseElement<Self::Prop>, Self::Error> {
|
) -> Result<ResponseElement<Self::Prop>, Self::Error> {
|
||||||
let mut props = props.to_vec();
|
// Collections have a trailing slash
|
||||||
|
let mut path = path.to_string();
|
||||||
if props.contains(&"propname") {
|
if self.is_collection() && !path.ends_with('/') {
|
||||||
if props.len() != 1 {
|
path.push('/');
|
||||||
// propname MUST be the only queried prop per spec
|
|
||||||
return Err(
|
|
||||||
Error::BadRequest("propname MUST be the only queried prop".to_owned()).into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let props = Self::list_props()
|
|
||||||
.into_iter()
|
|
||||||
.map(|(ns, tag)| (ns.to_owned(), 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()
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if props.contains(&"allprop") {
|
let (mut props, mut invalid_props): (Vec<<Self::Prop as PropName>::Names>, Vec<_>) =
|
||||||
if props.len() != 1 {
|
match prop {
|
||||||
// allprop MUST be the only queried prop per spec
|
PropfindType::Propname => {
|
||||||
return Err(
|
let props = Self::list_props()
|
||||||
Error::BadRequest("allprop MUST be the only queried prop".to_owned()).into(),
|
.into_iter()
|
||||||
);
|
.map(|(ns, tag)| (ns.map(NamespaceOwned::from), tag.to_string()))
|
||||||
}
|
.collect_vec();
|
||||||
props = Self::list_props()
|
|
||||||
.into_iter()
|
return Ok(ResponseElement {
|
||||||
.map(|(_ns, tag)| tag)
|
href: path.to_owned(),
|
||||||
.collect();
|
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 mut valid_props = vec![];
|
let prop_responses = props
|
||||||
let mut invalid_props = vec![];
|
|
||||||
for prop in props {
|
|
||||||
if let Ok(valid_prop) = <Self::Prop as EnumUnitVariants>::UnitVariants::from_str(prop) {
|
|
||||||
valid_props.push(valid_prop);
|
|
||||||
} else {
|
|
||||||
invalid_props.push(prop.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let prop_responses = valid_props
|
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|prop| self.get_prop(rmap, principal, &prop))
|
.map(|prop| self.get_prop(principal_uri, principal, &prop))
|
||||||
.collect::<Result<Vec<_>, Self::Error>>()?;
|
.collect::<Result<Vec<_>, Self::Error>>()?;
|
||||||
|
|
||||||
let mut propstats = vec![PropstatWrapper::Normal(PropstatElement {
|
let mut propstats = vec![PropstatWrapper::Normal(PropstatElement {
|
||||||
@@ -164,11 +177,7 @@ pub trait Resource: Clone + 'static {
|
|||||||
if !invalid_props.is_empty() {
|
if !invalid_props.is_empty() {
|
||||||
propstats.push(PropstatWrapper::TagList(PropstatElement {
|
propstats.push(PropstatWrapper::TagList(PropstatElement {
|
||||||
status: StatusCode::NOT_FOUND,
|
status: StatusCode::NOT_FOUND,
|
||||||
prop: invalid_props
|
prop: invalid_props.into(),
|
||||||
.into_iter()
|
|
||||||
.map(|tag| (None, tag))
|
|
||||||
.collect_vec()
|
|
||||||
.into(),
|
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
Ok(ResponseElement {
|
Ok(ResponseElement {
|
||||||
|
|||||||
4
crates/dav/src/resource/principal_uri.rs
Normal file
4
crates/dav/src/resource/principal_uri.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
pub trait PrincipalUri: 'static + Clone + Send + Sync {
|
||||||
|
fn principal_collection(&self) -> String;
|
||||||
|
fn principal_uri(&self, principal: &str) -> String;
|
||||||
|
}
|
||||||
@@ -1,36 +1,43 @@
|
|||||||
use actix_web::dev::{AppService, HttpServiceFactory};
|
use super::{PrincipalUri, Resource};
|
||||||
use actix_web::error::UrlGenerationError;
|
|
||||||
use actix_web::test::TestRequest;
|
|
||||||
use actix_web::web::Data;
|
|
||||||
use actix_web::{ResponseError, dev::ResourceMap, http::Method, web};
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
use crate::Principal;
|
use crate::Principal;
|
||||||
|
use crate::resource::{AxumMethods, AxumService};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use axum::Router;
|
||||||
|
use axum::extract::FromRequestParts;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
use super::Resource;
|
#[async_trait]
|
||||||
use super::methods::{route_delete, route_propfind, route_proppatch};
|
pub trait ResourceService: Clone + Sized + Send + Sync + AxumMethods + 'static {
|
||||||
|
type PathComponents: std::fmt::Debug
|
||||||
#[async_trait(?Send)]
|
+ for<'de> Deserialize<'de>
|
||||||
pub trait ResourceService: Sized + 'static {
|
+ Sized
|
||||||
type MemberType: Resource<Error = Self::Error, Principal = Self::Principal>;
|
+ Send
|
||||||
type PathComponents: for<'de> Deserialize<'de> + Sized + Clone + 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
+ 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>;
|
type Resource: Resource<Error = Self::Error, Principal = Self::Principal>;
|
||||||
type Error: ResponseError + From<crate::Error>;
|
type Error: From<crate::Error> + Send + Sync + IntoResponse + 'static;
|
||||||
type Principal: Principal;
|
type Principal: Principal + FromRequestParts<Self>;
|
||||||
|
type PrincipalUri: PrincipalUri;
|
||||||
|
|
||||||
|
const DAV_HEADER: &'static str;
|
||||||
|
|
||||||
async fn get_members(
|
async fn get_members(
|
||||||
&self,
|
&self,
|
||||||
_path_components: &Self::PathComponents,
|
_path: &Self::PathComponents,
|
||||||
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
|
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||||
Ok(vec![])
|
Ok(vec![])
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_resource(
|
async fn get_resource(
|
||||||
&self,
|
&self,
|
||||||
_path: &Self::PathComponents,
|
path: &Self::PathComponents,
|
||||||
|
show_deleted: bool,
|
||||||
) -> Result<Self::Resource, Self::Error>;
|
) -> Result<Self::Resource, Self::Error>;
|
||||||
|
|
||||||
async fn save_resource(
|
async fn save_resource(
|
||||||
&self,
|
&self,
|
||||||
_path: &Self::PathComponents,
|
_path: &Self::PathComponents,
|
||||||
@@ -38,6 +45,7 @@ pub trait ResourceService: Sized + 'static {
|
|||||||
) -> Result<(), Self::Error> {
|
) -> Result<(), Self::Error> {
|
||||||
Err(crate::Error::Unauthorized.into())
|
Err(crate::Error::Unauthorized.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete_resource(
|
async fn delete_resource(
|
||||||
&self,
|
&self,
|
||||||
_path: &Self::PathComponents,
|
_path: &Self::PathComponents,
|
||||||
@@ -46,51 +54,36 @@ pub trait ResourceService: Sized + 'static {
|
|||||||
Err(crate::Error::Unauthorized.into())
|
Err(crate::Error::Unauthorized.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
// Returns whether an existing resource was overwritten
|
||||||
fn actix_resource(self) -> actix_web::Resource {
|
async fn copy_resource(
|
||||||
Self::actix_additional_routes(
|
&self,
|
||||||
web::resource("")
|
_path: &Self::PathComponents,
|
||||||
.app_data(Data::new(self))
|
_destination: &Self::PathComponents,
|
||||||
.route(
|
_user: &Self::Principal,
|
||||||
web::method(Method::from_str("PROPFIND").unwrap()).to(route_propfind::<Self>),
|
_overwrite: bool,
|
||||||
)
|
) -> Result<bool, Self::Error> {
|
||||||
.route(
|
Err(crate::Error::Forbidden.into())
|
||||||
web::method(Method::from_str("PROPPATCH").unwrap()).to(route_proppatch::<Self>),
|
|
||||||
)
|
|
||||||
.delete(route_delete::<Self>),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hook for other resources to insert their additional methods (i.e. REPORT, MKCALENDAR)
|
// Returns whether an existing resource was overwritten
|
||||||
#[inline]
|
async fn move_resource(
|
||||||
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
|
&self,
|
||||||
res
|
_path: &Self::PathComponents,
|
||||||
|
_destination: &Self::PathComponents,
|
||||||
|
_user: &Self::Principal,
|
||||||
|
_overwrite: bool,
|
||||||
|
) -> Result<bool, Self::Error> {
|
||||||
|
Err(crate::Error::Forbidden.into())
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
pub trait NamedRoute {
|
fn axum_service(self) -> AxumService<Self>
|
||||||
fn route_name() -> &'static str;
|
|
||||||
|
|
||||||
fn get_url<U, I>(rmap: &ResourceMap, elements: U) -> Result<String, UrlGenerationError>
|
|
||||||
where
|
where
|
||||||
U: IntoIterator<Item = I>,
|
Self: AxumMethods,
|
||||||
I: AsRef<str>,
|
|
||||||
{
|
{
|
||||||
Ok(rmap
|
AxumService::new(self)
|
||||||
.url_for(
|
}
|
||||||
&TestRequest::default().to_http_request(),
|
|
||||||
Self::route_name(),
|
fn axum_router<S: Send + Sync + Clone + 'static>(self) -> Router<S> {
|
||||||
elements,
|
Router::new().route_service("/", self.axum_service())
|
||||||
)?
|
|
||||||
.path()
|
|
||||||
.to_owned())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ResourceServiceRoute<RS: ResourceService>(pub RS);
|
|
||||||
|
|
||||||
impl<RS: ResourceService> HttpServiceFactory for ResourceServiceRoute<RS> {
|
|
||||||
fn register(self, config: &mut AppService) {
|
|
||||||
self.0.actix_resource().register(config);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,11 @@ use crate::extensions::{
|
|||||||
CommonPropertiesExtension, CommonPropertiesProp, CommonPropertiesPropName,
|
CommonPropertiesExtension, CommonPropertiesProp, CommonPropertiesPropName,
|
||||||
};
|
};
|
||||||
use crate::privileges::UserPrivilegeSet;
|
use crate::privileges::UserPrivilegeSet;
|
||||||
use crate::resource::{NamedRoute, Resource, ResourceService};
|
use crate::resource::{AxumMethods, PrincipalUri, Resource, ResourceName, ResourceService};
|
||||||
use crate::xml::{Resourcetype, ResourcetypeInner};
|
use crate::xml::{Resourcetype, ResourcetypeInner};
|
||||||
use actix_web::dev::ResourceMap;
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use axum::Router;
|
||||||
|
use axum::extract::FromRequestParts;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -18,15 +19,15 @@ impl<PR: Resource, P: Principal> Default for RootResource<PR, P> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<PR: Resource + NamedRoute, P: Principal> CommonPropertiesExtension for RootResource<PR, P> {
|
impl<PR: Resource, P: Principal> Resource for RootResource<PR, P> {
|
||||||
type PrincipalResource = PR;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<PR: Resource + NamedRoute, P: Principal> Resource for RootResource<PR, P> {
|
|
||||||
type Prop = CommonPropertiesProp;
|
type Prop = CommonPropertiesProp;
|
||||||
type Error = PR::Error;
|
type Error = PR::Error;
|
||||||
type Principal = P;
|
type Principal = P;
|
||||||
|
|
||||||
|
fn is_collection(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
fn get_resourcetype(&self) -> Resourcetype {
|
fn get_resourcetype(&self) -> Resourcetype {
|
||||||
Resourcetype(&[ResourcetypeInner(
|
Resourcetype(&[ResourcetypeInner(
|
||||||
Some(crate::namespace::NS_DAV),
|
Some(crate::namespace::NS_DAV),
|
||||||
@@ -34,13 +35,17 @@ impl<PR: Resource + NamedRoute, P: Principal> Resource for RootResource<PR, P> {
|
|||||||
)])
|
)])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_displayname(&self) -> Option<&str> {
|
||||||
|
Some("RustiCal DAV root")
|
||||||
|
}
|
||||||
|
|
||||||
fn get_prop(
|
fn get_prop(
|
||||||
&self,
|
&self,
|
||||||
rmap: &ResourceMap,
|
principal_uri: &impl PrincipalUri,
|
||||||
user: &P,
|
user: &P,
|
||||||
prop: &CommonPropertiesPropName,
|
prop: &CommonPropertiesPropName,
|
||||||
) -> Result<Self::Prop, Self::Error> {
|
) -> Result<Self::Prop, Self::Error> {
|
||||||
CommonPropertiesExtension::get_prop(self, rmap, user, prop)
|
CommonPropertiesExtension::get_prop(self, principal_uri, user, prop)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_user_privileges(&self, _user: &P) -> Result<UserPrivilegeSet, Self::Error> {
|
fn get_user_privileges(&self, _user: &P) -> Result<UserPrivilegeSet, Self::Error> {
|
||||||
@@ -49,25 +54,54 @@ impl<PR: Resource + NamedRoute, P: Principal> Resource for RootResource<PR, P> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RootResourceService<PR: Resource, P: Principal>(PhantomData<PR>, PhantomData<P>);
|
pub struct RootResourceService<PRS: ResourceService + Clone, P: Principal, PURI: PrincipalUri>(
|
||||||
|
PRS,
|
||||||
|
PhantomData<P>,
|
||||||
|
PhantomData<PURI>,
|
||||||
|
);
|
||||||
|
|
||||||
impl<PR: Resource, P: Principal> Default for RootResourceService<PR, P> {
|
impl<PRS: ResourceService + Clone, P: Principal, PURI: PrincipalUri>
|
||||||
fn default() -> Self {
|
RootResourceService<PRS, P, PURI>
|
||||||
Self(PhantomData, PhantomData)
|
{
|
||||||
|
pub fn new(principal_resource_service: PRS) -> Self {
|
||||||
|
Self(principal_resource_service, PhantomData, PhantomData)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
#[async_trait]
|
||||||
impl<PR: Resource<Principal = P> + NamedRoute, P: Principal> ResourceService
|
impl<
|
||||||
for RootResourceService<PR, P>
|
PRS: ResourceService<Principal = P> + Clone,
|
||||||
|
P: Principal + FromRequestParts<Self>,
|
||||||
|
PURI: PrincipalUri,
|
||||||
|
> ResourceService for RootResourceService<PRS, P, PURI>
|
||||||
|
where
|
||||||
|
PRS::Resource: ResourceName,
|
||||||
{
|
{
|
||||||
type PathComponents = ();
|
type PathComponents = ();
|
||||||
type MemberType = PR;
|
type MemberType = PRS::Resource;
|
||||||
type Resource = RootResource<PR, P>;
|
type Resource = RootResource<PRS::Resource, P>;
|
||||||
type Error = PR::Error;
|
type Error = PRS::Error;
|
||||||
type Principal = P;
|
type Principal = P;
|
||||||
|
type PrincipalUri = PURI;
|
||||||
|
|
||||||
async fn get_resource(&self, _: &()) -> Result<Self::Resource, Self::Error> {
|
const DAV_HEADER: &str = "1, 3, access-control";
|
||||||
Ok(RootResource::<PR, P>::default())
|
|
||||||
|
async fn get_resource(
|
||||||
|
&self,
|
||||||
|
_: &(),
|
||||||
|
_show_deleted: bool,
|
||||||
|
) -> Result<Self::Resource, Self::Error> {
|
||||||
|
Ok(RootResource::<PRS::Resource, P>::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn axum_router<S: Send + Sync + Clone + 'static>(self) -> Router<S> {
|
||||||
|
Router::new()
|
||||||
|
.nest("/principal/{principal}", self.0.clone().axum_router())
|
||||||
|
.route_service("/", self.axum_service())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<PRS: ResourceService<Principal = P> + Clone, P: Principal, PURI: PrincipalUri> AxumMethods
|
||||||
|
for RootResourceService<PRS, P, PURI>
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user