Compare commits

..

55 Commits

Author SHA1 Message Date
Lennart
16aae73cd1 integration tests: Fix snapshot naming 2025-12-13 00:20:36 +01:00
Lennart
120d45eb0a caldav: Add proppatch test 2025-12-12 23:56:29 +01:00
Lennart
0bdfb786ff clippy appeasement 2025-12-12 23:47:10 +01:00
Lennart
d9cca5a298 improve caldav integration test 2025-12-12 23:43:14 +01:00
Lennart
50a74e3a25 fix integration tests 2025-12-12 14:46:10 +01:00
Lennart
ed8a9e718a more integration tests 2025-12-12 14:35:47 +01:00
Lennart
38b5a3812e add integration tests 2025-12-12 14:12:09 +01:00
Lennart
d3e7ede93c frontend: Merge components into single bundle 2025-12-12 13:00:44 +01:00
Lennart
4e90f725e0 update dependencies 2025-12-12 11:47:15 +01:00
Lennart
ef40f5ea8c version 0.11.2 2025-12-11 20:34:34 +01:00
Lennart
1230e29243 frontend: tiny improvement to import forms 2025-12-11 20:17:04 +01:00
Lennart
1b2296c00a clippy appeasement 2025-12-11 20:16:44 +01:00
Lennart
ac6ab0ca9a clippy appeasement 2025-12-11 20:01:04 +01:00
Lennart
6312f52b10 update license information 2025-12-11 19:59:20 +01:00
Lennart
ec28cb9d9a frontend: improve calendar creation form and fix data binding bugs 2025-12-11 19:52:48 +01:00
Lennart
4b4210b4d7 Add initial test for app initialisation 2025-12-10 14:43:06 +01:00
Lennart
8fadff1b57 fix insta snapshots 2025-12-10 14:30:18 +01:00
Lennart
61a8c32af4 add some more propfind regression tests 2025-12-10 14:22:04 +01:00
Lennart
a45e0b2efd carddav: Try out some tests with insta 2025-12-10 12:26:31 +01:00
Lennart
eecc03b7b7 caldav: add debug to principal resource 2025-12-10 12:25:59 +01:00
Lennart
e8303b9c82 main: slight refactoring 2025-12-10 12:25:13 +01:00
Lennart
a686286d06 sqlite_store: Refactor notification logic 2025-12-10 10:44:41 +01:00
Lennart
d81074de3b version 0.11.1 2025-12-05 20:32:17 +01:00
Lennart
42386adcfa frontend: remove debug statement from template 2025-12-05 20:31:58 +01:00
Lennart
d2f5f7c89b version 0.11.0 2025-12-05 15:06:01 +01:00
Lennart Kämmle
15e431ce12 Merge pull request #138 from lennart-k/feature/birthday-calendar
Feature/birthday calendar
2025-12-05 15:03:56 +01:00
Lennart
96a16951f4 sqlx prepare 2025-12-05 14:55:30 +01:00
Lennart
a32b766c0c Merge branch 'main' into feature/birthday-calendar 2025-12-05 14:51:51 +01:00
Lennart
7a101b7364 frontend: Fix cursor for anchors 2025-12-05 14:51:34 +01:00
Lennart
57275a10b4 Add birthday calendar creation to frontend 2025-12-05 14:50:02 +01:00
Lennart
af239e34bf birthday calendar store: Support manual birthday calendar creation 2025-12-05 14:49:09 +01:00
Lennart
e99b1d9123 calendar resource: Remove prop write guards 2025-12-05 14:48:35 +01:00
Lennart
e39657eb29 PROPPATCH: Fix privileges 2025-12-05 14:48:11 +01:00
Lennart
607db62859 Merge branch 'main' into feature/birthday-calendar 2025-12-05 11:47:42 +01:00
Lennart
eba377b980 update dependencies 2025-12-05 11:47:11 +01:00
Lennart
d5c1ddc590 caldav: Update test_propfind regression test 2025-11-22 18:49:32 +01:00
Lennart
a79e1901b8 test_propfind: Revert assert_eq order 2025-11-22 18:48:36 +01:00
Lennart
f29c8fa925 Merge branch 'main' into feature/birthday-calendar 2025-11-22 18:46:59 +01:00
Lennart
54f1ee0788 use similar-asserts for regression tests 2025-11-22 18:46:47 +01:00
Lennart
96f221f721 birthday_calendar: Refactor insert_birthday_calendar 2025-11-22 18:35:26 +01:00
Lennart
ba3b64a9c4 Merge branch 'main' into feature/birthday-calendar 2025-11-22 18:30:44 +01:00
Lennart
22a0337375 version 0.10.5 2025-11-17 19:14:17 +01:00
Lennart
21902e108a fix some error messages 2025-11-17 19:13:13 +01:00
Lennart
08f526fa5b Add startup routine to fix orphaned objects
fixes #145, related to #142
2025-11-17 19:11:30 +01:00
Lennart
ac73f3aaff addressbook_store: Commit import addressbooks to changelog 2025-11-17 18:35:10 +01:00
Lennart
9fdc8434db calendar import: log added events 2025-11-17 18:22:33 +01:00
Lennart
85f3d89235 version 0.10.4 2025-11-17 01:21:55 +01:00
Lennart
092604694a multiget: percent-decode hrefs 2025-11-17 01:21:20 +01:00
Lennart
8ef24668ba version 0.10.3 2025-11-14 11:02:27 +01:00
Lennart
416658d069 frontend: Fix missing getTimezones import in create-calendar-form
fixes #141
2025-11-14 11:01:59 +01:00
Lennart
80eae5db9e version 0.10.2 2025-11-09 21:39:09 +01:00
Lennart
66f541f1c7 Drop log level for 404 to info
fixes #139
2025-11-09 21:36:17 +01:00
Lennart
ea7196501e docs: Add verification for Google Search Console (not analytics) 2025-11-06 00:19:33 +01:00
Lennart
33d14a9ba0 sqlite_store: Add some more basic tests 2025-11-05 23:17:59 +01:00
Lennart
d843909084 Update Cargo.toml 2025-11-05 16:16:01 +01:00
113 changed files with 5347 additions and 4010 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

497
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,8 @@
members = ["crates/*"] members = ["crates/*"]
[workspace.package] [workspace.package]
version = "0.10.1" version = "0.11.2"
rust-version = "1.91"
edition = "2024" edition = "2024"
description = "A CalDAV server" description = "A CalDAV server"
documentation = "https://lennart-k.github.io/rustical/" documentation = "https://lennart-k.github.io/rustical/"
@@ -12,6 +13,7 @@ license = "AGPL-3.0-or-later"
[package] [package]
name = "rustical" name = "rustical"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true
@@ -35,8 +37,19 @@ opentelemetry = [
debug = 0 debug = 0
[workspace.dependencies] [workspace.dependencies]
rustical_dav = { path = "./crates/dav/" }
rustical_dav_push = { path = "./crates/dav_push/" }
rustical_store = { path = "./crates/store/" }
rustical_store_sqlite = { path = "./crates/store_sqlite/" }
rustical_caldav = { path = "./crates/caldav/" }
rustical_carddav = { path = "./crates/carddav/" }
rustical_frontend = { path = "./crates/frontend/" }
rustical_xml = { path = "./crates/xml/" }
rustical_oidc = { path = "./crates/oidc/" }
rustical_ical = { path = "./crates/ical/" }
matchit = "0.9" matchit = "0.9"
uuid = { version = "1.11", features = ["v4", "fast-rng"] } uuid = { version = "1.19", features = ["v4", "fast-rng"] }
async-trait = "0.1" async-trait = "0.1"
axum = "0.8" axum = "0.8"
tracing = { version = "0.1", features = ["async-await"] } tracing = { version = "0.1", features = ["async-await"] }
@@ -47,11 +60,11 @@ password-auth = { version = "1.0", features = ["argon2", "pbkdf2"] }
pbkdf2 = { version = "0.12", features = ["simple"] } pbkdf2 = { version = "0.12", features = ["simple"] }
rand_core = { version = "0.9", features = ["std"] } rand_core = { version = "0.9", features = ["std"] }
chrono = { version = "0.4", features = ["serde"] } chrono = { version = "0.4", features = ["serde"] }
regex = "1.10" regex = "1.12"
rstest = "0.26" rstest = "0.26"
rstest_reuse = "0.7" rstest_reuse = "0.7"
sha2 = "0.10" sha2 = "0.10"
tokio = { version = "1", features = [ tokio = { version = "1.48", features = [
"net", "net",
"tracing", "tracing",
"macros", "macros",
@@ -62,14 +75,14 @@ url = "2.5"
base64 = "0.22" base64 = "0.22"
thiserror = "2.0" thiserror = "2.0"
quick-xml = { version = "0.38" } quick-xml = { version = "0.38" }
rust-embed = "8.5" rust-embed = "8.9"
tower-sessions = "0.14" tower-sessions = "0.14"
futures-core = "0.3.31" futures-core = "0.3"
hex = { version = "0.4.3", features = ["serde"] } hex = { version = "0.4", features = ["serde"] }
mime_guess = "2.0" 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.1", features = [
"from", "from",
"try_into", "try_into",
"into", "into",
@@ -78,7 +91,7 @@ derive_more = { version = "2.0", features = [
"display", "display",
] } ] }
askama = { version = "0.14", features = ["serde_json"] } askama = { version = "0.14", features = ["serde_json"] }
askama_web = { version = "0.14.0", features = ["axum-0.8"] } askama_web = { version = "0.14", 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",
@@ -89,7 +102,7 @@ sqlx = { version = "0.8", default-features = false, features = [
"migrate", "migrate",
"json", "json",
] } ] }
http = "1.3" http = "1.4"
headers = "0.4" headers = "0.4"
strum = "0.27" strum = "0.27"
strum_macros = "0.27" strum_macros = "0.27"
@@ -108,29 +121,19 @@ tower-http = { version = "0.6", features = [
"catch-panic", "catch-panic",
] } ] }
percent-encoding = "2.3" percent-encoding = "2.3"
rustical_dav = { path = "./crates/dav/" }
rustical_dav_push = { path = "./crates/dav_push/" }
rustical_store = { path = "./crates/store/" }
rustical_store_sqlite = { path = "./crates/store_sqlite/" }
rustical_caldav = { path = "./crates/caldav/" }
rustical_carddav = { path = "./crates/carddav/" }
rustical_frontend = { path = "./crates/frontend/" }
rustical_xml = { path = "./crates/xml/" }
rustical_oidc = { path = "./crates/oidc/" }
rustical_ical = { path = "./crates/ical/" }
chrono-tz = "0.10" chrono-tz = "0.10"
chrono-humanize = "0.2" chrono-humanize = "0.2"
rand = "0.9" rand = "0.9"
axum-extra = { version = "0.12", features = ["typed-header"] } axum-extra = { version = "0.12", features = ["typed-header"] }
rrule = "0.14" rrule = "0.14"
argon2 = "0.5" argon2 = "0.5"
rpassword = "7.3" rpassword = "7.4"
password-hash = { version = "0.5" } password-hash = { version = "0.5" }
syn = { version = "2.0", features = ["full"] } 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.21" darling = "0.23"
reqwest = { version = "0.12", features = [ reqwest = { version = "0.12", features = [
"rustls-tls", "rustls-tls",
"charset", "charset",
@@ -145,21 +148,28 @@ ece = { version = "2.3", default-features = false, features = [
] } ] }
openssl = { version = "0.10", features = ["vendored"] } openssl = { version = "0.10", features = ["vendored"] }
async-std = { version = "1.13", features = ["attributes"] } async-std = { version = "1.13", features = ["attributes"] }
similar-asserts = "1.7"
insta = { version = "1.44", features = ["filters"] }
[dev-dependencies]
rstest.workspace = true
rustical_store_sqlite = { workspace = true, features = ["test"] }
insta.workspace = true
[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
toml = { workspace = true } toml.workspace = true
serde = { workspace = true } serde.workspace = true
tokio = { workspace = true } tokio.workspace = true
tracing = { workspace = true } tracing.workspace = true
anyhow = { workspace = true } anyhow.workspace = true
clap.workspace = true clap.workspace = true
sqlx = { workspace = true } sqlx.workspace = true
async-trait = { workspace = true } async-trait.workspace = true
uuid.workspace = true uuid.workspace = true
axum.workspace = true axum.workspace = true

View File

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

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_caldav" name = "rustical_caldav"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true
@@ -12,26 +13,27 @@ rustical_store_sqlite = { workspace = true, features = ["test"] }
rstest.workspace = true rstest.workspace = true
async-std.workspace = true async-std.workspace = true
serde_json.workspace = true serde_json.workspace = true
insta.workspace = true
[dependencies] [dependencies]
axum.workspace = true axum.workspace = true
axum-extra.workspace = true axum-extra.workspace = true
tower.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
futures-util = { workspace = true } futures-util.workspace = true
derive_more = { workspace = true } derive_more.workspace = true
base64 = { workspace = true } base64.workspace = true
serde = { workspace = true } serde.workspace = true
tokio = { workspace = true } tokio.workspace = true
url = { workspace = true } url.workspace = true
rustical_dav = { workspace = true } rustical_dav.workspace = true
rustical_store = { workspace = true } 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 ical.workspace = true
percent-encoding.workspace = true percent-encoding.workspace = true
rustical_xml.workspace = true rustical_xml.workspace = true
@@ -44,3 +46,4 @@ tower-http.workspace = true
strum.workspace = true strum.workspace = true
strum_macros.workspace = true strum_macros.workspace = true
vtimezones-rs.workspace = true vtimezones-rs.workspace = true
similar-asserts.workspace = true

View File

@@ -26,16 +26,18 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
let mut not_found = vec![]; let mut not_found = vec![];
for href in &cal_query.href { for href in &cal_query.href {
if let Some(filename) = href.strip_prefix(path) { if let Ok(href) = percent_encoding::percent_decode_str(href).decode_utf8()
&& let Some(filename) = href.strip_prefix(path)
{
let filename = filename.trim_start_matches('/'); let filename = filename.trim_start_matches('/');
if let Some(object_id) = filename.strip_suffix(".ics") { if let Some(object_id) = filename.strip_suffix(".ics") {
match store.get_object(principal, cal_id, object_id, false).await { match store.get_object(principal, cal_id, object_id, false).await {
Ok(object) => result.push(object), Ok(object) => result.push(object),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()), Err(rustical_store::Error::NotFound) => not_found.push(href.to_string()),
Err(err) => return Err(err.into()), Err(err) => return Err(err.into()),
} }
} else { } else {
not_found.push(href.to_owned()); not_found.push(href.to_string());
} }
} else { } else {
not_found.push(href.to_owned()); not_found.push(href.to_owned());

View File

@@ -16,6 +16,7 @@ pub struct CompFilterElement {
pub(crate) time_range: Option<TimeRangeElement>, pub(crate) time_range: Option<TimeRangeElement>,
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)] #[xml(ns = "rustical_dav::namespace::NS_CALDAV", flatten)]
pub(crate) prop_filter: Vec<PropFilterElement>, pub(crate) prop_filter: Vec<PropFilterElement>,
#[allow(clippy::use_self)]
#[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>,

View File

@@ -188,9 +188,6 @@ impl Resource for CalendarResource {
} }
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> { fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
if self.read_only {
return Err(rustical_dav::Error::PropReadOnly);
}
match prop { match prop {
CalendarPropWrapper::Calendar(prop) => match prop { CalendarPropWrapper::Calendar(prop) => match prop {
CalendarProp::CalendarColor(color) => { CalendarProp::CalendarColor(color) => {
@@ -263,9 +260,6 @@ impl Resource for CalendarResource {
} }
fn remove_prop(&mut self, prop: &CalendarPropWrapperName) -> Result<(), rustical_dav::Error> { fn remove_prop(&mut self, prop: &CalendarPropWrapperName) -> Result<(), rustical_dav::Error> {
if self.read_only {
return Err(rustical_dav::Error::PropReadOnly);
}
match prop { match prop {
CalendarPropWrapperName::Calendar(prop) => match prop { CalendarPropWrapperName::Calendar(prop) => match prop {
CalendarPropName::CalendarColor => { CalendarPropName::CalendarColor => {

View File

@@ -211,6 +211,9 @@ END:VCALENDAR
<privilege> <privilege>
<read/> <read/>
</privilege> </privilege>
<privilege>
<write-properties/>
</privilege>
<privilege> <privilege>
<read-acl/> <read-acl/>
</privilege> </privilege>

View File

@@ -39,9 +39,7 @@ async fn test_propfind() {
.unwrap() .unwrap()
.trim() .trim()
.replace("\r\n", "\n"); .replace("\r\n", "\n");
println!("{output}"); similar_asserts::assert_eq!(expected_output, output);
println!("{}, {} \n\n\n", output.len(), expected_output.len());
assert_eq!(output, expected_output);
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,3 @@
use std::sync::Arc;
use crate::{ use crate::{
CalDavPrincipalUri, CalDavPrincipalUri,
principal::{PrincipalResource, PrincipalResourceService}, principal::{PrincipalResource, PrincipalResourceService},
@@ -14,6 +12,7 @@ use rustical_store_sqlite::{
tests::{get_test_calendar_store, get_test_principal_store, get_test_subscription_store}, tests::{get_test_calendar_store, get_test_principal_store, get_test_subscription_store},
}; };
use rustical_xml::XmlSerializeRoot; use rustical_xml::XmlSerializeRoot;
use std::sync::Arc;
#[rstest] #[rstest]
#[tokio::test] #[tokio::test]
@@ -64,6 +63,8 @@ async fn test_propfind() {
) )
.unwrap(); .unwrap();
insta::assert_debug_snapshot!(propfind);
let principal = Principal { let principal = Principal {
id: "user".to_string(), id: "user".to_string(),
displayname: None, displayname: None,
@@ -88,5 +89,6 @@ async fn test_propfind() {
) )
.unwrap(); .unwrap();
let _output = response.serialize_to_string().unwrap(); insta::assert_debug_snapshot!(response);
insta::assert_snapshot!(response.serialize_to_string().unwrap());
} }

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_carddav" name = "rustical_carddav"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true
@@ -11,19 +12,19 @@ publish = false
axum.workspace = true axum.workspace = true
axum-extra.workspace = true axum-extra.workspace = true
tower.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
futures-util = { workspace = true } futures-util.workspace = true
derive_more = { workspace = true } derive_more.workspace = true
base64 = { workspace = true } base64.workspace = true
serde = { workspace = true } serde.workspace = true
tokio = { workspace = true } tokio.workspace = true
url = { workspace = true } url.workspace = true
rustical_dav = { workspace = true } rustical_dav.workspace = true
rustical_store = { workspace = true } rustical_store.workspace = true
chrono = { workspace = true } 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
@@ -34,3 +35,6 @@ percent-encoding.workspace = true
ical.workspace = true ical.workspace = true
strum.workspace = true strum.workspace = true
strum_macros.workspace = true strum_macros.workspace = true
[dev-dependencies]
insta.workspace = true

View File

@@ -34,7 +34,9 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
let mut not_found = vec![]; let mut not_found = vec![];
for href in &addressbook_multiget.href { for href in &addressbook_multiget.href {
if let Some(filename) = href.strip_prefix(path) { if let Ok(href) = percent_encoding::percent_decode_str(href).decode_utf8()
&& let Some(filename) = href.strip_prefix(path)
{
let filename = filename.trim_start_matches('/'); let filename = filename.trim_start_matches('/');
if let Some(object_id) = filename.strip_suffix(".vcf") { if let Some(object_id) = filename.strip_suffix(".vcf") {
match store match store
@@ -42,11 +44,11 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
.await .await
{ {
Ok(object) => result.push(object), Ok(object) => result.push(object),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()), Err(rustical_store::Error::NotFound) => not_found.push(href.to_string()),
Err(err) => return Err(err.into()), Err(err) => return Err(err.into()),
} }
} else { } else {
not_found.push(href.to_owned()); not_found.push(href.to_string());
} }
} else { } else {
not_found.push(href.to_owned()); not_found.push(href.to_owned());

View File

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

View File

@@ -6,7 +6,7 @@ use rustical_dav_push::DavPushExtensionProp;
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize}; use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
use strum_macros::VariantArray; use strum_macros::VariantArray;
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "AddressbookPropName")] #[xml(unit_variants_ident = "AddressbookPropName")]
pub enum AddressbookProp { pub enum AddressbookProp {
// CardDAV (RFC 6352) // CardDAV (RFC 6352)
@@ -20,7 +20,7 @@ pub enum AddressbookProp {
MaxResourceSize(i64), MaxResourceSize(i64),
} }
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName, Debug)]
#[xml(unit_variants_ident = "AddressbookPropWrapperName", untagged)] #[xml(unit_variants_ident = "AddressbookPropWrapperName", untagged)]
pub enum AddressbookPropWrapper { pub enum AddressbookPropWrapper {
Addressbook(AddressbookProp), Addressbook(AddressbookProp),

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,5 @@
use axum::response::IntoResponse; use axum::response::IntoResponse;
use http::StatusCode; use http::StatusCode;
use tracing::error;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {

View File

@@ -11,11 +11,13 @@ mod service;
pub use service::*; pub use service::*;
mod prop; mod prop;
pub use prop::*; pub use prop::*;
#[cfg(test)]
pub mod tests;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PrincipalResource { pub struct PrincipalResource {
principal: Principal, pub principal: Principal,
members: Vec<String>, pub members: Vec<String>,
} }
impl ResourceName for PrincipalResource { impl ResourceName for PrincipalResource {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_dav" name = "rustical_dav"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true

View File

@@ -6,7 +6,7 @@ use crate::{
}; };
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize}; use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, PropName, EnumVariants)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Debug, 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)

View File

@@ -1,6 +1,6 @@
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize}; use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, PropName, EnumVariants)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, PropName, EnumVariants, Debug)]
#[xml(unit_variants_ident = "SyncTokenExtensionPropName")] #[xml(unit_variants_ident = "SyncTokenExtensionPropName")]
pub enum SyncTokenExtensionProp { pub enum SyncTokenExtensionProp {
// Collection Synchronization (RFC 6578) // Collection Synchronization (RFC 6578)

View File

@@ -88,7 +88,7 @@ pub async fn route_proppatch<R: ResourceService>(
.get_resource(path_components, false) .get_resource(path_components, false)
.await?; .await?;
let privileges = resource.get_user_privileges(principal)?; let privileges = resource.get_user_privileges(principal)?;
if !privileges.has(&UserPrivilege::Write) { if !privileges.has(&UserPrivilege::WriteProperties) {
return Err(Error::Unauthorized.into()); return Err(Error::Unauthorized.into());
} }

View File

@@ -1,8 +1,8 @@
use crate::xml::HrefElement; use crate::xml::HrefElement;
use rustical_xml::{XmlDeserialize, XmlSerialize}; use rustical_xml::{XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, Debug)]
pub struct GroupMembership(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>); pub struct GroupMembership(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, Debug)]
pub struct GroupMemberSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>); pub struct GroupMemberSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);

View File

@@ -3,9 +3,9 @@ use headers::{CacheControl, ContentType, HeaderMapExt};
use http::StatusCode; use http::StatusCode;
use quick_xml::name::Namespace; use quick_xml::name::Namespace;
use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot}; use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot};
use std::collections::HashMap; use std::{collections::HashMap, fmt::Debug};
#[derive(XmlSerialize)] #[derive(XmlSerialize, Debug)]
pub struct PropTagWrapper<T: XmlSerialize>(#[xml(flatten, ty = "untagged")] pub Vec<T>); pub struct PropTagWrapper<T: XmlSerialize>(#[xml(flatten, ty = "untagged")] pub Vec<T>);
// RFC 2518 // RFC 2518
@@ -30,7 +30,7 @@ fn xml_serialize_status(
XmlSerialize::serialize(&format!("HTTP/1.1 {status}"), ns, tag, namespaces, writer) XmlSerialize::serialize(&format!("HTTP/1.1 {status}"), ns, tag, namespaces, writer)
} }
#[derive(XmlSerialize)] #[derive(XmlSerialize, Debug)]
#[xml(untagged)] #[xml(untagged)]
pub enum PropstatWrapper<T: XmlSerialize> { pub enum PropstatWrapper<T: XmlSerialize> {
Normal(PropstatElement<PropTagWrapper<T>>), Normal(PropstatElement<PropTagWrapper<T>>),
@@ -40,7 +40,7 @@ pub enum PropstatWrapper<T: XmlSerialize> {
// RFC 2518 // RFC 2518
// <!ELEMENT response (href, ((href*, status)|(propstat+)), // <!ELEMENT response (href, ((href*, status)|(propstat+)),
// responsedescription?) > // responsedescription?) >
#[derive(XmlSerialize, XmlRootTag)] #[derive(XmlSerialize, XmlRootTag, Debug)]
#[xml(ns = "crate::namespace::NS_DAV", root = "response")] #[xml(ns = "crate::namespace::NS_DAV", root = "response")]
#[xml(ns_prefix( #[xml(ns_prefix(
crate::namespace::NS_DAV = "", crate::namespace::NS_DAV = "",

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_dav_push" name = "rustical_dav_push"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true
@@ -9,15 +10,15 @@ publish = false
[dependencies] [dependencies]
rustical_xml.workspace = true rustical_xml.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
serde = { workspace = true } serde.workspace = true
thiserror = { workspace = true } thiserror.workspace = true
itertools = { workspace = true } itertools.workspace = true
log = { workspace = true } log.workspace = true
derive_more = { workspace = true } derive_more.workspace = true
tracing = { workspace = true } tracing.workspace = true
reqwest.workspace = true reqwest.workspace = true
tokio.workspace = true tokio.workspace = true
rustical_dav.workspace = true rustical_dav.workspace = true

View File

@@ -2,7 +2,7 @@ use crate::{ContentUpdate, PropertyUpdate, SupportedTriggers, Transports, Trigge
use rustical_dav::header::Depth; use rustical_dav::header::Depth;
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize}; use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, PropName, EnumVariants)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, PropName, EnumVariants, Debug)]
#[xml(unit_variants_ident = "DavPushExtensionPropName")] #[xml(unit_variants_ident = "DavPushExtensionPropName")]
pub enum DavPushExtensionProp { pub enum DavPushExtensionProp {
// WebDav Push // WebDav Push

View File

@@ -22,7 +22,7 @@ impl Default for Transports {
} }
} }
#[derive(XmlSerialize, XmlDeserialize, PartialEq, Eq, Clone)] #[derive(XmlSerialize, XmlDeserialize, PartialEq, Eq, Clone, Debug)]
pub struct SupportedTriggers(#[xml(flatten, ty = "untagged")] pub Vec<Trigger>); pub struct SupportedTriggers(#[xml(flatten, ty = "untagged")] pub Vec<Trigger>);
#[derive(XmlSerialize, XmlDeserialize, PartialEq, Eq, Debug, Clone)] #[derive(XmlSerialize, XmlDeserialize, PartialEq, Eq, Debug, Clone)]

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_frontend" name = "rustical_frontend"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true

View File

@@ -13,6 +13,6 @@
"imports": { "imports": {
"@deno/vite-plugin": "npm:@deno/vite-plugin@^1.0.5", "@deno/vite-plugin": "npm:@deno/vite-plugin@^1.0.5",
"lit": "npm:lit@^3.3.1", "lit": "npm:lit@^3.3.1",
"vite": "npm:vite@^7.1.12" "vite": "npm:vite@^7.2.7"
} }
} }

View File

@@ -1,13 +1,13 @@
{ {
"version": "5", "version": "5",
"specifiers": { "specifiers": {
"npm:@deno/vite-plugin@^1.0.5": "1.0.5_vite@7.1.12__picomatch@4.0.3", "npm:@deno/vite-plugin@^1.0.5": "1.0.5_vite@7.2.7__picomatch@4.0.3",
"npm:lit@^3.3.1": "3.3.1", "npm:lit@^3.3.1": "3.3.1",
"npm:vite@*": "7.1.12_picomatch@4.0.3", "npm:vite@*": "7.2.7_picomatch@4.0.3",
"npm:vite@^7.1.12": "7.1.12_picomatch@4.0.3" "npm:vite@^7.2.7": "7.2.7_picomatch@4.0.3"
}, },
"npm": { "npm": {
"@deno/vite-plugin@1.0.5_vite@7.1.12__picomatch@4.0.3": { "@deno/vite-plugin@1.0.5_vite@7.2.7__picomatch@4.0.3": {
"integrity": "sha512-tLja5n4dyMhcze1NzvSs2iiriBymfBlDCZIrjMTxb9O2ru0gvmV6mn5oBD2teNw5Sd92cj3YJzKwsAs8tMJXlg==", "integrity": "sha512-tLja5n4dyMhcze1NzvSs2iiriBymfBlDCZIrjMTxb9O2ru0gvmV6mn5oBD2teNw5Sd92cj3YJzKwsAs8tMJXlg==",
"dependencies": [ "dependencies": [
"vite" "vite"
@@ -397,8 +397,8 @@
"picomatch" "picomatch"
] ]
}, },
"vite@7.1.12_picomatch@4.0.3": { "vite@7.2.7_picomatch@4.0.3": {
"integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==", "integrity": "sha512-ITcnkFeR3+fI8P1wMgItjGrR10170d8auB4EpMLPqmx6uxElH3a/hHGQabSHKdqd4FXWO1nFIp9rRn7JQ34ACQ==",
"dependencies": [ "dependencies": [
"esbuild", "esbuild",
"fdir", "fdir",
@@ -417,7 +417,7 @@
"dependencies": [ "dependencies": [
"npm:@deno/vite-plugin@^1.0.5", "npm:@deno/vite-plugin@^1.0.5",
"npm:lit@^3.3.1", "npm:lit@^3.3.1",
"npm:vite@^7.1.12" "npm:vite@^7.2.7"
] ]
} }
} }

View File

@@ -1,16 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Lit</title>
<link rel="stylesheet" href="./src/index.css" />
<script type="module" src="/src/my-element.ts"></script>
</head>
<body>
<my-element>
<h1>Vite + Lit</h1>
</my-element>
</body>
</html>

View File

@@ -0,0 +1,8 @@
export { CreateAddressbookForm } from './create-addressbook-form.ts'
export { CreateBirthdayCalendarForm } from './create-birthday-calendar-form.ts'
export { CreateCalendarForm } from './create-calendar-form.ts'
export { DeleteButton } from './delete-button.ts'
export { EditAddressbookForm } from './edit-addressbook-form.ts'
export { EditCalendarForm } from './edit-calendar-form.ts'
export { ImportAddressbookForm } from './import-addressbook-form.ts'
export { ImportCalendarForm } from './import-calendar-form.ts'

View File

@@ -36,27 +36,27 @@ export class CreateAddressbookForm extends LitElement {
<form @submit=${this.submit} ${ref(this.form)}> <form @submit=${this.submit} ${ref(this.form)}>
<label> <label>
principal (for group addressbooks) principal (for group addressbooks)
<select name="principal" value=${this.user} @change=${e => this.principal = e.target.value}> <select .value=${this.user} @change=${e => this.principal = e.target.value}>
<option value=${this.user}>${this.user}</option> <option .value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map(membership => html` ${window.rusticalUser.memberships.map(membership => html`
<option value=${membership}>${membership}</option> <option .value=${membership}>${membership}</option>
`)} `)}
</select> </select>
</label> </label>
<br> <br>
<label> <label>
id id
<input type="text" name="id" value=${this.addr_id} @change=${e => this.addr_id = e.target.value} /> <input type="text" .value=${this.addr_id} @change=${e => this.addr_id = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Displayname Displayname
<input type="text" name="displayname" value=${this.displayname} @change=${e => this.displayname = e.target.value} /> <input type="text" .value=${this.displayname} @change=${e => this.displayname = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Description Description
<input type="text" name="description" @change=${e => this.description = e.target.value} /> <input type="text" .value=${this.description} @change=${e => this.description = e.target.value} />
</label> </label>
<br> <br>
<button type="submit">Create</button> <button type="submit">Create</button>

View File

@@ -0,0 +1,102 @@
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";
import { Ref, createRef, ref } from 'lit/directives/ref.js';
import { escapeXml } from ".";
import { getTimezones } from "./timezones.ts";
@customElement("create-birthday-calendar-form")
export class CreateBirthdayCalendarForm extends LitElement {
protected override createRenderRoot() {
return this
}
@property()
principal: string = ''
@property()
addr_id: string = ''
@property()
displayname: string = ''
@property()
description: string = ''
@property()
color: string = ''
dialog: Ref<HTMLDialogElement> = createRef()
form: Ref<HTMLFormElement> = createRef()
@property()
timezones: Array<String> = []
override render() {
return html`
<button @click=${() => this.dialog.value.showModal()}>Create birthday calendar</button>
<dialog ${ref(this.dialog)}>
<h3>Create calendar</h3>
<form @submit=${this.submit} ${ref(this.form)}>
<label>
Displayname
<input type="text" .value=${this.displayname} required @change=${e => this.displayname = e.target.value} />
</label>
<br>
<label>
Description
<input type="text" .value=${this.description} @change=${e => this.description = e.target.value} />
</label>
<br>
<label>
Color
<input type="color" .value=${this.color} @change=${e => this.color = e.target.value} />
</label>
<br>
<button type="submit">Create</button>
<button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button>
</form>
</dialog>
`
}
async submit(e: SubmitEvent) {
e.preventDefault()
if (!this.addr_id) {
alert("Empty id")
return
}
if (!this.displayname) {
alert("Empty displayname")
return
}
let response = await fetch(`/caldav/principal/${this.principal}/_birthdays_${this.addr_id}`, {
method: 'MKCOL',
headers: {
'Content-Type': 'application/xml'
},
body: `
<mkcol xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CS="http://calendarserver.org/ns/" xmlns:ICAL="http://apple.com/ns/ical/">
<set>
<prop>
<displayname>${escapeXml(this.displayname)}</displayname>
${this.description ? `<CAL:calendar-description>${escapeXml(this.description)}</CAL:calendar-description>` : ''}
${this.color ? `<ICAL:calendar-color>${escapeXml(this.color)}</ICAL:calendar-color>` : ''}
<CAL:supported-calendar-component-set>
<CAL:comp name="VEVENT" />
</CAL:supported-calendar-component-set>
</prop>
</set>
</mkcol>
`
})
if (response.status >= 400) {
alert(`Error ${response.status}: ${await response.text()}`)
return null
}
window.location.reload()
return null
}
}
declare global {
interface HTMLElementTagNameMap {
'create-calendar-form': CreateCalendarForm
}
}

View File

@@ -1,15 +1,30 @@
import { html, LitElement } from "lit"; import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js"; import { customElement, property } from "lit/decorators.js";
import { Ref, createRef, ref } from 'lit/directives/ref.js'; import { Ref, createRef, ref } from 'lit/directives/ref.js';
import { escapeXml } from "."; import { escapeXml, SVG_ICON_CALENDAR, SVG_ICON_INTERNET } from ".";
import { getTimezones } from "./timezones.ts";
@customElement("create-calendar-form") @customElement("create-calendar-form")
export class CreateCalendarForm extends LitElement { export class CreateCalendarForm extends LitElement {
constructor() { constructor() {
super() super()
this.resetForm()
this.fetchTimezones() this.fetchTimezones()
} }
resetForm() {
this.form.value?.reset()
this.principal = this.user
this.cal_id = self.crypto.randomUUID()
this.displayname = ''
this.description = ''
this.timezone_id = ''
this.color = ''
this.isSubscription = false
this.subscriptionUrl = null
this.components = new Set(["VEVENT", "VTODO"])
}
async fetchTimezones() { async fetchTimezones() {
this.timezones = await getTimezones() this.timezones = await getTimezones()
} }
@@ -21,23 +36,23 @@ export class CreateCalendarForm extends LitElement {
@property() @property()
user: string = '' user: string = ''
@property() @property()
principal: string = '' principal: string
@property() @property()
cal_id: string = self.crypto.randomUUID() cal_id: string
@property() @property()
displayname: string = '' displayname: string
@property() @property()
description: string = '' description: string
@property() @property()
timezone_id: string = '' timezone_id: string
@property() @property()
color: string = '' color: string
@property() @property()
isSubscription: boolean = false isSubscription: boolean
@property() @property()
subscriptionUrl: string = '' subscriptionUrl: string
@property() @property()
components: Set<"VEVENT" | "VTODO" | "VJOURNAL"> = new Set() components: Set<"VEVENT" | "VTODO" | "VJOURNAL">
dialog: Ref<HTMLDialogElement> = createRef() dialog: Ref<HTMLDialogElement> = createRef()
form: Ref<HTMLFormElement> = createRef() form: Ref<HTMLFormElement> = createRef()
@@ -46,13 +61,13 @@ export class CreateCalendarForm extends LitElement {
override render() { override render() {
return html` return html`
<button @click=${() => this.dialog.value.showModal()}>Create calendar</button> <button @click=${e => this.dialog.value.showModal()}>Create calendar</button>
<dialog ${ref(this.dialog)}> <dialog ${ref(this.dialog)} @close=${e => this.resetForm()}>
<h3>Create calendar</h3> <h3>Create calendar</h3>
<form @submit=${this.submit} ${ref(this.form)}> <form @submit=${this.submit} ${ref(this.form)}>
<label> <label>
principal (for group calendars) principal (for group calendars)
<select name="principal" value=${this.user} @change=${e => this.principal = e.target.value}> <select required value=${this.user} @change=${e => this.principal = e.target.value}>
<option value=${this.user}>${this.user}</option> <option value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map(membership => html` ${window.rusticalUser.memberships.map(membership => html`
<option value=${membership}>${membership}</option> <option value=${membership}>${membership}</option>
@@ -62,17 +77,17 @@ export class CreateCalendarForm extends LitElement {
<br> <br>
<label> <label>
id id
<input type="text" name="id" value=${this.cal_id} @change=${e => this.cal_id = e.target.value} /> <input type="text" required .value=${this.cal_id} @change=${e => this.cal_id = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Displayname Displayname
<input type="text" name="displayname" value=${this.displayname} @change=${e => this.displayname = e.target.value} /> <input type="text" required .value=${this.displayname} @change=${e => this.displayname = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Timezone (optional) Timezone (optional)
<select name="timezone" .value=${this.timezone_id} @change=${e => this.timezone_id = e.target.value}> <select .value=${this.timezone_id} @change=${e => this.timezone_id = e.target.value}>
<option value="">No timezone</option> <option value="">No timezone</option>
${this.timezones.map(timezone => html` ${this.timezones.map(timezone => html`
<option value=${timezone} ?selected=${timezone === this.timezone_id}>${timezone}</option> <option value=${timezone} ?selected=${timezone === this.timezone_id}>${timezone}</option>
@@ -82,45 +97,57 @@ export class CreateCalendarForm extends LitElement {
<br> <br>
<label> <label>
Description Description
<input type="text" name="description" @change=${e => this.description = e.target.value} /> <input type="text" .value=${this.description} @change=${e => this.description = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Color Color
<input type="color" name="color" @change=${e => this.color = e.target.value} /> <input type="color" .value=${this.color} @change=${e => this.color = e.target.value} />
</label> </label>
<br> <br>
<br> <br>
<label> <label>Type</label>
Calendar is subscription to external calendar <div class="tab-radio">
<input type="checkbox" name="is_subscription" @change=${e => this.isSubscription = e.target.checked} /> <label>
</label> <input type="radio" name="type" .checked=${!this.isSubscription} @change=${e => this.isSubscription = false}></input>
${SVG_ICON_CALENDAR}
Calendar
</label>
<label>
<input type="radio" name="type" .checked=${this.isSubscription} @change=${e => this.isSubscription = true}></input>
${SVG_ICON_INTERNET}
webCal Subscription
</label>
</div>
<br> <br>
${this.isSubscription ? html` ${this.isSubscription ? html`
<label> <label>
Subscription URL Subscription URL
<input type="text" name="subscription_url" @change=${e => this.subscriptionUrl = e.target.value} /> <input type="text" pattern="https://.*" .required=${this.isSubscription} .value=${this.subscriptionUrl} @change=${e => this.subscriptionUrl = e.target.value} />
</label> </label>
<br> <br>
<br>
`: html``} `: html``}
<br>
${["VEVENT", "VTODO", "VJOURNAL"].map(comp => html` <label>Components</label>
<label> <div>
Support ${comp} ${["VEVENT", "VTODO", "VJOURNAL"].map(comp => html`
<input type="checkbox" value=${comp} @change=${e => e.target.checked ? this.components.add(e.target.value) : this.components.delete(e.target.value)} /> <label>
</label> Support ${comp}
<br> <input type="checkbox" .value=${comp} @change=${e => e.target.checked ? this.components.add(e.target.value) : this.components.delete(e.target.value)} .checked=${this.components.has(comp)} />
`)} </label>
<br>
`)}
</div>
<br> <br>
<button type="submit">Create</button> <button type="submit">Create</button>
<button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button> <button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close();}} class="cancel">Cancel</button>
</form> </form>
</dialog> </dialog>
` `
} }
async submit(e: SubmitEvent) { async submit(e: SubmitEvent) {
console.log(this.displayname)
e.preventDefault() e.preventDefault()
if (!this.cal_id) { if (!this.cal_id) {
alert("Empty id") alert("Empty id")
@@ -134,6 +161,10 @@ export class CreateCalendarForm extends LitElement {
alert("No calendar components selected") alert("No calendar components selected")
return return
} }
if (this.isSubscription && !this.subscriptionUrl) {
alert("Invalid subscription url")
return
}
let response = await fetch(`/caldav/principal/${this.principal || this.user}/${this.cal_id}`, { let response = await fetch(`/caldav/principal/${this.principal || this.user}/${this.cal_id}`, {
method: 'MKCOL', method: 'MKCOL',

View File

@@ -34,12 +34,12 @@ export class EditAddressbookForm extends LitElement {
<form @submit=${this.submit} ${ref(this.form)}> <form @submit=${this.submit} ${ref(this.form)}>
<label> <label>
Displayname Displayname
<input type="text" name="displayname" .value=${this.displayname} @change=${e => this.displayname = e.target.value} /> <input type="text" .value=${this.displayname} @change=${e => this.displayname = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Description Description
<input type="text" name="description" .value=${this.description} @change=${e => this.description = e.target.value} /> <input type="text" .value=${this.description} @change=${e => this.description = e.target.value} />
</label> </label>
<br> <br>
<button type="submit">Submit</button> <button type="submit">Submit</button>

View File

@@ -53,12 +53,12 @@ export class EditCalendarForm extends LitElement {
<form @submit=${this.submit} ${ref(this.form)}> <form @submit=${this.submit} ${ref(this.form)}>
<label> <label>
Displayname Displayname
<input type="text" name="displayname" .value=${this.displayname} @change=${e => this.displayname = e.target.value} /> <input type="text" required .value=${this.displayname} @change=${e => this.displayname = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Timezone (optional) Timezone (optional)
<select name="timezone" .value=${this.timezone_id} @change=${e => this.timezone_id = e.target.value}> <select .value=${this.timezone_id} @change=${e => this.timezone_id = e.target.value}>
<option value="">No timezone</option> <option value="">No timezone</option>
${this.timezones.map(timezone => html` ${this.timezones.map(timezone => html`
<option value=${timezone} ?selected=${timezone === this.timezone_id}>${timezone}</option> <option value=${timezone} ?selected=${timezone === this.timezone_id}>${timezone}</option>
@@ -68,18 +68,18 @@ export class EditCalendarForm extends LitElement {
<br> <br>
<label> <label>
Description Description
<input type="text" name="description" .value=${this.description} @change=${e => this.description = e.target.value} /> <input type="text" .value=${this.description} @change=${e => this.description = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
Color Color
<input type="color" name="color" .value=${this.color} @change=${e => this.color = e.target.value} /> <input type="color" .value=${this.color} @change=${e => this.color = e.target.value} />
</label> </label>
<br> <br>
${["VEVENT", "VTODO", "VJOURNAL"].map(comp => html` ${["VEVENT", "VTODO", "VJOURNAL"].map(comp => html`
<label> <label>
Support ${comp} Support ${comp}
<input type="checkbox" value=${comp} ?checked=${this.components.has(comp)} @change=${e => e.target.checked ? this.components.add(e.target.value) : this.components.delete(e.target.value)} /> <input type="checkbox" .value=${comp} ?checked=${this.components.has(comp)} @change=${e => e.target.checked ? this.components.add(e.target.value) : this.components.delete(e.target.value)} />
</label> </label>
<br> <br>
`)} `)}

View File

@@ -32,23 +32,25 @@ export class ImportAddressbookForm extends LitElement {
<form @submit=${this.submit} ${ref(this.form)}> <form @submit=${this.submit} ${ref(this.form)}>
<label> <label>
principal (for group addressbook) principal (for group addressbook)
<select name="principal" value=${this.user} @change=${e => this.principal = e.target.value}> <select name="principal" required .value=${this.user} @change=${e => this.principal = e.target.value}>
<option value=${this.user}>${this.user}</option> <option .value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map(membership => html` ${window.rusticalUser.memberships.map(membership => html`
<option value=${membership}>${membership}</option> <option .value=${membership}>${membership}</option>
`)} `)}
</select> </select>
</label> </label>
<br> <br>
<label> <label>
id id
<input type="text" name="id" value=${this.addressbook_id} @change=${e => this.addressbook_id = e.target.value} /> <input type="text" required .value=${this.addressbook_id} @change=${e => this.addressbook_id = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
file file
<input type="file" accept="text/vcard" name="file" @change=${e => this.file = e.target.files[0]} /> <input type="file" accept="text/vcard" required @change=${e => this.file = e.target.files[0]} />
</label> </label>
<br>
<br>
<button type="submit">Import</button> <button type="submit">Import</button>
<button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button> <button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button>
</form> </form>

View File

@@ -32,23 +32,25 @@ export class ImportCalendarForm extends LitElement {
<form @submit=${this.submit} ${ref(this.form)}> <form @submit=${this.submit} ${ref(this.form)}>
<label> <label>
principal (for group calendars) principal (for group calendars)
<select name="principal" value=${this.user} @change=${e => this.principal = e.target.value}> <select name="principal" required .value=${this.user} @change=${e => this.principal = e.target.value}>
<option value=${this.user}>${this.user}</option> <option .value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map(membership => html` ${window.rusticalUser.memberships.map(membership => html`
<option value=${membership}>${membership}</option> <option .value=${membership}>${membership}</option>
`)} `)}
</select> </select>
</label> </label>
<br> <br>
<label> <label>
id id
<input type="text" name="id" value=${this.cal_id} @change=${e => this.cal_id = e.target.value} /> <input type="text" required .value=${this.cal_id} @change=${e => this.cal_id = e.target.value} />
</label> </label>
<br> <br>
<label> <label>
file file
<input type="file" accept="text/calendar" name="file" @change=${e => this.file = e.target.files[0]} /> <input type="file" required accept="text/calendar" @change=${e => this.file = e.target.files[0]} />
</label> </label>
<br>
<br>
<button type="submit">Import</button> <button type="submit">Import</button>
<button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button> <button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button>
</form> </form>

View File

@@ -1,3 +1,5 @@
import {svg} from 'lit'
export function escapeXml(unsafe: string): string { export function escapeXml(unsafe: string): string {
return unsafe.replace(/&/g, '&amp;') return unsafe.replace(/&/g, '&amp;')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
@@ -5,3 +7,23 @@ export function escapeXml(unsafe: string): string {
.replace(/"/g, '&quot;') .replace(/"/g, '&quot;')
.replace(/'/g, '&apos;') .replace(/'/g, '&apos;')
} }
export const SVG_ICON_CALENDAR = svg`<!-- Adapted from https://iconoir.com/ -->
<svg width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon">
<path d="M15 4V2M15 4V6M15 4H10.5M3 10V19C3 20.1046 3.89543 21 5 21H19C20.1046 21 21 20.1046 21 19V10H3Z" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M3 10V6C3 4.89543 3.89543 4 5 4H7" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M7 2V6" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M21 10V6C21 4.89543 20.1046 4 19 4H18.5" stroke-linecap="round" stroke-linejoin="round"></path>
</svg>
`
export const SVG_ICON_INTERNET = svg`<!-- Adapted from https://iconoir.com/ -->
<svg class="icon" width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M13 2.04932C13 2.04932 16 5.99994 16 11.9999" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M11 21.9506C11 21.9506 8 17.9999 8 11.9999C8 5.99994 11 2.04932 11 2.04932" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M2.62964 15.5H12" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M2.62964 8.5H21.3704" stroke-linecap="round" stroke-linejoin="round"></path>
<path fill-rule="evenodd" clip-rule="evenodd" d="M21.8789 17.9174C22.3727 18.2211 22.3423 18.9604 21.8337 19.0181L19.2671 19.309L18.1159 21.6213C17.8878 22.0795 17.1827 21.8552 17.0661 21.2873L15.8108 15.1713C15.7123 14.6913 16.1437 14.3892 16.561 14.646L21.8789 17.9174Z"></path>
</svg>
`

View File

@@ -14,20 +14,14 @@ export default defineConfig({
rollupOptions: { rollupOptions: {
input: [ input: [
"lib/create-calendar-form.ts", "lib/bundle.ts",
"lib/edit-calendar-form.ts",
"lib/import-calendar-form.ts",
"lib/create-addressbook-form.ts",
"lib/edit-addressbook-form.ts",
"lib/import-addressbook-form.ts",
"lib/delete-button.ts",
], ],
output: { output: {
dir: "../public/assets/js/", dir: "../public/assets/js/",
format: "es", format: "es",
manualChunks: { // manualChunks: {
lit: ["lit"], // lit: ["lit"],
} // }
} }
}, },
}, },

File diff suppressed because it is too large Load Diff

View File

@@ -1,125 +0,0 @@
import { i, x } from "./lit-DkXrt_Iv.mjs";
import { n as n$1, t } from "./property-B8WoKf1Y.mjs";
import { e, n } from "./ref-BwbQvJBB.mjs";
import { e as escapeXml } from "./index-_IB1wMbZ.mjs";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i2 = decorators.length - 1, decorator; i2 >= 0; i2--)
if (decorator = decorators[i2])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
let CreateAddressbookForm = class extends i {
constructor() {
super();
this.user = "";
this.principal = "";
this.addr_id = self.crypto.randomUUID();
this.displayname = "";
this.description = "";
this.dialog = e();
this.form = e();
}
createRenderRoot() {
return this;
}
render() {
return x`
<button @click=${() => this.dialog.value.showModal()}>Create addressbook</button>
<dialog ${n(this.dialog)}>
<h3>Create addressbook</h3>
<form @submit=${this.submit} ${n(this.form)}>
<label>
principal (for group addressbooks)
<select name="principal" value=${this.user} @change=${(e2) => this.principal = e2.target.value}>
<option value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map((membership) => x`
<option value=${membership}>${membership}</option>
`)}
</select>
</label>
<br>
<label>
id
<input type="text" name="id" value=${this.addr_id} @change=${(e2) => this.addr_id = e2.target.value} />
</label>
<br>
<label>
Displayname
<input type="text" name="displayname" value=${this.displayname} @change=${(e2) => this.displayname = e2.target.value} />
</label>
<br>
<label>
Description
<input type="text" name="description" @change=${(e2) => this.description = e2.target.value} />
</label>
<br>
<button type="submit">Create</button>
<button type="submit" @click=${(event) => {
event.preventDefault();
this.dialog.value.close();
this.form.value.reset();
}} class="cancel">Cancel</button>
</form>
</dialog>
`;
}
async submit(e2) {
console.log(this.displayname);
e2.preventDefault();
if (!this.addr_id) {
alert("Empty id");
return;
}
if (!this.displayname) {
alert("Empty displayname");
return;
}
let response = await fetch(`/carddav/principal/${this.principal || this.user}/${this.addr_id}`, {
method: "MKCOL",
headers: {
"Content-Type": "application/xml"
},
body: `
<mkcol xmlns="DAV:" xmlns:CARD="urn:ietf:params:xml:ns:carddav">
<set>
<prop>
<displayname>${escapeXml(this.displayname)}</displayname>
${this.description ? `<CARD:addressbook-description>${escapeXml(this.description)}</CARD:addressbook-description>` : ""}
</prop>
</set>
</mkcol>
`
});
if (response.status >= 400) {
alert(`Error ${response.status}: ${await response.text()}`);
return null;
}
window.location.reload();
return null;
}
};
__decorateClass([
n$1()
], CreateAddressbookForm.prototype, "user", 2);
__decorateClass([
n$1()
], CreateAddressbookForm.prototype, "principal", 2);
__decorateClass([
n$1()
], CreateAddressbookForm.prototype, "addr_id", 2);
__decorateClass([
n$1()
], CreateAddressbookForm.prototype, "displayname", 2);
__decorateClass([
n$1()
], CreateAddressbookForm.prototype, "description", 2);
CreateAddressbookForm = __decorateClass([
t("create-addressbook-form")
], CreateAddressbookForm);
export {
CreateAddressbookForm
};

View File

@@ -1,200 +0,0 @@
import { i, x } from "./lit-DkXrt_Iv.mjs";
import { n as n$1, t } from "./property-B8WoKf1Y.mjs";
import { e, n } from "./ref-BwbQvJBB.mjs";
import { e as escapeXml } from "./index-_IB1wMbZ.mjs";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i2 = decorators.length - 1, decorator; i2 >= 0; i2--)
if (decorator = decorators[i2])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
let CreateCalendarForm = class extends i {
constructor() {
super();
this.user = "";
this.principal = "";
this.cal_id = self.crypto.randomUUID();
this.displayname = "";
this.description = "";
this.timezone_id = "";
this.color = "";
this.isSubscription = false;
this.subscriptionUrl = "";
this.components = /* @__PURE__ */ new Set();
this.dialog = e();
this.form = e();
this.timezones = [];
this.fetchTimezones();
}
async fetchTimezones() {
this.timezones = await getTimezones();
}
createRenderRoot() {
return this;
}
render() {
return x`
<button @click=${() => this.dialog.value.showModal()}>Create calendar</button>
<dialog ${n(this.dialog)}>
<h3>Create calendar</h3>
<form @submit=${this.submit} ${n(this.form)}>
<label>
principal (for group calendars)
<select name="principal" value=${this.user} @change=${(e2) => this.principal = e2.target.value}>
<option value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map((membership) => x`
<option value=${membership}>${membership}</option>
`)}
</select>
</label>
<br>
<label>
id
<input type="text" name="id" value=${this.cal_id} @change=${(e2) => this.cal_id = e2.target.value} />
</label>
<br>
<label>
Displayname
<input type="text" name="displayname" value=${this.displayname} @change=${(e2) => this.displayname = e2.target.value} />
</label>
<br>
<label>
Timezone (optional)
<select name="timezone" .value=${this.timezone_id} @change=${(e2) => this.timezone_id = e2.target.value}>
<option value="">No timezone</option>
${this.timezones.map((timezone) => x`
<option value=${timezone} ?selected=${timezone === this.timezone_id}>${timezone}</option>
`)}
</select>
</label>
<br>
<label>
Description
<input type="text" name="description" @change=${(e2) => this.description = e2.target.value} />
</label>
<br>
<label>
Color
<input type="color" name="color" @change=${(e2) => this.color = e2.target.value} />
</label>
<br>
<br>
<label>
Calendar is subscription to external calendar
<input type="checkbox" name="is_subscription" @change=${(e2) => this.isSubscription = e2.target.checked} />
</label>
<br>
${this.isSubscription ? x`
<label>
Subscription URL
<input type="text" name="subscription_url" @change=${(e2) => this.subscriptionUrl = e2.target.value} />
</label>
<br>
` : x``}
<br>
${["VEVENT", "VTODO", "VJOURNAL"].map((comp) => x`
<label>
Support ${comp}
<input type="checkbox" value=${comp} @change=${(e2) => e2.target.checked ? this.components.add(e2.target.value) : this.components.delete(e2.target.value)} />
</label>
<br>
`)}
<br>
<button type="submit">Create</button>
<button type="submit" @click=${(event) => {
event.preventDefault();
this.dialog.value.close();
this.form.value.reset();
}} class="cancel">Cancel</button>
</form>
</dialog>
`;
}
async submit(e2) {
console.log(this.displayname);
e2.preventDefault();
if (!this.cal_id) {
alert("Empty id");
return;
}
if (!this.displayname) {
alert("Empty displayname");
return;
}
if (!this.components.size) {
alert("No calendar components selected");
return;
}
let response = await fetch(`/caldav/principal/${this.principal || this.user}/${this.cal_id}`, {
method: "MKCOL",
headers: {
"Content-Type": "application/xml"
},
body: `
<mkcol xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CS="http://calendarserver.org/ns/" xmlns:ICAL="http://apple.com/ns/ical/">
<set>
<prop>
<displayname>${escapeXml(this.displayname)}</displayname>
${this.timezone_id ? `<CAL:calendar-timezone-id>${escapeXml(this.timezone_id)}</CAL:calendar-timezone-id>` : ""}
${this.description ? `<CAL:calendar-description>${escapeXml(this.description)}</CAL:calendar-description>` : ""}
${this.color ? `<ICAL:calendar-color>${escapeXml(this.color)}</ICAL:calendar-color>` : ""}
${this.isSubscription && this.subscriptionUrl ? `<CS:source><href>${escapeXml(this.subscriptionUrl)}</href></CS:source>` : ""}
<CAL:supported-calendar-component-set>
${Array.from(this.components.keys()).map((comp) => `<CAL:comp name="${escapeXml(comp)}" />`).join("\n")}
</CAL:supported-calendar-component-set>
</prop>
</set>
</mkcol>
`
});
if (response.status >= 400) {
alert(`Error ${response.status}: ${await response.text()}`);
return null;
}
window.location.reload();
return null;
}
};
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "user", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "principal", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "cal_id", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "displayname", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "description", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "timezone_id", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "color", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "isSubscription", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "subscriptionUrl", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "components", 2);
__decorateClass([
n$1()
], CreateCalendarForm.prototype, "timezones", 2);
CreateCalendarForm = __decorateClass([
t("create-calendar-form")
], CreateCalendarForm);
export {
CreateCalendarForm
};

View File

@@ -1,55 +0,0 @@
import { i, x } from "./lit-DkXrt_Iv.mjs";
import { n, t } from "./property-B8WoKf1Y.mjs";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i2 = decorators.length - 1, decorator; i2 >= 0; i2--)
if (decorator = decorators[i2])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
let DeleteButton = class extends i {
constructor() {
super();
this.trash = false;
}
createRenderRoot() {
return this;
}
render() {
let text = this.trash ? "Trash" : "Delete";
return x`<button class="delete" @click=${(e) => this._onClick(e)}>${text}</button>`;
}
async _onClick(event) {
event.preventDefault();
if (!this.trash && !confirm("Do you want to delete this collection permanently?")) {
return;
}
let response = await fetch(this.href, {
method: "DELETE",
headers: {
"X-No-Trashbin": this.trash ? "0" : "1"
}
});
if (response.status < 200 || response.status >= 300) {
alert("An error occured, look into the console");
console.error(response);
return;
}
window.location.reload();
}
};
__decorateClass([
n({ type: Boolean })
], DeleteButton.prototype, "trash", 2);
__decorateClass([
n()
], DeleteButton.prototype, "href", 2);
DeleteButton = __decorateClass([
t("delete-button")
], DeleteButton);
export {
DeleteButton
};

View File

@@ -1,114 +0,0 @@
import { i, x } from "./lit-DkXrt_Iv.mjs";
import { n as n$1, t } from "./property-B8WoKf1Y.mjs";
import { e, n } from "./ref-BwbQvJBB.mjs";
import { e as escapeXml } from "./index-_IB1wMbZ.mjs";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i2 = decorators.length - 1, decorator; i2 >= 0; i2--)
if (decorator = decorators[i2])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
let EditAddressbookForm = class extends i {
constructor() {
super();
this.principal = "";
this.addr_id = "";
this.displayname = "";
this.description = "";
this.dialog = e();
this.form = e();
}
createRenderRoot() {
return this;
}
render() {
return x`
<button @click=${() => this.dialog.value.showModal()}>Edit</button>
<dialog ${n(this.dialog)}>
<h3>Edit addressbook</h3>
<form @submit=${this.submit} ${n(this.form)}>
<label>
Displayname
<input type="text" name="displayname" .value=${this.displayname} @change=${(e2) => this.displayname = e2.target.value} />
</label>
<br>
<label>
Description
<input type="text" name="description" .value=${this.description} @change=${(e2) => this.description = e2.target.value} />
</label>
<br>
<button type="submit">Submit</button>
<button type="submit" @click=${(event) => {
event.preventDefault();
this.dialog.value.close();
this.form.value.reset();
}} class="cancel">Cancel</button>
</form>
</dialog>
`;
}
async submit(e2) {
e2.preventDefault();
if (!this.principal) {
alert("Empty principal");
return;
}
if (!this.addr_id) {
alert("Empty id");
return;
}
if (!this.displayname) {
alert("Empty displayname");
return;
}
let response = await fetch(`/carddav/principal/${this.principal}/${this.addr_id}`, {
method: "PROPPATCH",
headers: {
"Content-Type": "application/xml"
},
body: `
<propertyupdate xmlns="DAV:" xmlns:CARD="urn:ietf:params:xml:ns:carddav">
<set>
<prop>
<displayname>${escapeXml(this.displayname)}</displayname>
${this.description ? `<CARD:addressbook-description>${escapeXml(this.description)}</CARD:addressbook-description>` : ""}
</prop>
</set>
<remove>
<prop>
${!this.description ? "<CARD:calendar-description />" : ""}
</prop>
</remove>
</propertyupdate>
`
});
if (response.status >= 400) {
alert(`Error ${response.status}: ${await response.text()}`);
return null;
}
window.location.reload();
return null;
}
};
__decorateClass([
n$1()
], EditAddressbookForm.prototype, "principal", 2);
__decorateClass([
n$1()
], EditAddressbookForm.prototype, "addr_id", 2);
__decorateClass([
n$1()
], EditAddressbookForm.prototype, "displayname", 2);
__decorateClass([
n$1()
], EditAddressbookForm.prototype, "description", 2);
EditAddressbookForm = __decorateClass([
t("edit-addressbook-form")
], EditAddressbookForm);
export {
EditAddressbookForm
};

View File

@@ -1,183 +0,0 @@
import { i, x } from "./lit-DkXrt_Iv.mjs";
import { n as n$1, t } from "./property-B8WoKf1Y.mjs";
import { e, n } from "./ref-BwbQvJBB.mjs";
import { e as escapeXml } from "./index-_IB1wMbZ.mjs";
let timezonesPromise = null;
async function getTimezones() {
timezonesPromise ||= new Promise(async (resolve, reject) => {
try {
let response = await fetch("/frontend/_timezones.json");
resolve(await response.json());
} catch (e2) {
reject(e2);
}
});
return await timezonesPromise;
}
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i2 = decorators.length - 1, decorator; i2 >= 0; i2--)
if (decorator = decorators[i2])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
let EditCalendarForm = class extends i {
constructor() {
super();
this.displayname = "";
this.description = "";
this.timezone_id = "";
this.color = "";
this.components = /* @__PURE__ */ new Set();
this.dialog = e();
this.form = e();
this.timezones = [];
this.fetchTimezones();
}
async fetchTimezones() {
this.timezones = await getTimezones();
}
createRenderRoot() {
return this;
}
render() {
return x`
<button @click=${() => this.dialog.value.showModal()}>Edit</button>
<dialog ${n(this.dialog)}>
<h3>Edit calendar</h3>
<form @submit=${this.submit} ${n(this.form)}>
<label>
Displayname
<input type="text" name="displayname" .value=${this.displayname} @change=${(e2) => this.displayname = e2.target.value} />
</label>
<br>
<label>
Timezone (optional)
<select name="timezone" .value=${this.timezone_id} @change=${(e2) => this.timezone_id = e2.target.value}>
<option value="">No timezone</option>
${this.timezones.map((timezone) => x`
<option value=${timezone} ?selected=${timezone === this.timezone_id}>${timezone}</option>
`)}
</select>
</label>
<br>
<label>
Description
<input type="text" name="description" .value=${this.description} @change=${(e2) => this.description = e2.target.value} />
</label>
<br>
<label>
Color
<input type="color" name="color" .value=${this.color} @change=${(e2) => this.color = e2.target.value} />
</label>
<br>
${["VEVENT", "VTODO", "VJOURNAL"].map((comp) => x`
<label>
Support ${comp}
<input type="checkbox" value=${comp} ?checked=${this.components.has(comp)} @change=${(e2) => e2.target.checked ? this.components.add(e2.target.value) : this.components.delete(e2.target.value)} />
</label>
<br>
`)}
<br>
<button type="submit">Submit</button>
<button type="submit" @click=${(event) => {
event.preventDefault();
this.dialog.value.close();
this.form.value.reset();
}} class="cancel">Cancel</button>
</form>
</dialog>
`;
}
async submit(e2) {
e2.preventDefault();
if (!this.principal) {
alert("Empty principal");
return;
}
if (!this.cal_id) {
alert("Empty id");
return;
}
if (!this.displayname) {
alert("Empty displayname");
return;
}
if (!this.components.size) {
alert("No calendar components selected");
return;
}
let response = await fetch(`/caldav/principal/${this.principal}/${this.cal_id}`, {
method: "PROPPATCH",
headers: {
"Content-Type": "application/xml"
},
body: `
<propertyupdate xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CS="http://calendarserver.org/ns/" xmlns:ICAL="http://apple.com/ns/ical/">
<set>
<prop>
<displayname>${escapeXml(this.displayname)}</displayname>
${this.timezone_id ? `<CAL:calendar-timezone-id>${escapeXml(this.timezone_id)}</CAL:calendar-timezone-id>` : ""}
${this.description ? `<CAL:calendar-description>${escapeXml(this.description)}</CAL:calendar-description>` : ""}
${this.color ? `<ICAL:calendar-color>${escapeXml(this.color)}</ICAL:calendar-color>` : ""}
<CAL:supported-calendar-component-set>
${Array.from(this.components.keys()).map((comp) => `<CAL:comp name="${escapeXml(comp)}" />`).join("\n")}
</CAL:supported-calendar-component-set>
</prop>
</set>
<remove>
<prop>
${!this.timezone_id ? `<CAL:calendar-timezone-id />` : ""}
${!this.description ? "<CAL:calendar-description />" : ""}
${!this.color ? "<ICAL:calendar-color />" : ""}
</prop>
</remove>
</propertyupdate>
`
});
if (response.status >= 400) {
alert(`Error ${response.status}: ${await response.text()}`);
return null;
}
window.location.reload();
return null;
}
};
__decorateClass([
n$1()
], EditCalendarForm.prototype, "principal", 2);
__decorateClass([
n$1()
], EditCalendarForm.prototype, "cal_id", 2);
__decorateClass([
n$1()
], EditCalendarForm.prototype, "displayname", 2);
__decorateClass([
n$1()
], EditCalendarForm.prototype, "description", 2);
__decorateClass([
n$1()
], EditCalendarForm.prototype, "timezone_id", 2);
__decorateClass([
n$1()
], EditCalendarForm.prototype, "color", 2);
__decorateClass([
n$1({
converter: {
fromAttribute: (value, _type) => new Set(value ? JSON.parse(value) : []),
toAttribute: (value, _type) => JSON.stringify(value)
}
})
], EditCalendarForm.prototype, "components", 2);
__decorateClass([
n$1()
], EditCalendarForm.prototype, "timezones", 2);
EditCalendarForm = __decorateClass([
t("edit-calendar-form")
], EditCalendarForm);
export {
EditCalendarForm
};

View File

@@ -1,100 +0,0 @@
import { i, x } from "./lit-DkXrt_Iv.mjs";
import { n as n$1, t } from "./property-B8WoKf1Y.mjs";
import { e, n } from "./ref-BwbQvJBB.mjs";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i2 = decorators.length - 1, decorator; i2 >= 0; i2--)
if (decorator = decorators[i2])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
let ImportAddressbookForm = class extends i {
constructor() {
super();
this.user = "";
this.addressbook_id = self.crypto.randomUUID();
this.dialog = e();
this.form = e();
}
createRenderRoot() {
return this;
}
render() {
return x`
<button @click=${() => this.dialog.value.showModal()}>Import addressbook</button>
<dialog ${n(this.dialog)}>
<h3>Import addressbook</h3>
<form @submit=${this.submit} ${n(this.form)}>
<label>
principal (for group addressbook)
<select name="principal" value=${this.user} @change=${(e2) => this.principal = e2.target.value}>
<option value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map((membership) => x`
<option value=${membership}>${membership}</option>
`)}
</select>
</label>
<br>
<label>
id
<input type="text" name="id" value=${this.addressbook_id} @change=${(e2) => this.addressbook_id = e2.target.value} />
</label>
<br>
<label>
file
<input type="file" accept="text/vcard" name="file" @change=${(e2) => this.file = e2.target.files[0]} />
</label>
<button type="submit">Import</button>
<button type="submit" @click=${(event) => {
event.preventDefault();
this.dialog.value.close();
this.form.value.reset();
}} class="cancel">Cancel</button>
</form>
</dialog>
`;
}
async submit(e2) {
e2.preventDefault();
this.principal ||= this.user;
if (!this.principal) {
alert("Empty principal");
return;
}
if (!this.addressbook_id) {
alert("Empty id");
return;
}
let response = await fetch(`/carddav/principal/${this.principal}/${this.addressbook_id}`, {
method: "IMPORT",
headers: {
"Content-Type": "text/vcard"
},
body: this.file
});
if (response.status >= 400) {
alert(`Error ${response.status}: ${await response.text()}`);
return null;
}
window.location.reload();
return null;
}
};
__decorateClass([
n$1()
], ImportAddressbookForm.prototype, "user", 2);
__decorateClass([
n$1()
], ImportAddressbookForm.prototype, "principal", 2);
__decorateClass([
n$1()
], ImportAddressbookForm.prototype, "addressbook_id", 2);
ImportAddressbookForm = __decorateClass([
t("import-addressbook-form")
], ImportAddressbookForm);
export {
ImportAddressbookForm
};

View File

@@ -1,100 +0,0 @@
import { i, x } from "./lit-DkXrt_Iv.mjs";
import { n as n$1, t } from "./property-B8WoKf1Y.mjs";
import { e, n } from "./ref-BwbQvJBB.mjs";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i2 = decorators.length - 1, decorator; i2 >= 0; i2--)
if (decorator = decorators[i2])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
let ImportCalendarForm = class extends i {
constructor() {
super();
this.user = "";
this.cal_id = self.crypto.randomUUID();
this.dialog = e();
this.form = e();
}
createRenderRoot() {
return this;
}
render() {
return x`
<button @click=${() => this.dialog.value.showModal()}>Import calendar</button>
<dialog ${n(this.dialog)}>
<h3>Import calendar</h3>
<form @submit=${this.submit} ${n(this.form)}>
<label>
principal (for group calendars)
<select name="principal" value=${this.user} @change=${(e2) => this.principal = e2.target.value}>
<option value=${this.user}>${this.user}</option>
${window.rusticalUser.memberships.map((membership) => x`
<option value=${membership}>${membership}</option>
`)}
</select>
</label>
<br>
<label>
id
<input type="text" name="id" value=${this.cal_id} @change=${(e2) => this.cal_id = e2.target.value} />
</label>
<br>
<label>
file
<input type="file" accept="text/calendar" name="file" @change=${(e2) => this.file = e2.target.files[0]} />
</label>
<button type="submit">Import</button>
<button type="submit" @click=${(event) => {
event.preventDefault();
this.dialog.value.close();
this.form.value.reset();
}} class="cancel">Cancel</button>
</form>
</dialog>
`;
}
async submit(e2) {
e2.preventDefault();
this.principal ||= this.user;
if (!this.principal) {
alert("Empty principal");
return;
}
if (!this.cal_id) {
alert("Empty id");
return;
}
let response = await fetch(`/caldav/principal/${this.principal}/${this.cal_id}`, {
method: "IMPORT",
headers: {
"Content-Type": "text/calendar"
},
body: this.file
});
if (response.status >= 400) {
alert(`Error ${response.status}: ${await response.text()}`);
return null;
}
window.location.reload();
return null;
}
};
__decorateClass([
n$1()
], ImportCalendarForm.prototype, "user", 2);
__decorateClass([
n$1()
], ImportCalendarForm.prototype, "principal", 2);
__decorateClass([
n$1()
], ImportCalendarForm.prototype, "cal_id", 2);
ImportCalendarForm = __decorateClass([
t("import-calendar-form")
], ImportCalendarForm);
export {
ImportCalendarForm
};

View File

@@ -1,6 +0,0 @@
function escapeXml(unsafe) {
return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
export {
escapeXml as e
};

View File

@@ -1,520 +0,0 @@
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const t$1 = globalThis, e$2 = t$1.ShadowRoot && (void 0 === t$1.ShadyCSS || t$1.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype, s$2 = Symbol(), o$3 = /* @__PURE__ */ new WeakMap();
let n$2 = class n {
constructor(t2, e2, o2) {
if (this._$cssResult$ = true, o2 !== s$2) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");
this.cssText = t2, this.t = e2;
}
get styleSheet() {
let t2 = this.o;
const s2 = this.t;
if (e$2 && void 0 === t2) {
const e2 = void 0 !== s2 && 1 === s2.length;
e2 && (t2 = o$3.get(s2)), void 0 === t2 && ((this.o = t2 = new CSSStyleSheet()).replaceSync(this.cssText), e2 && o$3.set(s2, t2));
}
return t2;
}
toString() {
return this.cssText;
}
};
const r$2 = (t2) => new n$2("string" == typeof t2 ? t2 : t2 + "", void 0, s$2), S$1 = (s2, o2) => {
if (e$2) s2.adoptedStyleSheets = o2.map(((t2) => t2 instanceof CSSStyleSheet ? t2 : t2.styleSheet));
else for (const e2 of o2) {
const o3 = document.createElement("style"), n3 = t$1.litNonce;
void 0 !== n3 && o3.setAttribute("nonce", n3), o3.textContent = e2.cssText, s2.appendChild(o3);
}
}, c$2 = e$2 ? (t2) => t2 : (t2) => t2 instanceof CSSStyleSheet ? ((t3) => {
let e2 = "";
for (const s2 of t3.cssRules) e2 += s2.cssText;
return r$2(e2);
})(t2) : t2;
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const { is: i$2, defineProperty: e$1, getOwnPropertyDescriptor: h$1, getOwnPropertyNames: r$1, getOwnPropertySymbols: o$2, getPrototypeOf: n$1 } = Object, a$1 = globalThis, c$1 = a$1.trustedTypes, l$1 = c$1 ? c$1.emptyScript : "", p$1 = a$1.reactiveElementPolyfillSupport, d$1 = (t2, s2) => t2, u$1 = { toAttribute(t2, s2) {
switch (s2) {
case Boolean:
t2 = t2 ? l$1 : null;
break;
case Object:
case Array:
t2 = null == t2 ? t2 : JSON.stringify(t2);
}
return t2;
}, fromAttribute(t2, s2) {
let i2 = t2;
switch (s2) {
case Boolean:
i2 = null !== t2;
break;
case Number:
i2 = null === t2 ? null : Number(t2);
break;
case Object:
case Array:
try {
i2 = JSON.parse(t2);
} catch (t3) {
i2 = null;
}
}
return i2;
} }, f$1 = (t2, s2) => !i$2(t2, s2), b = { attribute: true, type: String, converter: u$1, reflect: false, useDefault: false, hasChanged: f$1 };
Symbol.metadata ??= Symbol("metadata"), a$1.litPropertyMetadata ??= /* @__PURE__ */ new WeakMap();
let y$1 = class y extends HTMLElement {
static addInitializer(t2) {
this._$Ei(), (this.l ??= []).push(t2);
}
static get observedAttributes() {
return this.finalize(), this._$Eh && [...this._$Eh.keys()];
}
static createProperty(t2, s2 = b) {
if (s2.state && (s2.attribute = false), this._$Ei(), this.prototype.hasOwnProperty(t2) && ((s2 = Object.create(s2)).wrapped = true), this.elementProperties.set(t2, s2), !s2.noAccessor) {
const i2 = Symbol(), h2 = this.getPropertyDescriptor(t2, i2, s2);
void 0 !== h2 && e$1(this.prototype, t2, h2);
}
}
static getPropertyDescriptor(t2, s2, i2) {
const { get: e2, set: r2 } = h$1(this.prototype, t2) ?? { get() {
return this[s2];
}, set(t3) {
this[s2] = t3;
} };
return { get: e2, set(s3) {
const h2 = e2?.call(this);
r2?.call(this, s3), this.requestUpdate(t2, h2, i2);
}, configurable: true, enumerable: true };
}
static getPropertyOptions(t2) {
return this.elementProperties.get(t2) ?? b;
}
static _$Ei() {
if (this.hasOwnProperty(d$1("elementProperties"))) return;
const t2 = n$1(this);
t2.finalize(), void 0 !== t2.l && (this.l = [...t2.l]), this.elementProperties = new Map(t2.elementProperties);
}
static finalize() {
if (this.hasOwnProperty(d$1("finalized"))) return;
if (this.finalized = true, this._$Ei(), this.hasOwnProperty(d$1("properties"))) {
const t3 = this.properties, s2 = [...r$1(t3), ...o$2(t3)];
for (const i2 of s2) this.createProperty(i2, t3[i2]);
}
const t2 = this[Symbol.metadata];
if (null !== t2) {
const s2 = litPropertyMetadata.get(t2);
if (void 0 !== s2) for (const [t3, i2] of s2) this.elementProperties.set(t3, i2);
}
this._$Eh = /* @__PURE__ */ new Map();
for (const [t3, s2] of this.elementProperties) {
const i2 = this._$Eu(t3, s2);
void 0 !== i2 && this._$Eh.set(i2, t3);
}
this.elementStyles = this.finalizeStyles(this.styles);
}
static finalizeStyles(s2) {
const i2 = [];
if (Array.isArray(s2)) {
const e2 = new Set(s2.flat(1 / 0).reverse());
for (const s3 of e2) i2.unshift(c$2(s3));
} else void 0 !== s2 && i2.push(c$2(s2));
return i2;
}
static _$Eu(t2, s2) {
const i2 = s2.attribute;
return false === i2 ? void 0 : "string" == typeof i2 ? i2 : "string" == typeof t2 ? t2.toLowerCase() : void 0;
}
constructor() {
super(), this._$Ep = void 0, this.isUpdatePending = false, this.hasUpdated = false, this._$Em = null, this._$Ev();
}
_$Ev() {
this._$ES = new Promise(((t2) => this.enableUpdating = t2)), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), this.constructor.l?.forEach(((t2) => t2(this)));
}
addController(t2) {
(this._$EO ??= /* @__PURE__ */ new Set()).add(t2), void 0 !== this.renderRoot && this.isConnected && t2.hostConnected?.();
}
removeController(t2) {
this._$EO?.delete(t2);
}
_$E_() {
const t2 = /* @__PURE__ */ new Map(), s2 = this.constructor.elementProperties;
for (const i2 of s2.keys()) this.hasOwnProperty(i2) && (t2.set(i2, this[i2]), delete this[i2]);
t2.size > 0 && (this._$Ep = t2);
}
createRenderRoot() {
const t2 = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions);
return S$1(t2, this.constructor.elementStyles), t2;
}
connectedCallback() {
this.renderRoot ??= this.createRenderRoot(), this.enableUpdating(true), this._$EO?.forEach(((t2) => t2.hostConnected?.()));
}
enableUpdating(t2) {
}
disconnectedCallback() {
this._$EO?.forEach(((t2) => t2.hostDisconnected?.()));
}
attributeChangedCallback(t2, s2, i2) {
this._$AK(t2, i2);
}
_$ET(t2, s2) {
const i2 = this.constructor.elementProperties.get(t2), e2 = this.constructor._$Eu(t2, i2);
if (void 0 !== e2 && true === i2.reflect) {
const h2 = (void 0 !== i2.converter?.toAttribute ? i2.converter : u$1).toAttribute(s2, i2.type);
this._$Em = t2, null == h2 ? this.removeAttribute(e2) : this.setAttribute(e2, h2), this._$Em = null;
}
}
_$AK(t2, s2) {
const i2 = this.constructor, e2 = i2._$Eh.get(t2);
if (void 0 !== e2 && this._$Em !== e2) {
const t3 = i2.getPropertyOptions(e2), h2 = "function" == typeof t3.converter ? { fromAttribute: t3.converter } : void 0 !== t3.converter?.fromAttribute ? t3.converter : u$1;
this._$Em = e2;
const r2 = h2.fromAttribute(s2, t3.type);
this[e2] = r2 ?? this._$Ej?.get(e2) ?? r2, this._$Em = null;
}
}
requestUpdate(t2, s2, i2) {
if (void 0 !== t2) {
const e2 = this.constructor, h2 = this[t2];
if (i2 ??= e2.getPropertyOptions(t2), !((i2.hasChanged ?? f$1)(h2, s2) || i2.useDefault && i2.reflect && h2 === this._$Ej?.get(t2) && !this.hasAttribute(e2._$Eu(t2, i2)))) return;
this.C(t2, s2, i2);
}
false === this.isUpdatePending && (this._$ES = this._$EP());
}
C(t2, s2, { useDefault: i2, reflect: e2, wrapped: h2 }, r2) {
i2 && !(this._$Ej ??= /* @__PURE__ */ new Map()).has(t2) && (this._$Ej.set(t2, r2 ?? s2 ?? this[t2]), true !== h2 || void 0 !== r2) || (this._$AL.has(t2) || (this.hasUpdated || i2 || (s2 = void 0), this._$AL.set(t2, s2)), true === e2 && this._$Em !== t2 && (this._$Eq ??= /* @__PURE__ */ new Set()).add(t2));
}
async _$EP() {
this.isUpdatePending = true;
try {
await this._$ES;
} catch (t3) {
Promise.reject(t3);
}
const t2 = this.scheduleUpdate();
return null != t2 && await t2, !this.isUpdatePending;
}
scheduleUpdate() {
return this.performUpdate();
}
performUpdate() {
if (!this.isUpdatePending) return;
if (!this.hasUpdated) {
if (this.renderRoot ??= this.createRenderRoot(), this._$Ep) {
for (const [t4, s3] of this._$Ep) this[t4] = s3;
this._$Ep = void 0;
}
const t3 = this.constructor.elementProperties;
if (t3.size > 0) for (const [s3, i2] of t3) {
const { wrapped: t4 } = i2, e2 = this[s3];
true !== t4 || this._$AL.has(s3) || void 0 === e2 || this.C(s3, void 0, i2, e2);
}
}
let t2 = false;
const s2 = this._$AL;
try {
t2 = this.shouldUpdate(s2), t2 ? (this.willUpdate(s2), this._$EO?.forEach(((t3) => t3.hostUpdate?.())), this.update(s2)) : this._$EM();
} catch (s3) {
throw t2 = false, this._$EM(), s3;
}
t2 && this._$AE(s2);
}
willUpdate(t2) {
}
_$AE(t2) {
this._$EO?.forEach(((t3) => t3.hostUpdated?.())), this.hasUpdated || (this.hasUpdated = true, this.firstUpdated(t2)), this.updated(t2);
}
_$EM() {
this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = false;
}
get updateComplete() {
return this.getUpdateComplete();
}
getUpdateComplete() {
return this._$ES;
}
shouldUpdate(t2) {
return true;
}
update(t2) {
this._$Eq &&= this._$Eq.forEach(((t3) => this._$ET(t3, this[t3]))), this._$EM();
}
updated(t2) {
}
firstUpdated(t2) {
}
};
y$1.elementStyles = [], y$1.shadowRootOptions = { mode: "open" }, y$1[d$1("elementProperties")] = /* @__PURE__ */ new Map(), y$1[d$1("finalized")] = /* @__PURE__ */ new Map(), p$1?.({ ReactiveElement: y$1 }), (a$1.reactiveElementVersions ??= []).push("2.1.1");
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const t = globalThis, i$1 = t.trustedTypes, s$1 = i$1 ? i$1.createPolicy("lit-html", { createHTML: (t2) => t2 }) : void 0, e = "$lit$", h = `lit$${Math.random().toFixed(9).slice(2)}$`, o$1 = "?" + h, n2 = `<${o$1}>`, r = document, l = () => r.createComment(""), c = (t2) => null === t2 || "object" != typeof t2 && "function" != typeof t2, a = Array.isArray, u = (t2) => a(t2) || "function" == typeof t2?.[Symbol.iterator], d = "[ \n\f\r]", f = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g, v = /-->/g, _ = />/g, m = RegExp(`>|${d}(?:([^\\s"'>=/]+)(${d}*=${d}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`, "g"), p = /'/g, g = /"/g, $ = /^(?:script|style|textarea|title)$/i, y2 = (t2) => (i2, ...s2) => ({ _$litType$: t2, strings: i2, values: s2 }), x = y2(1), T = Symbol.for("lit-noChange"), E = Symbol.for("lit-nothing"), A = /* @__PURE__ */ new WeakMap(), C = r.createTreeWalker(r, 129);
function P(t2, i2) {
if (!a(t2) || !t2.hasOwnProperty("raw")) throw Error("invalid template strings array");
return void 0 !== s$1 ? s$1.createHTML(i2) : i2;
}
const V = (t2, i2) => {
const s2 = t2.length - 1, o2 = [];
let r2, l2 = 2 === i2 ? "<svg>" : 3 === i2 ? "<math>" : "", c2 = f;
for (let i3 = 0; i3 < s2; i3++) {
const s3 = t2[i3];
let a2, u2, d2 = -1, y3 = 0;
for (; y3 < s3.length && (c2.lastIndex = y3, u2 = c2.exec(s3), null !== u2); ) y3 = c2.lastIndex, c2 === f ? "!--" === u2[1] ? c2 = v : void 0 !== u2[1] ? c2 = _ : void 0 !== u2[2] ? ($.test(u2[2]) && (r2 = RegExp("</" + u2[2], "g")), c2 = m) : void 0 !== u2[3] && (c2 = m) : c2 === m ? ">" === u2[0] ? (c2 = r2 ?? f, d2 = -1) : void 0 === u2[1] ? d2 = -2 : (d2 = c2.lastIndex - u2[2].length, a2 = u2[1], c2 = void 0 === u2[3] ? m : '"' === u2[3] ? g : p) : c2 === g || c2 === p ? c2 = m : c2 === v || c2 === _ ? c2 = f : (c2 = m, r2 = void 0);
const x2 = c2 === m && t2[i3 + 1].startsWith("/>") ? " " : "";
l2 += c2 === f ? s3 + n2 : d2 >= 0 ? (o2.push(a2), s3.slice(0, d2) + e + s3.slice(d2) + h + x2) : s3 + h + (-2 === d2 ? i3 : x2);
}
return [P(t2, l2 + (t2[s2] || "<?>") + (2 === i2 ? "</svg>" : 3 === i2 ? "</math>" : "")), o2];
};
class N {
constructor({ strings: t2, _$litType$: s2 }, n3) {
let r2;
this.parts = [];
let c2 = 0, a2 = 0;
const u2 = t2.length - 1, d2 = this.parts, [f2, v2] = V(t2, s2);
if (this.el = N.createElement(f2, n3), C.currentNode = this.el.content, 2 === s2 || 3 === s2) {
const t3 = this.el.content.firstChild;
t3.replaceWith(...t3.childNodes);
}
for (; null !== (r2 = C.nextNode()) && d2.length < u2; ) {
if (1 === r2.nodeType) {
if (r2.hasAttributes()) for (const t3 of r2.getAttributeNames()) if (t3.endsWith(e)) {
const i2 = v2[a2++], s3 = r2.getAttribute(t3).split(h), e2 = /([.?@])?(.*)/.exec(i2);
d2.push({ type: 1, index: c2, name: e2[2], strings: s3, ctor: "." === e2[1] ? H : "?" === e2[1] ? I : "@" === e2[1] ? L : k }), r2.removeAttribute(t3);
} else t3.startsWith(h) && (d2.push({ type: 6, index: c2 }), r2.removeAttribute(t3));
if ($.test(r2.tagName)) {
const t3 = r2.textContent.split(h), s3 = t3.length - 1;
if (s3 > 0) {
r2.textContent = i$1 ? i$1.emptyScript : "";
for (let i2 = 0; i2 < s3; i2++) r2.append(t3[i2], l()), C.nextNode(), d2.push({ type: 2, index: ++c2 });
r2.append(t3[s3], l());
}
}
} else if (8 === r2.nodeType) if (r2.data === o$1) d2.push({ type: 2, index: c2 });
else {
let t3 = -1;
for (; -1 !== (t3 = r2.data.indexOf(h, t3 + 1)); ) d2.push({ type: 7, index: c2 }), t3 += h.length - 1;
}
c2++;
}
}
static createElement(t2, i2) {
const s2 = r.createElement("template");
return s2.innerHTML = t2, s2;
}
}
function S(t2, i2, s2 = t2, e2) {
if (i2 === T) return i2;
let h2 = void 0 !== e2 ? s2._$Co?.[e2] : s2._$Cl;
const o2 = c(i2) ? void 0 : i2._$litDirective$;
return h2?.constructor !== o2 && (h2?._$AO?.(false), void 0 === o2 ? h2 = void 0 : (h2 = new o2(t2), h2._$AT(t2, s2, e2)), void 0 !== e2 ? (s2._$Co ??= [])[e2] = h2 : s2._$Cl = h2), void 0 !== h2 && (i2 = S(t2, h2._$AS(t2, i2.values), h2, e2)), i2;
}
class M {
constructor(t2, i2) {
this._$AV = [], this._$AN = void 0, this._$AD = t2, this._$AM = i2;
}
get parentNode() {
return this._$AM.parentNode;
}
get _$AU() {
return this._$AM._$AU;
}
u(t2) {
const { el: { content: i2 }, parts: s2 } = this._$AD, e2 = (t2?.creationScope ?? r).importNode(i2, true);
C.currentNode = e2;
let h2 = C.nextNode(), o2 = 0, n3 = 0, l2 = s2[0];
for (; void 0 !== l2; ) {
if (o2 === l2.index) {
let i3;
2 === l2.type ? i3 = new R(h2, h2.nextSibling, this, t2) : 1 === l2.type ? i3 = new l2.ctor(h2, l2.name, l2.strings, this, t2) : 6 === l2.type && (i3 = new z(h2, this, t2)), this._$AV.push(i3), l2 = s2[++n3];
}
o2 !== l2?.index && (h2 = C.nextNode(), o2++);
}
return C.currentNode = r, e2;
}
p(t2) {
let i2 = 0;
for (const s2 of this._$AV) void 0 !== s2 && (void 0 !== s2.strings ? (s2._$AI(t2, s2, i2), i2 += s2.strings.length - 2) : s2._$AI(t2[i2])), i2++;
}
}
class R {
get _$AU() {
return this._$AM?._$AU ?? this._$Cv;
}
constructor(t2, i2, s2, e2) {
this.type = 2, this._$AH = E, this._$AN = void 0, this._$AA = t2, this._$AB = i2, this._$AM = s2, this.options = e2, this._$Cv = e2?.isConnected ?? true;
}
get parentNode() {
let t2 = this._$AA.parentNode;
const i2 = this._$AM;
return void 0 !== i2 && 11 === t2?.nodeType && (t2 = i2.parentNode), t2;
}
get startNode() {
return this._$AA;
}
get endNode() {
return this._$AB;
}
_$AI(t2, i2 = this) {
t2 = S(this, t2, i2), c(t2) ? t2 === E || null == t2 || "" === t2 ? (this._$AH !== E && this._$AR(), this._$AH = E) : t2 !== this._$AH && t2 !== T && this._(t2) : void 0 !== t2._$litType$ ? this.$(t2) : void 0 !== t2.nodeType ? this.T(t2) : u(t2) ? this.k(t2) : this._(t2);
}
O(t2) {
return this._$AA.parentNode.insertBefore(t2, this._$AB);
}
T(t2) {
this._$AH !== t2 && (this._$AR(), this._$AH = this.O(t2));
}
_(t2) {
this._$AH !== E && c(this._$AH) ? this._$AA.nextSibling.data = t2 : this.T(r.createTextNode(t2)), this._$AH = t2;
}
$(t2) {
const { values: i2, _$litType$: s2 } = t2, e2 = "number" == typeof s2 ? this._$AC(t2) : (void 0 === s2.el && (s2.el = N.createElement(P(s2.h, s2.h[0]), this.options)), s2);
if (this._$AH?._$AD === e2) this._$AH.p(i2);
else {
const t3 = new M(e2, this), s3 = t3.u(this.options);
t3.p(i2), this.T(s3), this._$AH = t3;
}
}
_$AC(t2) {
let i2 = A.get(t2.strings);
return void 0 === i2 && A.set(t2.strings, i2 = new N(t2)), i2;
}
k(t2) {
a(this._$AH) || (this._$AH = [], this._$AR());
const i2 = this._$AH;
let s2, e2 = 0;
for (const h2 of t2) e2 === i2.length ? i2.push(s2 = new R(this.O(l()), this.O(l()), this, this.options)) : s2 = i2[e2], s2._$AI(h2), e2++;
e2 < i2.length && (this._$AR(s2 && s2._$AB.nextSibling, e2), i2.length = e2);
}
_$AR(t2 = this._$AA.nextSibling, i2) {
for (this._$AP?.(false, true, i2); t2 !== this._$AB; ) {
const i3 = t2.nextSibling;
t2.remove(), t2 = i3;
}
}
setConnected(t2) {
void 0 === this._$AM && (this._$Cv = t2, this._$AP?.(t2));
}
}
class k {
get tagName() {
return this.element.tagName;
}
get _$AU() {
return this._$AM._$AU;
}
constructor(t2, i2, s2, e2, h2) {
this.type = 1, this._$AH = E, this._$AN = void 0, this.element = t2, this.name = i2, this._$AM = e2, this.options = h2, s2.length > 2 || "" !== s2[0] || "" !== s2[1] ? (this._$AH = Array(s2.length - 1).fill(new String()), this.strings = s2) : this._$AH = E;
}
_$AI(t2, i2 = this, s2, e2) {
const h2 = this.strings;
let o2 = false;
if (void 0 === h2) t2 = S(this, t2, i2, 0), o2 = !c(t2) || t2 !== this._$AH && t2 !== T, o2 && (this._$AH = t2);
else {
const e3 = t2;
let n3, r2;
for (t2 = h2[0], n3 = 0; n3 < h2.length - 1; n3++) r2 = S(this, e3[s2 + n3], i2, n3), r2 === T && (r2 = this._$AH[n3]), o2 ||= !c(r2) || r2 !== this._$AH[n3], r2 === E ? t2 = E : t2 !== E && (t2 += (r2 ?? "") + h2[n3 + 1]), this._$AH[n3] = r2;
}
o2 && !e2 && this.j(t2);
}
j(t2) {
t2 === E ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t2 ?? "");
}
}
class H extends k {
constructor() {
super(...arguments), this.type = 3;
}
j(t2) {
this.element[this.name] = t2 === E ? void 0 : t2;
}
}
class I extends k {
constructor() {
super(...arguments), this.type = 4;
}
j(t2) {
this.element.toggleAttribute(this.name, !!t2 && t2 !== E);
}
}
class L extends k {
constructor(t2, i2, s2, e2, h2) {
super(t2, i2, s2, e2, h2), this.type = 5;
}
_$AI(t2, i2 = this) {
if ((t2 = S(this, t2, i2, 0) ?? E) === T) return;
const s2 = this._$AH, e2 = t2 === E && s2 !== E || t2.capture !== s2.capture || t2.once !== s2.once || t2.passive !== s2.passive, h2 = t2 !== E && (s2 === E || e2);
e2 && this.element.removeEventListener(this.name, this, s2), h2 && this.element.addEventListener(this.name, this, t2), this._$AH = t2;
}
handleEvent(t2) {
"function" == typeof this._$AH ? this._$AH.call(this.options?.host ?? this.element, t2) : this._$AH.handleEvent(t2);
}
}
class z {
constructor(t2, i2, s2) {
this.element = t2, this.type = 6, this._$AN = void 0, this._$AM = i2, this.options = s2;
}
get _$AU() {
return this._$AM._$AU;
}
_$AI(t2) {
S(this, t2);
}
}
const j = t.litHtmlPolyfillSupport;
j?.(N, R), (t.litHtmlVersions ??= []).push("3.3.1");
const B = (t2, i2, s2) => {
const e2 = s2?.renderBefore ?? i2;
let h2 = e2._$litPart$;
if (void 0 === h2) {
const t3 = s2?.renderBefore ?? null;
e2._$litPart$ = h2 = new R(i2.insertBefore(l(), t3), t3, void 0, s2 ?? {});
}
return h2._$AI(t2), h2;
};
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const s = globalThis;
class i extends y$1 {
constructor() {
super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0;
}
createRenderRoot() {
const t2 = super.createRenderRoot();
return this.renderOptions.renderBefore ??= t2.firstChild, t2;
}
update(t2) {
const r2 = this.render();
this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t2), this._$Do = B(r2, this.renderRoot, this.renderOptions);
}
connectedCallback() {
super.connectedCallback(), this._$Do?.setConnected(true);
}
disconnectedCallback() {
super.disconnectedCallback(), this._$Do?.setConnected(false);
}
render() {
return T;
}
}
i._$litElement$ = true, i["finalized"] = true, s.litElementHydrateSupport?.({ LitElement: i });
const o = s.litElementPolyfillSupport;
o?.({ LitElement: i });
(s.litElementVersions ??= []).push("4.2.1");
export {
E,
f$1 as f,
i,
u$1 as u,
x
};

View File

@@ -1,47 +0,0 @@
import { f, u } from "./lit-DkXrt_Iv.mjs";
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const t = (t2) => (e, o2) => {
void 0 !== o2 ? o2.addInitializer((() => {
customElements.define(t2, e);
})) : customElements.define(t2, e);
};
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const o = { attribute: true, type: String, converter: u, reflect: false, hasChanged: f }, r = (t2 = o, e, r2) => {
const { kind: n2, metadata: i } = r2;
let s = globalThis.litPropertyMetadata.get(i);
if (void 0 === s && globalThis.litPropertyMetadata.set(i, s = /* @__PURE__ */ new Map()), "setter" === n2 && ((t2 = Object.create(t2)).wrapped = true), s.set(r2.name, t2), "accessor" === n2) {
const { name: o2 } = r2;
return { set(r3) {
const n3 = e.get.call(this);
e.set.call(this, r3), this.requestUpdate(o2, n3, t2);
}, init(e2) {
return void 0 !== e2 && this.C(o2, void 0, t2, e2), e2;
} };
}
if ("setter" === n2) {
const { name: o2 } = r2;
return function(r3) {
const n3 = this[o2];
e.call(this, r3), this.requestUpdate(o2, n3, t2);
};
}
throw Error("Unsupported decorator location: " + n2);
};
function n(t2) {
return (e, o2) => "object" == typeof o2 ? r(t2, e, o2) : ((t3, e2, o3) => {
const r2 = e2.hasOwnProperty(o3);
return e2.constructor.createProperty(o3, t3), r2 ? Object.getOwnPropertyDescriptor(e2, o3) : void 0;
})(t2, e, o2);
}
export {
n,
t
};

View File

@@ -1,124 +0,0 @@
import { E } from "./lit-DkXrt_Iv.mjs";
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const f$1 = (o2) => void 0 === o2.strings;
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const t = { CHILD: 2 }, e$1 = (t2) => (...e2) => ({ _$litDirective$: t2, values: e2 });
class i {
constructor(t2) {
}
get _$AU() {
return this._$AM._$AU;
}
_$AT(t2, e2, i2) {
this._$Ct = t2, this._$AM = e2, this._$Ci = i2;
}
_$AS(t2, e2) {
return this.update(t2, e2);
}
update(t2, e2) {
return this.render(...e2);
}
}
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const s = (i2, t2) => {
const e2 = i2._$AN;
if (void 0 === e2) return false;
for (const i3 of e2) i3._$AO?.(t2, false), s(i3, t2);
return true;
}, o$1 = (i2) => {
let t2, e2;
do {
if (void 0 === (t2 = i2._$AM)) break;
e2 = t2._$AN, e2.delete(i2), i2 = t2;
} while (0 === e2?.size);
}, r = (i2) => {
for (let t2; t2 = i2._$AM; i2 = t2) {
let e2 = t2._$AN;
if (void 0 === e2) t2._$AN = e2 = /* @__PURE__ */ new Set();
else if (e2.has(i2)) break;
e2.add(i2), c(t2);
}
};
function h$1(i2) {
void 0 !== this._$AN ? (o$1(this), this._$AM = i2, r(this)) : this._$AM = i2;
}
function n$1(i2, t2 = false, e2 = 0) {
const r2 = this._$AH, h2 = this._$AN;
if (void 0 !== h2 && 0 !== h2.size) if (t2) if (Array.isArray(r2)) for (let i3 = e2; i3 < r2.length; i3++) s(r2[i3], false), o$1(r2[i3]);
else null != r2 && (s(r2, false), o$1(r2));
else s(this, i2);
}
const c = (i2) => {
i2.type == t.CHILD && (i2._$AP ??= n$1, i2._$AQ ??= h$1);
};
class f extends i {
constructor() {
super(...arguments), this._$AN = void 0;
}
_$AT(i2, t2, e2) {
super._$AT(i2, t2, e2), r(this), this.isConnected = i2._$AU;
}
_$AO(i2, t2 = true) {
i2 !== this.isConnected && (this.isConnected = i2, i2 ? this.reconnected?.() : this.disconnected?.()), t2 && (s(this, i2), o$1(this));
}
setValue(t2) {
if (f$1(this._$Ct)) this._$Ct._$AI(t2, this);
else {
const i2 = [...this._$Ct._$AH];
i2[this._$Ci] = t2, this._$Ct._$AI(i2, this, 0);
}
}
disconnected() {
}
reconnected() {
}
}
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const e = () => new h();
class h {
}
const o = /* @__PURE__ */ new WeakMap(), n = e$1(class extends f {
render(i2) {
return E;
}
update(i2, [s2]) {
const e2 = s2 !== this.G;
return e2 && void 0 !== this.G && this.rt(void 0), (e2 || this.lt !== this.ct) && (this.G = s2, this.ht = i2.options?.host, this.rt(this.ct = i2.element)), E;
}
rt(t2) {
if (this.isConnected || (t2 = void 0), "function" == typeof this.G) {
const i2 = this.ht ?? globalThis;
let s2 = o.get(i2);
void 0 === s2 && (s2 = /* @__PURE__ */ new WeakMap(), o.set(i2, s2)), void 0 !== s2.get(this.G) && this.G.call(this.ht, void 0), s2.set(this.G, t2), void 0 !== t2 && this.G.call(this.ht, t2);
} else this.G.value = t2;
}
get lt() {
return "function" == typeof this.G ? o.get(this.ht ?? globalThis)?.get(this.G) : this.G?.value;
}
disconnected() {
this.lt === this.ct && this.rt(void 0);
}
reconnected() {
this.rt(this.ct);
}
});
export {
e,
n
};

File diff suppressed because it is too large Load Diff

View File

@@ -53,6 +53,11 @@ a {
color: var(--text-on-background-color); color: var(--text-on-background-color);
} }
a,
button {
cursor: pointer;
}
header { header {
background: var(--background-darker); background: var(--background-darker);
min-height: 60px; min-height: 60px;
@@ -239,10 +244,8 @@ ul.collection-list {
z-index: 1; z-index: 1;
pointer-events: none; pointer-events: none;
a,
button { button {
pointer-events: all; pointer-events: all;
cursor: pointer;
} }
.title { .title {
@@ -335,8 +338,10 @@ select {
form { form {
input[type="text"], input[type="text"],
input[type="url"],
input[type="password"], input[type="password"],
input[type="color"], input[type="color"],
input[type="file"],
textarea, textarea,
select { select {
width: 100%; width: 100%;
@@ -361,3 +366,57 @@ svg.icon {
border-radius: 12px; border-radius: 12px;
} }
} }
.tab-radio {
display: flex;
display: grid;
grid-auto-flow: column;
grid-auto-columns: 1fr;
background: color-mix(in srgb, var(--background-color), var(--dilute-color) 10%);
border: 2px solid var(--border-color);
border-radius: 8px;
color: var(--text-on-background-color);
margin: 2px;
label {
padding: 10px;
background: color-mix(in srgb, var(--background-color), var(--dilute-color) 10%);
border-radius: 12px;
cursor: pointer;
position: relative;
display: flex;
align-items: center;
svg {
margin-right: 4px;
}
input {
appearance: none;
position: absolute;
width: 100%;
height: 100%;
inset: 0;
pointer-events: none;
}
}
label:hover {
background: color-mix(in srgb, var(--background-color), var(--dilute-color) 15%);
}
label:has(input:focus-visible) {
outline: medium auto currentColor;
outline: medium auto invert;
outline: 5px auto -webkit-focus-ring-color;
input {
outline: none;
}
}
label:has(input:checked) {
background: color-mix(in srgb, var(--background-color), var(--dilute-color) 20%);
}
}

View File

@@ -1,6 +1,6 @@
<h2>{{user.id }}'s Addressbooks</h2> <h2>{{user.id }}'s Addressbooks</h2>
<ul class="collection-list"> <ul class="collection-list">
{% for (meta, addressbook) in addressbooks %} {% for (meta, birthday_cal, addressbook) in addressbooks %}
<li class="collection-list-item"> <li class="collection-list-item">
<a href="/frontend/user/{{ addressbook.principal }}/addressbook/{{ addressbook.id}}"></a> <a href="/frontend/user/{{ addressbook.principal }}/addressbook/{{ addressbook.id}}"></a>
<div class="inner"> <div class="inner">
@@ -24,6 +24,13 @@
></edit-addressbook-form> ></edit-addressbook-form>
<delete-button trash <delete-button trash
href="/carddav/principal/{{ addressbook.principal }}/{{ addressbook.id }}"></delete-button> href="/carddav/principal/{{ addressbook.principal }}/{{ addressbook.id }}"></delete-button>
{% if !birthday_cal.is_some() %}
<create-birthday-calendar-form
principal="{{ addressbook.principal }}"
addr_id="{{ addressbook.id }}"
displayname="{{ addressbook.displayname.as_deref().unwrap_or_default() }} birthdays"
></create-birthday-calendar-form>
{% endif %}
</div> </div>
<div class="metadata"> <div class="metadata">
{{ meta.len }} ({{ meta.size | filesizeformat }}) objects, {{ meta.deleted_len }} ({{ meta.deleted_size | filesizeformat }}) deleted objects {{ meta.len }} ({{ meta.size | filesizeformat }}) objects, {{ meta.deleted_len }} ({{ meta.deleted_size | filesizeformat }}) deleted objects
@@ -37,7 +44,7 @@
{%if !deleted_addressbooks.is_empty() %} {%if !deleted_addressbooks.is_empty() %}
<h3>Deleted Addressbooks</h3> <h3>Deleted Addressbooks</h3>
<ul class="collection-list"> <ul class="collection-list">
{% for (meta, addressbook) in deleted_addressbooks %} {% for (meta, birthday_cal, addressbook) in deleted_addressbooks %}
<li class="collection-list-item"> <li class="collection-list-item">
<a href="/frontend/user/{{ addressbook.principal }}/addressbook/{{ addressbook.id}}"></a> <a href="/frontend/user/{{ addressbook.principal }}/addressbook/{{ addressbook.id}}"></a>
<div class="inner"> <div class="inner">

View File

@@ -0,0 +1,9 @@
<!-- Adapted from https://iconoir.com/ -->
<svg class="icon" width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M13 2.04932C13 2.04932 16 5.99994 16 11.9999" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M11 21.9506C11 21.9506 8 17.9999 8 11.9999C8 5.99994 11 2.04932 11 2.04932" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M2.62964 15.5H12" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M2.62964 8.5H21.3704" stroke-linecap="round" stroke-linejoin="round"></path>
<path fill-rule="evenodd" clip-rule="evenodd" d="M21.8789 17.9174C22.3727 18.2211 22.3423 18.9604 21.8337 19.0181L19.2671 19.309L18.1159 21.6213C17.8878 22.0795 17.1827 21.8552 17.0661 21.2873L15.8108 15.1713C15.7123 14.6913 16.1437 14.3892 16.561 14.646L21.8789 17.9174Z"></path>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -5,13 +5,7 @@
<script> <script>
window.rusticalUser = JSON.parse(document.querySelector('#data-rustical-user').innerHTML) window.rusticalUser = JSON.parse(document.querySelector('#data-rustical-user').innerHTML)
</script> </script>
<script type="module" src="/frontend/assets/js/create-calendar-form.mjs" async></script> <script type="module" src="/frontend/assets/js/bundle.mjs" async></script>
<script type="module" src="/frontend/assets/js/edit-calendar-form.mjs" async></script>
<script type="module" src="/frontend/assets/js/import-calendar-form.mjs" async></script>
<script type="module" src="/frontend/assets/js/create-addressbook-form.mjs" async></script>
<script type="module" src="/frontend/assets/js/edit-addressbook-form.mjs" async></script>
<script type="module" src="/frontend/assets/js/import-addressbook-form.mjs" async></script>
<script type="module" src="/frontend/assets/js/delete-button.mjs" async></script>
{% endblock %} {% endblock %}
{% block header_center %} {% block header_center %}
<nav class="header-center"> <nav class="header-center">

View File

@@ -12,7 +12,7 @@ use http::{Method, StatusCode};
use routes::{addressbooks::route_addressbooks, calendars::route_calendars}; use routes::{addressbooks::route_addressbooks, calendars::route_calendars};
use rustical_oidc::{OidcConfig, OidcServiceConfig, route_get_oidc_callback, route_post_oidc}; use rustical_oidc::{OidcConfig, OidcServiceConfig, route_get_oidc_callback, route_post_oidc};
use rustical_store::{ use rustical_store::{
AddressbookStore, CalendarStore, AddressbookStore, CalendarStore, PrefixedCalendarStore,
auth::{AuthenticationProvider, middleware::AuthenticationLayer}, auth::{AuthenticationProvider, middleware::AuthenticationLayer},
}; };
use std::sync::Arc; use std::sync::Arc;
@@ -39,7 +39,11 @@ use crate::routes::{
#[cfg(not(feature = "dev"))] #[cfg(not(feature = "dev"))]
use assets::{Assets, EmbedService}; use assets::{Assets, EmbedService};
pub fn frontend_router<AP: AuthenticationProvider, CS: CalendarStore, AS: AddressbookStore>( pub fn frontend_router<
AP: AuthenticationProvider,
CS: CalendarStore,
AS: AddressbookStore + PrefixedCalendarStore,
>(
prefix: &'static str, prefix: &'static str,
auth_provider: Arc<AP>, auth_provider: Arc<AP>,
cal_store: Arc<CS>, cal_store: Arc<CS>,

View File

@@ -1,10 +1,12 @@
use std::sync::Arc;
use askama::Template; use askama::Template;
use askama_web::WebTemplate; use askama_web::WebTemplate;
use axum::{Extension, extract::Path, response::IntoResponse}; use axum::{Extension, extract::Path, response::IntoResponse};
use http::StatusCode; use http::StatusCode;
use rustical_store::{Addressbook, AddressbookStore, CollectionMetadata, auth::Principal}; use rustical_store::{
Addressbook, AddressbookStore, Calendar, CollectionMetadata, PrefixedCalendarStore,
auth::Principal,
};
use std::sync::Arc;
use crate::pages::user::{Section, UserPage}; use crate::pages::user::{Section, UserPage};
@@ -18,11 +20,11 @@ impl Section for AddressbooksSection {
#[template(path = "components/sections/addressbooks_section.html")] #[template(path = "components/sections/addressbooks_section.html")]
pub struct AddressbooksSection { pub struct AddressbooksSection {
pub user: Principal, pub user: Principal,
pub addressbooks: Vec<(CollectionMetadata, Addressbook)>, pub addressbooks: Vec<(CollectionMetadata, Option<Calendar>, Addressbook)>,
pub deleted_addressbooks: Vec<(CollectionMetadata, Addressbook)>, pub deleted_addressbooks: Vec<(CollectionMetadata, Option<Calendar>, Addressbook)>,
} }
pub async fn route_addressbooks<AS: AddressbookStore>( pub async fn route_addressbooks<AS: AddressbookStore + PrefixedCalendarStore>(
Path(user_id): Path<String>, Path(user_id): Path<String>,
Extension(addr_store): Extension<Arc<AS>>, Extension(addr_store): Extension<Arc<AS>>,
user: Principal, user: Principal,
@@ -43,22 +45,42 @@ pub async fn route_addressbooks<AS: AddressbookStore>(
let mut addressbook_infos = vec![]; let mut addressbook_infos = vec![];
for addressbook in addressbooks { for addressbook in addressbooks {
let birthday_id = format!("{}{}", AS::PREFIX, &addressbook.id);
let birthday_cal = match addr_store
.get_calendar(&addressbook.principal, &birthday_id, true)
.await
{
Ok(cal) => Some(cal),
Err(rustical_store::Error::NotFound) => None,
err => Some(err.unwrap()),
};
addressbook_infos.push(( addressbook_infos.push((
addr_store addr_store
.addressbook_metadata(&addressbook.principal, &addressbook.id) .addressbook_metadata(&addressbook.principal, &addressbook.id)
.await .await
.unwrap(), .unwrap(),
birthday_cal,
addressbook, addressbook,
)); ));
} }
let mut deleted_addressbook_infos = vec![]; let mut deleted_addressbook_infos = vec![];
for addressbook in deleted_addressbooks { for addressbook in deleted_addressbooks {
let birthday_id = format!("{}{}", AS::PREFIX, &addressbook.id);
let birthday_cal = match addr_store
.get_calendar(&addressbook.principal, &birthday_id, true)
.await
{
Ok(cal) => Some(cal),
Err(rustical_store::Error::NotFound) => None,
err => Some(err.unwrap()),
};
deleted_addressbook_infos.push(( deleted_addressbook_infos.push((
addr_store addr_store
.addressbook_metadata(&addressbook.principal, &addressbook.id) .addressbook_metadata(&addressbook.principal, &addressbook.id)
.await .await
.unwrap(), .unwrap(),
birthday_cal,
addressbook, addressbook,
)); ));
} }

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_ical" name = "rustical_ical"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true

View File

@@ -2,7 +2,7 @@ use axum::{http::StatusCode, response::IntoResponse};
use crate::CalDateTimeError; use crate::CalDateTimeError;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum Error { pub enum Error {
#[error("Invalid ics/vcf input: {0}")] #[error("Invalid ics/vcf input: {0}")]
InvalidData(String), InvalidData(String),

View File

@@ -13,7 +13,7 @@ const LOCAL_DATE_TIME: &str = "%Y%m%dT%H%M%S";
const UTC_DATE_TIME: &str = "%Y%m%dT%H%M%SZ"; const UTC_DATE_TIME: &str = "%Y%m%dT%H%M%SZ";
pub const LOCAL_DATE: &str = "%Y%m%d"; pub const LOCAL_DATE: &str = "%Y%m%d";
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum CalDateTimeError { pub enum CalDateTimeError {
#[error( #[error(
"Timezone has X-LIC-LOCATION property to specify a timezone from the Olson database, however its value {0} is invalid" "Timezone has X-LIC-LOCATION property to specify a timezone from the Olson database, however its value {0} is invalid"

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_oidc" name = "rustical_oidc"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_store" name = "rustical_store"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true
@@ -8,15 +9,16 @@ license.workspace = true
publish = false publish = false
[dependencies] [dependencies]
anyhow = { workspace = true } anyhow.workspace = true
async-trait = { workspace = true } async-trait.workspace = true
serde = { workspace = true } serde.workspace = true
ical = { workspace = true } sha2.workspace = true
chrono = { workspace = true } ical.workspace = true
regex = { workspace = true } chrono.workspace = true
thiserror = { workspace = true } regex.workspace = true
tracing = { workspace = true } thiserror.workspace = true
chrono-tz = { workspace = true } tracing.workspace = true
chrono-tz.workspace = true
derive_more = { workspace = true, features = ["as_ref"] } derive_more = { workspace = true, features = ["as_ref"] }
rustical_xml.workspace = true rustical_xml.workspace = true
tokio.workspace = true tokio.workspace = true
@@ -33,7 +35,7 @@ tower-sessions.workspace = true
vtimezones-rs.workspace = true vtimezones-rs.workspace = true
[dev-dependencies] [dev-dependencies]
rstest = { workspace = true } rstest.workspace = true
rstest_reuse = { workspace = true } rstest_reuse.workspace = true
rustical_store_sqlite.workspace = true rustical_store_sqlite.workspace = true
tokio.workspace = true tokio.workspace = true

View File

@@ -2,7 +2,7 @@ use crate::synctoken::format_synctoken;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use serde::Serialize; use serde::Serialize;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct Addressbook { pub struct Addressbook {
pub id: String, pub id: String,
pub principal: String, pub principal: String,

View File

@@ -4,7 +4,7 @@ use rustical_ical::CalendarObjectType;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
#[derive(Debug, Default, Clone, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CalendarMetadata { pub struct CalendarMetadata {
// Attributes that may be outsourced // Attributes that may be outsourced
pub displayname: Option<String>, pub displayname: Option<String>,
@@ -13,7 +13,7 @@ pub struct CalendarMetadata {
pub color: Option<String>, pub color: Option<String>,
} }
#[derive(Debug, Default, Clone, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Calendar { pub struct Calendar {
// Attributes that may be outsourced // Attributes that may be outsourced
#[serde(flatten)] #[serde(flatten)]

View File

@@ -41,6 +41,11 @@ impl Error {
_ => StatusCode::INTERNAL_SERVER_ERROR, _ => StatusCode::INTERNAL_SERVER_ERROR,
} }
} }
#[must_use]
pub const fn is_not_found(&self) -> bool {
matches!(self, Self::NotFound)
}
} }
impl IntoResponse for Error { impl IntoResponse for Error {

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_store_sqlite" name = "rustical_store_sqlite"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true
@@ -15,12 +16,12 @@ rstest.workspace = true
[dependencies] [dependencies]
tokio.workspace = true tokio.workspace = true
rustical_store = { workspace = true } rustical_store.workspace = true
async-trait = { workspace = true } async-trait.workspace = true
serde = { workspace = true } serde.workspace = true
sqlx = { workspace = true } sqlx.workspace = true
thiserror = { workspace = true } thiserror.workspace = true
tracing = { workspace = true } tracing.workspace = true
derive_more.workspace = true derive_more.workspace = true
chrono.workspace = true chrono.workspace = true
password-auth.workspace = true password-auth.workspace = true

View File

@@ -115,28 +115,56 @@ impl SqliteAddressbookStore {
.map_err(crate::Error::from).map(|cals| cals.into_iter().map(BirthdayCalendarJoinRow::into).collect())?) .map_err(crate::Error::from).map(|cals| cals.into_iter().map(BirthdayCalendarJoinRow::into).collect())?)
} }
#[instrument] #[must_use]
pub async fn _insert_birthday_calendar<'e, E: Executor<'e, Database = Sqlite>>( pub fn default_birthday_calendar(addressbook: Addressbook) -> Calendar {
executor: E,
addressbook: Addressbook,
) -> Result<(), rustical_store::Error> {
let birthday_name = addressbook let birthday_name = addressbook
.displayname .displayname
.as_ref()
.map(|name| format!("{name} birthdays")); .map(|name| format!("{name} birthdays"));
let birthday_push_topic = { let birthday_push_topic = {
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
hasher.update("birthdays"); hasher.update("birthdays");
hasher.update(addressbook.push_topic); hasher.update(&addressbook.push_topic);
format!("{:x}", hasher.finalize()) format!("{:x}", hasher.finalize())
}; };
Calendar {
principal: addressbook.principal,
meta: CalendarMetadata {
displayname: birthday_name,
order: 0,
description: None,
color: None,
},
id: format!("{}{}", Self::PREFIX, addressbook.id),
components: vec![CalendarObjectType::Event],
timezone_id: None,
deleted_at: None,
synctoken: Default::default(),
subscription_url: None,
push_topic: birthday_push_topic,
}
}
#[instrument]
pub async fn _insert_birthday_calendar<'e, E: Executor<'e, Database = Sqlite>>(
executor: E,
calendar: &Calendar,
) -> Result<(), rustical_store::Error> {
let id = calendar
.id
.strip_prefix(BIRTHDAYS_PREFIX)
.ok_or(Error::NotFound)?;
sqlx::query!( sqlx::query!(
r#"INSERT INTO birthday_calendars (principal, id, displayname, push_topic) r#"INSERT INTO birthday_calendars (principal, id, displayname, description, "order", color, push_topic)
VALUES (?, ?, ?, ?)"#, VALUES (?, ?, ?, ?, ?, ?, ?)"#,
addressbook.principal, calendar.principal,
addressbook.id, id,
birthday_name, calendar.meta.displayname,
birthday_push_topic, calendar.meta.description,
calendar.meta.order,
calendar.meta.color,
calendar.push_topic,
) )
.execute(executor) .execute(executor)
.await .await
@@ -255,8 +283,8 @@ impl CalendarStore for SqliteAddressbookStore {
} }
#[instrument] #[instrument]
async fn insert_calendar(&self, _calendar: Calendar) -> Result<(), Error> { async fn insert_calendar(&self, calendar: Calendar) -> Result<(), Error> {
Err(Error::ReadOnly) Self::_insert_birthday_calendar(&self.db, &calendar).await
} }
#[instrument] #[instrument]

View File

@@ -9,7 +9,7 @@ use rustical_store::{
}; };
use sqlx::{Acquire, Executor, Sqlite, SqlitePool, Transaction}; use sqlx::{Acquire, Executor, Sqlite, SqlitePool, Transaction};
use tokio::sync::mpsc::Sender; use tokio::sync::mpsc::Sender;
use tracing::{error, instrument}; use tracing::{error_span, instrument, warn};
pub mod birthday_calendar; pub mod birthday_calendar;
@@ -34,6 +34,111 @@ pub struct SqliteAddressbookStore {
} }
impl SqliteAddressbookStore { impl SqliteAddressbookStore {
// Commit "orphaned" objects to the changelog table
pub async fn repair_orphans(&self) -> Result<(), Error> {
struct Row {
principal: String,
addressbook_id: String,
id: String,
deleted: bool,
}
let mut tx = self
.db
.begin_with(BEGIN_IMMEDIATE)
.await
.map_err(crate::Error::from)?;
let rows = sqlx::query_as!(
Row,
r#"
SELECT principal, addressbook_id, id, (deleted_at IS NOT NULL) AS "deleted: bool"
FROM addressobjects
WHERE (principal, addressbook_id, id) NOT IN (
SELECT DISTINCT principal, addressbook_id, object_id FROM addressobjectchangelog
)
;
"#,
)
.fetch_all(&mut *tx)
.await
.map_err(crate::Error::from)?;
for row in rows {
let operation = if row.deleted {
ChangeOperation::Delete
} else {
ChangeOperation::Add
};
warn!(
"Commiting orphaned addressbook object ({},{},{}), deleted={}",
&row.principal, &row.addressbook_id, &row.id, &row.deleted
);
Self::log_object_operation(
&mut tx,
&row.principal,
&row.addressbook_id,
&row.id,
operation,
)
.await?;
}
tx.commit().await.map_err(crate::Error::from)?;
Ok(())
}
// Logs an operation to an address object
async fn log_object_operation(
tx: &mut Transaction<'_, Sqlite>,
principal: &str,
addressbook_id: &str,
object_id: &str,
operation: ChangeOperation,
) -> Result<String, Error> {
struct Synctoken {
synctoken: i64,
}
let Synctoken { synctoken } = sqlx::query_as!(
Synctoken,
r#"
UPDATE addressbooks
SET synctoken = synctoken + 1
WHERE (principal, id) = (?1, ?2)
RETURNING synctoken"#,
principal,
addressbook_id
)
.fetch_one(&mut **tx)
.await
.map_err(crate::Error::from)?;
sqlx::query!(
r#"
INSERT INTO addressobjectchangelog (principal, addressbook_id, object_id, "operation", synctoken)
VALUES (?1, ?2, ?3, ?4, (
SELECT synctoken FROM addressbooks WHERE (principal, id) = (?1, ?2)
))"#,
principal,
addressbook_id,
object_id,
operation
)
.execute(&mut **tx)
.await
.map_err(crate::Error::from)?;
Ok(format_synctoken(synctoken))
}
fn send_push_notification(&self, data: CollectionOperationInfo, topic: String) {
if let Err(err) = self.sender.try_send(CollectionOperation { topic, data }) {
error_span!(
"Error trying to send addressbook update notification:",
err = format!("{err:?}"),
);
}
}
async fn _get_addressbook<'e, E: Executor<'e, Database = Sqlite>>( async fn _get_addressbook<'e, E: Executor<'e, Database = Sqlite>>(
executor: E, executor: E,
principal: &str, principal: &str,
@@ -92,9 +197,9 @@ impl SqliteAddressbookStore {
async fn _update_addressbook<'e, E: Executor<'e, Database = Sqlite>>( async fn _update_addressbook<'e, E: Executor<'e, Database = Sqlite>>(
executor: E, executor: E,
principal: String, principal: &str,
id: String, id: &str,
addressbook: Addressbook, addressbook: &Addressbook,
) -> Result<(), rustical_store::Error> { ) -> Result<(), rustical_store::Error> {
let result = sqlx::query!( let result = sqlx::query!(
r#"UPDATE addressbooks SET principal = ?, id = ?, displayname = ?, description = ?, push_topic = ? r#"UPDATE addressbooks SET principal = ?, id = ?, displayname = ?, description = ?, push_topic = ?
@@ -399,7 +504,7 @@ impl AddressbookStore for SqliteAddressbookStore {
id: String, id: String,
addressbook: Addressbook, addressbook: Addressbook,
) -> Result<(), rustical_store::Error> { ) -> Result<(), rustical_store::Error> {
Self::_update_addressbook(&self.db, principal, id, addressbook).await Self::_update_addressbook(&self.db, &principal, &id, &addressbook).await
} }
#[instrument] #[instrument]
@@ -413,7 +518,8 @@ impl AddressbookStore for SqliteAddressbookStore {
.await .await
.map_err(crate::Error::from)?; .map_err(crate::Error::from)?;
Self::_insert_addressbook(&mut *tx, &addressbook).await?; Self::_insert_addressbook(&mut *tx, &addressbook).await?;
Self::_insert_birthday_calendar(&mut *tx, addressbook).await?; let birthday_cal = Self::default_birthday_calendar(addressbook);
Self::_insert_birthday_calendar(&mut *tx, &birthday_cal).await?;
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
Ok(()) Ok(())
} }
@@ -441,13 +547,8 @@ impl AddressbookStore for SqliteAddressbookStore {
Self::_delete_addressbook(&mut *tx, principal, addressbook_id, use_trashbin).await?; Self::_delete_addressbook(&mut *tx, principal, addressbook_id, use_trashbin).await?;
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Some(addressbook) = addressbook if let Some(addressbook) = addressbook {
&& let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(CollectionOperationInfo::Delete, addressbook.push_topic);
data: CollectionOperationInfo::Delete,
topic: addressbook.push_topic,
})
{
error!("Push notification about deleted addressbook failed: {err}");
} }
Ok(()) Ok(())
@@ -533,7 +634,7 @@ impl AddressbookStore for SqliteAddressbookStore {
Self::_put_object(&mut *tx, &principal, &addressbook_id, &object, overwrite).await?; Self::_put_object(&mut *tx, &principal, &addressbook_id, &object, overwrite).await?;
let sync_token = log_object_operation( let sync_token = Self::log_object_operation(
&mut tx, &mut tx,
&principal, &principal,
&addressbook_id, &addressbook_id,
@@ -545,15 +646,12 @@ impl AddressbookStore for SqliteAddressbookStore {
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(
data: CollectionOperationInfo::Content { sync_token }, CollectionOperationInfo::Content { sync_token },
topic: self self.get_addressbook(&principal, &addressbook_id, false)
.get_addressbook(&principal, &addressbook_id, false)
.await? .await?
.push_topic, .push_topic,
}) { );
error!("Push notification about deleted addressbook failed: {err}");
}
Ok(()) Ok(())
} }
@@ -574,7 +672,7 @@ impl AddressbookStore for SqliteAddressbookStore {
Self::_delete_object(&mut *tx, principal, addressbook_id, object_id, use_trashbin).await?; Self::_delete_object(&mut *tx, principal, addressbook_id, object_id, use_trashbin).await?;
let sync_token = log_object_operation( let sync_token = Self::log_object_operation(
&mut tx, &mut tx,
principal, principal,
addressbook_id, addressbook_id,
@@ -586,15 +684,12 @@ impl AddressbookStore for SqliteAddressbookStore {
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(
data: CollectionOperationInfo::Content { sync_token }, CollectionOperationInfo::Content { sync_token },
topic: self self.get_addressbook(principal, addressbook_id, false)
.get_addressbook(principal, addressbook_id, false)
.await? .await?
.push_topic, .push_topic,
}) { );
error!("Push notification about deleted addressbook failed: {err}");
}
Ok(()) Ok(())
} }
@@ -613,7 +708,7 @@ impl AddressbookStore for SqliteAddressbookStore {
Self::_restore_object(&mut *tx, principal, addressbook_id, object_id).await?; Self::_restore_object(&mut *tx, principal, addressbook_id, object_id).await?;
let sync_token = log_object_operation( let sync_token = Self::log_object_operation(
&mut tx, &mut tx,
principal, principal,
addressbook_id, addressbook_id,
@@ -624,15 +719,12 @@ impl AddressbookStore for SqliteAddressbookStore {
.map_err(crate::Error::from)?; .map_err(crate::Error::from)?;
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(
data: CollectionOperationInfo::Content { sync_token }, CollectionOperationInfo::Content { sync_token },
topic: self self.get_addressbook(principal, addressbook_id, false)
.get_addressbook(principal, addressbook_id, false)
.await? .await?
.push_topic, .push_topic,
}) { );
error!("Push notification about deleted addressbook failed: {err}");
}
Ok(()) Ok(())
} }
@@ -665,6 +757,7 @@ impl AddressbookStore for SqliteAddressbookStore {
Self::_insert_addressbook(&mut *tx, &addressbook).await?; Self::_insert_addressbook(&mut *tx, &addressbook).await?;
} }
let mut sync_token = None;
for object in objects { for object in objects {
Self::_put_object( Self::_put_object(
&mut *tx, &mut *tx,
@@ -674,49 +767,28 @@ impl AddressbookStore for SqliteAddressbookStore {
false, false,
) )
.await?; .await?;
sync_token = Some(
Self::log_object_operation(
&mut tx,
&addressbook.principal,
&addressbook.id,
object.get_id(),
ChangeOperation::Add,
)
.await?,
);
} }
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Some(sync_token) = sync_token {
self.send_push_notification(
CollectionOperationInfo::Content { sync_token },
self.get_addressbook(&addressbook.principal, &addressbook.id, true)
.await?
.push_topic,
);
}
Ok(()) Ok(())
} }
} }
// Logs an operation to an address object
async fn log_object_operation(
tx: &mut Transaction<'_, Sqlite>,
principal: &str,
addressbook_id: &str,
object_id: &str,
operation: ChangeOperation,
) -> Result<String, sqlx::Error> {
struct Synctoken {
synctoken: i64,
}
let Synctoken { synctoken } = sqlx::query_as!(
Synctoken,
r#"
UPDATE addressbooks
SET synctoken = synctoken + 1
WHERE (principal, id) = (?1, ?2)
RETURNING synctoken"#,
principal,
addressbook_id
)
.fetch_one(&mut **tx)
.await?;
sqlx::query!(
r#"
INSERT INTO addressobjectchangelog (principal, addressbook_id, object_id, "operation", synctoken)
VALUES (?1, ?2, ?3, ?4, (
SELECT synctoken FROM addressbooks WHERE (principal, id) = (?1, ?2)
))"#,
principal,
addressbook_id,
object_id,
operation
)
.execute(&mut **tx)
.await?;
Ok(format_synctoken(synctoken))
}

View File

@@ -11,7 +11,7 @@ use rustical_store::{CollectionOperation, CollectionOperationInfo};
use sqlx::types::chrono::NaiveDateTime; use sqlx::types::chrono::NaiveDateTime;
use sqlx::{Acquire, Executor, Sqlite, SqlitePool, Transaction}; use sqlx::{Acquire, Executor, Sqlite, SqlitePool, Transaction};
use tokio::sync::mpsc::Sender; use tokio::sync::mpsc::Sender;
use tracing::{error, instrument}; use tracing::{error_span, instrument, warn};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct CalendarObjectRow { struct CalendarObjectRow {
@@ -94,6 +94,105 @@ pub struct SqliteCalendarStore {
} }
impl SqliteCalendarStore { impl SqliteCalendarStore {
// Logs an operation to the events
async fn log_object_operation(
tx: &mut Transaction<'_, Sqlite>,
principal: &str,
cal_id: &str,
object_id: &str,
operation: ChangeOperation,
) -> Result<String, Error> {
struct Synctoken {
synctoken: i64,
}
let Synctoken { synctoken } = sqlx::query_as!(
Synctoken,
r#"
UPDATE calendars
SET synctoken = synctoken + 1
WHERE (principal, id) = (?1, ?2)
RETURNING synctoken"#,
principal,
cal_id
)
.fetch_one(&mut **tx)
.await
.map_err(crate::Error::from)?;
sqlx::query!(
r#"
INSERT INTO calendarobjectchangelog (principal, cal_id, object_id, "operation", synctoken)
VALUES (?1, ?2, ?3, ?4, (
SELECT synctoken FROM calendars WHERE (principal, id) = (?1, ?2)
))"#,
principal,
cal_id,
object_id,
operation
)
.execute(&mut **tx)
.await
.map_err(crate::Error::from)?;
Ok(format_synctoken(synctoken))
}
fn send_push_notification(&self, data: CollectionOperationInfo, topic: String) {
if let Err(err) = self.sender.try_send(CollectionOperation { topic, data }) {
error_span!(
"Error trying to send calendar update notification:",
err = format!("{err:?}"),
);
}
}
// Commit "orphaned" objects to the changelog table
pub async fn repair_orphans(&self) -> Result<(), Error> {
struct Row {
principal: String,
cal_id: String,
id: String,
deleted: bool,
}
let mut tx = self
.db
.begin_with(BEGIN_IMMEDIATE)
.await
.map_err(crate::Error::from)?;
let rows = sqlx::query_as!(
Row,
r#"
SELECT principal, cal_id, id, (deleted_at IS NOT NULL) AS "deleted: bool"
FROM calendarobjects
WHERE (principal, cal_id, id) NOT IN (
SELECT DISTINCT principal, cal_id, object_id FROM calendarobjectchangelog
)
;
"#,
)
.fetch_all(&mut *tx)
.await
.map_err(crate::Error::from)?;
for row in rows {
let operation = if row.deleted {
ChangeOperation::Delete
} else {
ChangeOperation::Add
};
warn!(
"Commiting orphaned calendar object ({},{},{}), deleted={}",
&row.principal, &row.cal_id, &row.id, &row.deleted
);
Self::log_object_operation(&mut tx, &row.principal, &row.cal_id, &row.id, operation)
.await?;
}
tx.commit().await.map_err(crate::Error::from)?;
Ok(())
}
async fn _get_calendar<'e, E: Executor<'e, Database = Sqlite>>( async fn _get_calendar<'e, E: Executor<'e, Database = Sqlite>>(
executor: E, executor: E,
principal: &str, principal: &str,
@@ -351,9 +450,9 @@ impl SqliteCalendarStore {
#[instrument] #[instrument]
async fn _put_object<'e, E: Executor<'e, Database = Sqlite>>( async fn _put_object<'e, E: Executor<'e, Database = Sqlite>>(
executor: E, executor: E,
principal: String, principal: &str,
cal_id: String, cal_id: &str,
object: CalendarObject, object: &CalendarObject,
overwrite: bool, overwrite: bool,
) -> Result<(), Error> { ) -> Result<(), Error> {
let (object_id, uid, ics) = (object.get_id(), object.get_uid(), object.get_ics()); let (object_id, uid, ics) = (object.get_id(), object.get_uid(), object.get_ics());
@@ -558,13 +657,8 @@ impl CalendarStore for SqliteCalendarStore {
Self::_delete_calendar(&mut *tx, principal, id, use_trashbin).await?; Self::_delete_calendar(&mut *tx, principal, id, use_trashbin).await?;
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Some(cal) = cal if let Some(cal) = cal {
&& let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(CollectionOperationInfo::Delete, cal.push_topic);
data: CollectionOperationInfo::Delete,
topic: cal.push_topic,
})
{
error!("Push notification about deleted calendar failed: {err}");
} }
Ok(()) Ok(())
} }
@@ -600,18 +694,32 @@ impl CalendarStore for SqliteCalendarStore {
Self::_insert_calendar(&mut *tx, calendar.clone()).await?; Self::_insert_calendar(&mut *tx, calendar.clone()).await?;
} }
let mut sync_token = None;
for object in objects { for object in objects {
Self::_put_object( Self::_put_object(&mut *tx, &calendar.principal, &calendar.id, &object, false).await?;
&mut *tx,
calendar.principal.clone(), sync_token = Some(
calendar.id.clone(), Self::log_object_operation(
object, &mut tx,
false, &calendar.principal,
) &calendar.id,
.await?; object.get_id(),
ChangeOperation::Add,
)
.await?,
);
} }
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Some(sync_token) = sync_token {
self.send_push_notification(
CollectionOperationInfo::Content { sync_token },
self.get_calendar(&calendar.principal, &calendar.id, true)
.await?
.push_topic,
);
}
Ok(()) Ok(())
} }
@@ -689,16 +797,9 @@ impl CalendarStore for SqliteCalendarStore {
return Err(Error::ReadOnly); return Err(Error::ReadOnly);
} }
Self::_put_object( Self::_put_object(&mut *tx, &principal, &cal_id, &object, overwrite).await?;
&mut *tx,
principal.clone(),
cal_id.clone(),
object,
overwrite,
)
.await?;
let sync_token = log_object_operation( let sync_token = Self::log_object_operation(
&mut tx, &mut tx,
&principal, &principal,
&cal_id, &cal_id,
@@ -709,15 +810,12 @@ impl CalendarStore for SqliteCalendarStore {
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(
data: CollectionOperationInfo::Content { sync_token }, CollectionOperationInfo::Content { sync_token },
topic: self self.get_calendar(&principal, &cal_id, true)
.get_calendar(&principal, &cal_id, true)
.await? .await?
.push_topic, .push_topic,
}) { );
error!("Push notification about deleted calendar failed: {err}");
}
Ok(()) Ok(())
} }
@@ -738,15 +836,15 @@ impl CalendarStore for SqliteCalendarStore {
Self::_delete_object(&mut *tx, principal, cal_id, id, use_trashbin).await?; Self::_delete_object(&mut *tx, principal, cal_id, id, use_trashbin).await?;
let sync_token = let sync_token =
log_object_operation(&mut tx, principal, cal_id, id, ChangeOperation::Delete).await?; Self::log_object_operation(&mut tx, principal, cal_id, id, ChangeOperation::Delete)
.await?;
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(
data: CollectionOperationInfo::Content { sync_token }, CollectionOperationInfo::Content { sync_token },
topic: self.get_calendar(principal, cal_id, true).await?.push_topic, self.get_calendar(principal, cal_id, true).await?.push_topic,
}) { );
error!("Push notification about deleted calendar failed: {err}");
}
Ok(()) Ok(())
} }
@@ -766,16 +864,14 @@ impl CalendarStore for SqliteCalendarStore {
Self::_restore_object(&mut *tx, principal, cal_id, object_id).await?; Self::_restore_object(&mut *tx, principal, cal_id, object_id).await?;
let sync_token = let sync_token =
log_object_operation(&mut tx, principal, cal_id, object_id, ChangeOperation::Add) Self::log_object_operation(&mut tx, principal, cal_id, object_id, ChangeOperation::Add)
.await?; .await?;
tx.commit().await.map_err(crate::Error::from)?; tx.commit().await.map_err(crate::Error::from)?;
if let Err(err) = self.sender.try_send(CollectionOperation { self.send_push_notification(
data: CollectionOperationInfo::Content { sync_token }, CollectionOperationInfo::Content { sync_token },
topic: self.get_calendar(principal, cal_id, true).await?.push_topic, self.get_calendar(principal, cal_id, true).await?.push_topic,
}) { );
error!("Push notification about deleted calendar failed: {err}");
}
Ok(()) Ok(())
} }
@@ -793,45 +889,3 @@ impl CalendarStore for SqliteCalendarStore {
false false
} }
} }
// Logs an operation to the events
async fn log_object_operation(
tx: &mut Transaction<'_, Sqlite>,
principal: &str,
cal_id: &str,
object_id: &str,
operation: ChangeOperation,
) -> Result<String, Error> {
struct Synctoken {
synctoken: i64,
}
let Synctoken { synctoken } = sqlx::query_as!(
Synctoken,
r#"
UPDATE calendars
SET synctoken = synctoken + 1
WHERE (principal, id) = (?1, ?2)
RETURNING synctoken"#,
principal,
cal_id
)
.fetch_one(&mut **tx)
.await
.map_err(crate::Error::from)?;
sqlx::query!(
r#"
INSERT INTO calendarobjectchangelog (principal, cal_id, object_id, "operation", synctoken)
VALUES (?1, ?2, ?3, ?4, (
SELECT synctoken FROM calendars WHERE (principal, id) = (?1, ?2)
))"#,
principal,
cal_id,
object_id,
operation
)
.execute(&mut **tx)
.await
.map_err(crate::Error::from)?;
Ok(format_synctoken(synctoken))
}

View File

@@ -37,7 +37,7 @@ impl SubscriptionStore for SqliteStore {
Err(err) => return Err(err), Err(err) => return Err(err),
}; };
sqlx::query!( sqlx::query!(
r#"INSERT OR REPLACE INTO davpush_subscriptions (id, topic, expiration, push_resource, public_key, public_key_type, auth_secret) VALUES (?, ?, ?, ?, ?, ?, ?)"#, r#"REPLACE INTO davpush_subscriptions (id, topic, expiration, push_resource, public_key, public_key_type, auth_secret) VALUES (?, ?, ?, ?, ?, ?, ?)"#,
sub.id, sub.id,
sub.topic, sub.topic,
sub.expiration, sub.expiration,

View File

@@ -0,0 +1,81 @@
#[cfg(test)]
mod tests {
use crate::{addressbook_store::SqliteAddressbookStore, tests::get_test_addressbook_store};
use rstest::rstest;
use rustical_store::{Addressbook, AddressbookStore};
#[rstest]
#[tokio::test]
async fn test_addressbook_store(
#[from(get_test_addressbook_store)]
#[future]
addr_store: SqliteAddressbookStore,
) {
let addr_store = addr_store.await;
let cal = Addressbook {
id: "addr".to_string(),
principal: "fake-user".to_string(),
displayname: None,
description: None,
deleted_at: None,
synctoken: 0,
push_topic: "alskdj".to_string(),
};
assert!(
addr_store.insert_addressbook(cal).await.is_err(),
"This should fail due to the user not existing "
);
let addr = Addressbook {
id: "addr".to_string(),
principal: "user".to_string(),
displayname: None,
description: None,
deleted_at: None,
synctoken: 0,
push_topic: "alskdj".to_string(),
};
addr_store.insert_addressbook(addr.clone()).await.unwrap();
assert_eq!(
addr_store
.get_addressbook("user", "addr", false)
.await
.unwrap(),
addr
);
addr_store
.delete_addressbook("user", "addr", true)
.await
.unwrap();
let Err(err) = addr_store.get_addressbook("user", "addr", false).await else {
panic!()
};
assert!(err.is_not_found());
addr_store
.get_addressbook("user", "addr", true)
.await
.unwrap();
addr_store
.restore_addressbook("user", "addr")
.await
.unwrap();
addr_store
.delete_addressbook("user", "addr", false)
.await
.unwrap();
let Err(err) = addr_store.get_addressbook("user", "addr", true).await else {
panic!()
};
assert!(err.is_not_found());
}
}

View File

@@ -0,0 +1,76 @@
#[cfg(test)]
mod tests {
use crate::{calendar_store::SqliteCalendarStore, tests::get_test_calendar_store};
use rstest::rstest;
use rustical_store::{Calendar, CalendarMetadata, CalendarStore};
#[rstest]
#[tokio::test]
async fn test_calendar_store(
#[from(get_test_calendar_store)]
#[future]
cal_store: SqliteCalendarStore,
) {
let cal_store = cal_store.await;
let cal = Calendar {
principal: "fake-user".to_string(),
timezone_id: None,
deleted_at: None,
meta: CalendarMetadata::default(),
id: "cal".to_string(),
synctoken: 0,
subscription_url: None,
push_topic: "alskdj".to_string(),
components: vec![],
};
assert!(
cal_store.insert_calendar(cal).await.is_err(),
"This should fail due to the user not existing "
);
let cal = Calendar {
principal: "user".to_string(),
timezone_id: None,
deleted_at: None,
meta: CalendarMetadata::default(),
id: "cal".to_string(),
synctoken: 0,
subscription_url: None,
push_topic: "alskdj".to_string(),
components: vec![],
};
cal_store.insert_calendar(cal.clone()).await.unwrap();
assert_eq!(
cal_store.get_calendar("user", "cal", false).await.unwrap(),
cal
);
cal_store
.delete_calendar("user", "cal", true)
.await
.unwrap();
let Err(err) = cal_store.get_calendar("user", "cal", false).await else {
panic!()
};
assert!(err.is_not_found());
cal_store.get_calendar("user", "cal", true).await.unwrap();
cal_store.restore_calendar("user", "cal").await.unwrap();
cal_store
.delete_calendar("user", "cal", false)
.await
.unwrap();
let Err(err) = cal_store.get_calendar("user", "cal", true).await else {
panic!()
};
assert!(err.is_not_found());
}
}

View File

@@ -2,12 +2,18 @@ use crate::{
SqliteStore, addressbook_store::SqliteAddressbookStore, calendar_store::SqliteCalendarStore, SqliteStore, addressbook_store::SqliteAddressbookStore, calendar_store::SqliteCalendarStore,
principal_store::SqlitePrincipalStore, principal_store::SqlitePrincipalStore,
}; };
use rustical_store::auth::{AuthenticationProvider, Principal, PrincipalType}; use rustical_store::{
Secret,
auth::{AuthenticationProvider, Principal, PrincipalType},
};
use sqlx::SqlitePool; use sqlx::SqlitePool;
use tokio::sync::OnceCell; use tokio::sync::OnceCell;
static DB: OnceCell<SqlitePool> = OnceCell::const_new(); static DB: OnceCell<SqlitePool> = OnceCell::const_new();
mod addressbook_store;
mod calendar_store;
async fn get_test_db() -> SqlitePool { async fn get_test_db() -> SqlitePool {
DB.get_or_init(async || { DB.get_or_init(async || {
let db = SqlitePool::connect("sqlite::memory:").await.unwrap(); let db = SqlitePool::connect("sqlite::memory:").await.unwrap();
@@ -28,6 +34,10 @@ async fn get_test_db() -> SqlitePool {
) )
.await .await
.unwrap(); .unwrap();
principal_store
.add_app_token("user", "test".to_string(), "pass".to_string())
.await
.unwrap();
db db
}) })

View File

@@ -1,6 +1,7 @@
[package] [package]
name = "rustical_xml" name = "rustical_xml"
version.workspace = true version.workspace = true
rust-version.workspace = true
edition.workspace = true edition.workspace = true
description.workspace = true description.workspace = true
repository.workspace = true repository.workspace = true

View File

@@ -1,7 +1,8 @@
[package] [package]
name = "xml_derive" name = "xml_derive"
version = "0.1.0" version.workspace = true
edition = "2024" rust-version.workspace = true
edition.workspace = true
license.workspace = true license.workspace = true
[lib] [lib]

View File

@@ -0,0 +1 @@
google-site-verification: googlec55e08580a46745c.html

View File

@@ -178,7 +178,9 @@ pub fn make_app<
tracing::debug!("unauthorized"); tracing::debug!("unauthorized");
} }
StatusCode::NOT_FOUND => { StatusCode::NOT_FOUND => {
tracing::warn!("client error"); // Clients like GNOME Calendar will try to reach /remote.php/webdav
// quite often clogging up the logs
tracing::info!("client error");
} }
_ => { _ => {
tracing::error!("client error"); tracing::error!("client error");

View File

@@ -0,0 +1,213 @@
use crate::integration_tests::{ResponseExtractString, get_app};
use axum::body::Body;
use axum::extract::Request;
use headers::{Authorization, HeaderMapExt};
use http::{HeaderValue, StatusCode};
use rstest::rstest;
use rustical_store::{CalendarMetadata, CalendarStore};
use rustical_store_sqlite::{calendar_store::SqliteCalendarStore, tests::get_test_calendar_store};
use tower::ServiceExt;
fn mkcalendar_template(
CalendarMetadata {
displayname,
order: _order,
description,
color,
}: &CalendarMetadata,
) -> String {
format!(
r#"
<?xml version='1.0' encoding='UTF-8' ?>
<CAL:mkcalendar 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>{displayname}</displayname>
<CAL:calendar-description>{description}</CAL:calendar-description>
<n0:calendar-color xmlns:n0="http://apple.com/ns/ical/">{color}</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>
</prop>
</set>
</CAL:mkcalendar>
"#,
displayname = displayname.as_deref().unwrap_or_default(),
description = description.as_deref().unwrap_or_default(),
color = color.as_deref().unwrap_or_default(),
)
}
#[rstest]
#[tokio::test]
async fn test_caldav_calendar(
#[from(get_app)]
#[future]
app: axum::Router,
#[from(get_test_calendar_store)]
#[future]
cal_store: SqliteCalendarStore,
) {
let app = app.await;
let cal_store = cal_store.await;
let mut calendar_meta = CalendarMetadata {
displayname: Some("Calendar".to_string()),
description: Some("Description".to_string()),
color: Some("#00FF00".to_string()),
order: 0,
};
let (principal, cal_id) = ("user", "calendar");
let url = format!("/caldav/principal/{principal}/{cal_id}");
let request_template = || {
Request::builder()
.method("MKCALENDAR")
.uri(&url)
.body(Body::from(mkcalendar_template(&calendar_meta)))
.unwrap()
};
// Try OPTIONS without authentication
let request = Request::builder()
.method("OPTIONS")
.uri(&url)
.body(Body::empty())
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
insta::assert_debug_snapshot!(response, @r#"
Response {
status: 200,
version: HTTP/1.1,
headers: {
"dav": "1, 3, access-control, calendar-access, webdav-push",
"allow": "PROPFIND, PROPPATCH, COPY, MOVE, DELETE, OPTIONS, REPORT, GET, HEAD, POST, MKCOL, MKCALENDAR, IMPORT",
},
body: Body(
UnsyncBoxBody,
),
}
"#);
// Try without authentication
let request = request_template();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
// Try with correct credentials
let mut request = request_template();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
let body = response.extract_string().await;
insta::assert_snapshot!("mkcalendar_body", body);
let mut request = Request::builder()
.method("GET")
.uri(&url)
.body(Body::empty())
.unwrap();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.extract_string().await;
insta::assert_snapshot!("get_body", body);
assert_eq!(
cal_store
.get_calendar(principal, cal_id, false)
.await
.unwrap()
.meta,
calendar_meta
);
let mut request = Request::builder()
.method("PROPFIND")
.uri(&url)
.body(Body::empty())
.unwrap();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::MULTI_STATUS);
let body = response.extract_string().await;
insta::with_settings!({
filters => vec![
(r"<PUSH:topic>[0-9a-f-]+</PUSH:topic>", "<PUSH:topic>[PUSH_TOPIC]</PUSH:topic>")
]
}, {
insta::assert_snapshot!("propfind_body", body);
});
let proppatch_request: &str = r#"
<propertyupdate xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CARD="urn:ietf:params:xml:ns:carddav">
<set>
<prop>
<displayname>New Displayname</displayname>
<CAL:calendar-description>Test</CAL:calendar-description>
</prop>
</set>
<remove>
<prop>
<CAL:calendar-description />
</prop>
</remove>
</propertyupdate>
"#;
let mut request = Request::builder()
.method("PROPPATCH")
.uri(&url)
.body(Body::from(proppatch_request))
.unwrap();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::MULTI_STATUS);
let body = response.extract_string().await;
insta::assert_snapshot!("proppatch_body", body);
calendar_meta.displayname = Some("New Displayname".to_string());
calendar_meta.description = None;
assert_eq!(
cal_store
.get_calendar(principal, cal_id, false)
.await
.unwrap()
.meta,
calendar_meta
);
let mut request = Request::builder()
.method("DELETE")
.uri(&url)
.header("X-No-Trashbin", HeaderValue::from_static("1"))
.body(Body::empty())
.unwrap();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.extract_string().await;
insta::assert_snapshot!("delete_body", body);
assert!(matches!(
cal_store.get_calendar(principal, cal_id, false).await,
Err(rustical_store::Error::NotFound)
));
}

View File

@@ -0,0 +1,111 @@
use crate::integration_tests::{ResponseExtractString, get_app};
use axum::body::Body;
use axum::extract::Request;
use headers::{Authorization, HeaderMapExt};
use http::{HeaderValue, StatusCode};
use rstest::rstest;
use tower::ServiceExt;
mod calendar;
#[rstest]
#[tokio::test]
async fn test_caldav_root(
#[from(get_app)]
#[future]
app: axum::Router,
) {
let app = app.await;
let request_template = || {
Request::builder()
.method("PROPFIND")
.uri("/caldav")
.body(Body::empty())
.unwrap()
};
// Try without authentication
let request = request_template();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
// Try with wrong password
let mut request = request_template();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "wrongpass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
// Try with correct credentials
let mut request = request_template();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::MULTI_STATUS);
let body = response.extract_string().await;
insta::assert_snapshot!("propfind_body", body);
}
#[rstest]
#[tokio::test]
async fn test_caldav_principal(
#[from(get_app)]
#[future]
app: axum::Router,
) {
let app = app.await;
let request_template = || {
Request::builder()
.method("PROPFIND")
.uri("/caldav/principal/user")
.body(Body::empty())
.unwrap()
};
// Try without authentication
let request = request_template();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
// Try with wrong password
let mut request = request_template();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "wrongpass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
// Try with correct credentials
let mut request = request_template();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::MULTI_STATUS);
let body = response.extract_string().await;
insta::assert_snapshot!("propfind_depth_0", body);
// Try with Depth: 1
let mut request = request_template();
request
.headers_mut()
.typed_insert(Authorization::basic("user", "pass"));
request
.headers_mut()
.insert("Depth", HeaderValue::from_static("1"));
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::MULTI_STATUS);
let body = response.extract_string().await;
insta::with_settings!({
filters => vec![
(r"<PUSH:topic>[0-9a-f-]+</PUSH:topic>", "<PUSH:topic>[PUSH_TOPIC]</PUSH:topic>")
]
}, {
insta::assert_snapshot!("propfind_depth_1", body);
});
}

View File

@@ -0,0 +1,5 @@
---
source: src/integration_tests/caldav/calendar.rs
expression: body
---

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