mirror of
https://github.com/lennart-k/rustical.git
synced 2026-01-30 16:28:21 +00:00
Compare commits
101 Commits
v0.11.4
...
7e099bcd6e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e099bcd6e | ||
|
|
dde05d2f45 | ||
|
|
4adf1818d4 | ||
|
|
f503bf2bf7 | ||
|
|
7c15976a1a | ||
|
|
669d81aea0 | ||
|
|
967d18de95 | ||
|
|
63373ad525 | ||
|
|
2c67890343 | ||
|
|
5ec2787ecf | ||
|
|
7eecd95757 | ||
|
|
c165e761be | ||
|
|
5f68a5ae5c | ||
|
|
c77b59dcb0 | ||
|
|
276fdcacf5 | ||
|
|
43fff63008 | ||
|
|
977fd75500 | ||
|
|
5639127782 | ||
|
|
a2255bc7f1 | ||
|
|
758793a11a | ||
|
|
a9f3833a32 | ||
|
|
896e934c0a | ||
|
|
bb880aa403 | ||
|
|
69acde10ba | ||
|
|
d84158e8ad | ||
|
|
7ef566040a | ||
|
|
1c1f0c6da2 | ||
|
|
3fafbd22f4 | ||
|
|
e68dc921e6 | ||
|
|
60b45e70ad | ||
|
|
a0c33c82dd | ||
|
|
8ae5e46abf | ||
|
|
48b2e614a8 | ||
|
|
f26214abb9 | ||
|
|
276e65d41a | ||
|
|
7c3e9ecbc1 | ||
|
|
53f81a9433 | ||
|
|
55eabfde4a | ||
|
|
5d9d6e3fdf | ||
|
|
1567bc64ef | ||
|
|
44ae995f29 | ||
|
|
9c1cd24d32 | ||
|
|
ff0c5697cf | ||
|
|
6ccb5a67e4 | ||
|
|
da718dd290 | ||
|
|
4112347e24 | ||
|
|
f4fd1cdd21 | ||
|
|
5f0ca67e54 | ||
|
|
3aef9abe48 | ||
|
|
9784f2b53f | ||
|
|
271fdfd686 | ||
|
|
4fabf74333 | ||
|
|
7b154adec3 | ||
|
|
951a1e4bdc | ||
|
|
8c44733d0a | ||
|
|
829f7b727f | ||
|
|
037e6f5c92 | ||
|
|
311ceb6bc5 | ||
|
|
1174af3a4b | ||
|
|
845b3e61e3 | ||
|
|
e5d6541ffb | ||
|
|
b632ff6fe8 | ||
|
|
1ee873ac93 | ||
|
|
bf5bdb96bc | ||
|
|
47c2a55941 | ||
|
|
bfcd94f096 | ||
|
|
8cbb72719d | ||
|
|
ff0246c4fc | ||
|
|
15124a2fd5 | ||
|
|
5c6f63a5f3 | ||
|
|
17ba8faef2 | ||
|
|
578ddde36d | ||
|
|
9c3972e21c | ||
|
|
816c26565a | ||
|
|
4de0f9f665 | ||
|
|
cf31a51965 | ||
|
|
9fc099f6f4 | ||
|
|
498be172c9 | ||
|
|
b8c395e746 | ||
|
|
4b8a8c61f2 | ||
|
|
f778c470d0 | ||
|
|
d44a172261 | ||
|
|
e0ba34baea | ||
|
|
a7893ddbda | ||
|
|
ed7becffc2 | ||
|
|
c29400a799 | ||
|
|
047552a726 | ||
|
|
1cfc8e7c23 | ||
|
|
b0fdca1b64 | ||
|
|
b65cca9d17 | ||
|
|
55ecbdcd41 | ||
|
|
89d3d3b7a4 | ||
|
|
a74b74369c | ||
|
|
85c49a0bdf | ||
|
|
f2e4e2c1a7 | ||
|
|
28c925301e | ||
|
|
b50ea478db | ||
|
|
2c7748255c | ||
|
|
f40a23a1f1 | ||
|
|
2a4ba33e45 | ||
|
|
6bc4bd3fa3 |
19
.github/workflows/cicd.yml
vendored
19
.github/workflows/cicd.yml
vendored
@@ -5,6 +5,7 @@ permissions:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
RUST_VERSION: "1.92"
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
@@ -12,7 +13,9 @@ jobs:
|
||||
name: Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: rustup update
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ env.RUST_VERSION }}
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
- run: cargo check
|
||||
@@ -21,7 +24,9 @@ jobs:
|
||||
name: Test Suite
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: rustup update
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ env.RUST_VERSION }}
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
- run: cargo test --all-features --verbose --workspace
|
||||
@@ -30,7 +35,9 @@ jobs:
|
||||
name: Test Coverage
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: rustup update
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ env.RUST_VERSION }}
|
||||
- name: Install tarpaulin
|
||||
run: cargo install cargo-tarpaulin
|
||||
|
||||
@@ -44,8 +51,10 @@ jobs:
|
||||
name: Lints
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: rustup update
|
||||
- run: rustup component add rustfmt clippy
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ env.RUST_VERSION }}
|
||||
components: rustfmt, clippy
|
||||
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
|
||||
14
.github/workflows/docker-publish.yml
vendored
14
.github/workflows/docker-publish.yml
vendored
@@ -2,7 +2,10 @@ name: Docker
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
- feat/*
|
||||
release:
|
||||
types: ["published"]
|
||||
|
||||
@@ -26,12 +29,12 @@ jobs:
|
||||
|
||||
# https://github.com/docker/setup-buildx-action
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
# https://github.com/docker/login-action
|
||||
- name: Log into registry ${{ env.REGISTRY }}
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -45,7 +48,8 @@ jobs:
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
${{ github.ref_name == 'main' && 'type=ref,event=branch' || '' }}
|
||||
type=ref,event=branch,prefix=br-
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
@@ -54,7 +58,7 @@ jobs:
|
||||
# https://github.com/docker/build-push-action
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/arm64,linux/amd64
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -16,3 +16,5 @@ site
|
||||
# Frontend
|
||||
**/node_modules
|
||||
**/.vite
|
||||
|
||||
**/*.snap.new
|
||||
|
||||
12
.sqlx/query-146e23ae4e0eaae4d65ac7563c67d4f295ccc2534dcc4b3bd710de773ed137f9.json
generated
Normal file
12
.sqlx/query-146e23ae4e0eaae4d65ac7563c67d4f295ccc2534dcc4b3bd710de773ed137f9.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM calendarobjectchangelog WHERE (principal, cal_id, object_id) = (?, ?, ?);",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "146e23ae4e0eaae4d65ac7563c67d4f295ccc2534dcc4b3bd710de773ed137f9"
|
||||
}
|
||||
12
.sqlx/query-354decac84758c88280f60fbf0f93dddc6c7ff92ac7b8ba44049d31df3c680e3.json
generated
Normal file
12
.sqlx/query-354decac84758c88280f60fbf0f93dddc6c7ff92ac7b8ba44049d31df3c680e3.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "UPDATE calendarobjects SET ics = ? WHERE (principal, cal_id, id) = (?, ?, ?);",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 4
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "354decac84758c88280f60fbf0f93dddc6c7ff92ac7b8ba44049d31df3c680e3"
|
||||
}
|
||||
38
.sqlx/query-bdaa4bee8b01d0e3773e34672ed4805d1e71d24888f2227045afd90bf080fc23.json
generated
Normal file
38
.sqlx/query-bdaa4bee8b01d0e3773e34672ed4805d1e71d24888f2227045afd90bf080fc23.json
generated
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT principal, cal_id, id, ics FROM calendarobjects WHERE ics LIKE '%VERSION:4.0%';",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "principal",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "cal_id",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "id",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ics",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "bdaa4bee8b01d0e3773e34672ed4805d1e71d24888f2227045afd90bf080fc23"
|
||||
}
|
||||
788
Cargo.lock
generated
788
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
19
Cargo.toml
19
Cargo.toml
@@ -2,8 +2,8 @@
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.11.4"
|
||||
rust-version = "1.91"
|
||||
version = "0.11.17"
|
||||
rust-version = "1.92"
|
||||
edition = "2024"
|
||||
description = "A CalDAV server"
|
||||
documentation = "https://lennart-k.github.io/rustical/"
|
||||
@@ -32,12 +32,11 @@ opentelemetry = [
|
||||
"dep:tracing-opentelemetry",
|
||||
]
|
||||
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
|
||||
[workspace.dependencies]
|
||||
rustical_dav = { path = "./crates/dav/" }
|
||||
rustical_dav = { path = "./crates/dav/", features = ["ical"] }
|
||||
rustical_dav_push = { path = "./crates/dav_push/" }
|
||||
rustical_store = { path = "./crates/store/" }
|
||||
rustical_store_sqlite = { path = "./crates/store_sqlite/" }
|
||||
@@ -74,7 +73,7 @@ tokio = { version = "1.48", features = [
|
||||
url = "2.5"
|
||||
base64 = "0.22"
|
||||
thiserror = "2.0"
|
||||
quick-xml = { version = "0.38" }
|
||||
quick-xml = { version = "0.39" }
|
||||
rust-embed = "8.9"
|
||||
tower-sessions = "0.14"
|
||||
futures-core = "0.3"
|
||||
@@ -90,8 +89,8 @@ derive_more = { version = "2.1", features = [
|
||||
"constructor",
|
||||
"display",
|
||||
] }
|
||||
askama = { version = "0.14", features = ["serde_json"] }
|
||||
askama_web = { version = "0.14", features = ["axum-0.8"] }
|
||||
askama = { version = "0.15", features = ["serde_json"] }
|
||||
askama_web = { version = "0.15", features = ["axum-0.8"] }
|
||||
sqlx = { version = "0.8", default-features = false, features = [
|
||||
"sqlx-sqlite",
|
||||
"uuid",
|
||||
@@ -108,9 +107,7 @@ strum = "0.27"
|
||||
strum_macros = "0.27"
|
||||
serde_json = { version = "1.0", features = ["raw_value"] }
|
||||
sqlx-sqlite = { version = "0.8", features = ["bundled"] }
|
||||
ical = { git = "https://github.com/lennart-k/ical-rs", features = [
|
||||
"generator",
|
||||
"serde",
|
||||
ical = { git = "https://github.com/lennart-k/ical-rs", branch = "dev", features = [
|
||||
"chrono-tz",
|
||||
] }
|
||||
toml = "0.9"
|
||||
@@ -150,6 +147,7 @@ openssl = { version = "0.10", features = ["vendored"] }
|
||||
async-std = { version = "1.13", features = ["attributes"] }
|
||||
similar-asserts = "1.7"
|
||||
insta = { version = "1.44", features = ["filters"] }
|
||||
criterion = { version = "0.8", features = ["async_tokio"] }
|
||||
|
||||
[dev-dependencies]
|
||||
rstest.workspace = true
|
||||
@@ -162,6 +160,7 @@ rustical_store_sqlite.workspace = true
|
||||
rustical_caldav.workspace = true
|
||||
rustical_carddav.workspace = true
|
||||
rustical_frontend.workspace = true
|
||||
ical.workspace = true
|
||||
toml.workspace = true
|
||||
serde.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM --platform=$BUILDPLATFORM rust:1.91-alpine AS chef
|
||||
FROM --platform=$BUILDPLATFORM rust:1.92-alpine AS chef
|
||||
|
||||
ARG TARGETPLATFORM
|
||||
ARG BUILDPLATFORM
|
||||
@@ -36,7 +36,7 @@ COPY --from=planner /rustical/recipe.json recipe.json
|
||||
RUN cargo chef cook --release --target "$(cat /tmp/rust_target)"
|
||||
|
||||
COPY . .
|
||||
RUN cargo install --target "$(cat /tmp/rust_target)" --path .
|
||||
RUN cargo install --locked --target "$(cat /tmp/rust_target)" --path .
|
||||
|
||||
FROM scratch
|
||||
COPY --from=builder /usr/local/cargo/bin/rustical /usr/local/bin/rustical
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
[](https://raw.githubusercontent.com/lennart-k/rustical/main/LICENSE)
|
||||
[](https://coveralls.io/github/lennart-k/rustical?branch=main)
|
||||
|
||||
# RustiCal
|
||||
|
||||
a CalDAV/CardDAV server
|
||||
|
||||
@@ -29,7 +29,7 @@ base64.workspace = true
|
||||
serde.workspace = true
|
||||
tokio.workspace = true
|
||||
url.workspace = true
|
||||
rustical_dav.workspace = true
|
||||
rustical_dav = { workspace = true, features = ["ical"] }
|
||||
rustical_store.workspace = true
|
||||
chrono.workspace = true
|
||||
chrono-tz.workspace = true
|
||||
|
||||
@@ -5,12 +5,11 @@ use axum::extract::State;
|
||||
use axum::{extract::Path, response::Response};
|
||||
use headers::{ContentType, HeaderMapExt};
|
||||
use http::{HeaderValue, Method, StatusCode, header};
|
||||
use ical::generator::{Emitter, IcalCalendarBuilder};
|
||||
use ical::property::Property;
|
||||
use ical::component::IcalCalendar;
|
||||
use ical::generator::Emitter;
|
||||
use ical::property::ContentLine;
|
||||
use percent_encoding::{CONTROLS, utf8_percent_encode};
|
||||
use rustical_ical::{CalendarObjectComponent, EventObject};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
|
||||
@@ -32,70 +31,49 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let mut vtimezones = HashMap::new();
|
||||
let objects = cal_store.get_objects(&principal, &calendar_id).await?;
|
||||
let objects = cal_store
|
||||
.get_objects(&principal, &calendar_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(_, object)| object.into())
|
||||
.collect();
|
||||
|
||||
let mut props = vec![];
|
||||
|
||||
let mut ical_calendar_builder = IcalCalendarBuilder::version("4.0")
|
||||
.gregorian()
|
||||
.prodid("RustiCal");
|
||||
if let Some(displayname) = calendar.meta.displayname {
|
||||
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||
props.push(ContentLine {
|
||||
name: "X-WR-CALNAME".to_owned(),
|
||||
value: Some(displayname),
|
||||
params: vec![],
|
||||
params: vec![].into(),
|
||||
});
|
||||
}
|
||||
if let Some(description) = calendar.meta.description {
|
||||
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||
props.push(ContentLine {
|
||||
name: "X-WR-CALDESC".to_owned(),
|
||||
value: Some(description),
|
||||
params: vec![],
|
||||
params: vec![].into(),
|
||||
});
|
||||
}
|
||||
if let Some(color) = calendar.meta.color {
|
||||
props.push(ContentLine {
|
||||
name: "X-WR-CALCOLOR".to_owned(),
|
||||
value: Some(color),
|
||||
params: vec![].into(),
|
||||
});
|
||||
}
|
||||
if let Some(timezone_id) = calendar.timezone_id {
|
||||
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||
props.push(ContentLine {
|
||||
name: "X-WR-TIMEZONE".to_owned(),
|
||||
value: Some(timezone_id),
|
||||
params: vec![],
|
||||
params: vec![].into(),
|
||||
});
|
||||
}
|
||||
|
||||
for object in &objects {
|
||||
vtimezones.extend(object.get_vtimezones());
|
||||
match object.get_data() {
|
||||
CalendarObjectComponent::Event(EventObject { event, .. }, overrides) => {
|
||||
ical_calendar_builder = ical_calendar_builder.add_event(event.clone());
|
||||
for ev_override in overrides {
|
||||
ical_calendar_builder =
|
||||
ical_calendar_builder.add_event(ev_override.event.clone());
|
||||
}
|
||||
}
|
||||
CalendarObjectComponent::Todo(todo, overrides) => {
|
||||
ical_calendar_builder = ical_calendar_builder.add_todo(todo.clone());
|
||||
for ev_override in overrides {
|
||||
ical_calendar_builder = ical_calendar_builder.add_todo(ev_override.clone());
|
||||
}
|
||||
}
|
||||
CalendarObjectComponent::Journal(journal, overrides) => {
|
||||
ical_calendar_builder = ical_calendar_builder.add_journal(journal.clone());
|
||||
for ev_override in overrides {
|
||||
ical_calendar_builder = ical_calendar_builder.add_journal(ev_override.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for vtimezone in vtimezones.into_values() {
|
||||
ical_calendar_builder = ical_calendar_builder.add_tz(vtimezone.to_owned());
|
||||
}
|
||||
|
||||
let ical_calendar = ical_calendar_builder
|
||||
.build()
|
||||
.map_err(|parser_error| Error::IcalError(parser_error.into()))?;
|
||||
let export_calendar = IcalCalendar::from_objects("RustiCal Export".to_owned(), objects, props);
|
||||
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ContentType::from_str("text/calendar").unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/calendar; charset=utf-8").unwrap());
|
||||
|
||||
let filename = format!("{}_{}.ics", calendar.principal, calendar.id);
|
||||
let filename = utf8_percent_encode(&filename, CONTROLS);
|
||||
@@ -109,6 +87,6 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(ical_calendar.generate())).unwrap())
|
||||
Ok(resp.body(Body::new(export_calendar.generate())).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,12 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use ical::{
|
||||
generator::Emitter,
|
||||
parser::{Component, ComponentMut},
|
||||
};
|
||||
use ical::parser::{Component, ComponentMut};
|
||||
use rustical_dav::header::Overwrite;
|
||||
use rustical_ical::{CalendarObject, CalendarObjectType};
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_store::{
|
||||
Calendar, CalendarMetadata, CalendarStore, SubscriptionStore, auth::Principal,
|
||||
};
|
||||
use std::io::BufReader;
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(resource_service))]
|
||||
@@ -29,18 +25,8 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let mut parser = ical::IcalParser::new(BufReader::new(body.as_bytes()));
|
||||
let mut cal = parser
|
||||
.next()
|
||||
.expect("input must contain calendar")
|
||||
.unwrap()
|
||||
.mutable();
|
||||
if parser.next().is_some() {
|
||||
return Err(rustical_ical::Error::InvalidData(
|
||||
"multiple calendars, only one allowed".to_owned(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let parser = ical::IcalParser::from_slice(body.as_bytes());
|
||||
let mut cal = parser.expect_one()?.mutable();
|
||||
|
||||
// Extract calendar metadata
|
||||
let displayname = cal
|
||||
@@ -49,14 +35,19 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
|
||||
let description = cal
|
||||
.get_property("X-WR-CALDESC")
|
||||
.and_then(|prop| prop.value.clone());
|
||||
let color = cal
|
||||
.get_property("X-WR-CALCOLOR")
|
||||
.and_then(|prop| prop.value.clone());
|
||||
let timezone_id = cal
|
||||
.get_property("X-WR-TIMEZONE")
|
||||
.and_then(|prop| prop.value.clone());
|
||||
// These properties should not appear in the expanded calendar objects
|
||||
cal.remove_property("X-WR-CALNAME");
|
||||
cal.remove_property("X-WR-CALDESC");
|
||||
cal.remove_property("X-WR-CALCOLOR");
|
||||
cal.remove_property("X-WR-TIMEZONE");
|
||||
let cal = cal.verify().unwrap();
|
||||
let cal = cal.build(None).unwrap();
|
||||
|
||||
// Make sure timezone is valid
|
||||
if let Some(timezone_id) = timezone_id.as_ref() {
|
||||
assert!(
|
||||
@@ -64,8 +55,7 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
|
||||
"Invalid calendar timezone id"
|
||||
);
|
||||
}
|
||||
|
||||
// Extract necessary component types
|
||||
// // Extract necessary component types
|
||||
let mut cal_components = vec![];
|
||||
if !cal.events.is_empty() {
|
||||
cal_components.push(CalendarObjectType::Event);
|
||||
@@ -77,13 +67,7 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
|
||||
cal_components.push(CalendarObjectType::Todo);
|
||||
}
|
||||
|
||||
let expanded_cals = cal.expand_calendar();
|
||||
// Janky way to convert between IcalCalendar and CalendarObject
|
||||
let objects = expanded_cals
|
||||
.into_iter()
|
||||
.map(|cal| cal.generate())
|
||||
.map(|ics| CalendarObject::from_ics(ics, None))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let objects = cal.into_objects()?.into_iter().map(Into::into).collect();
|
||||
let new_cal = Calendar {
|
||||
principal,
|
||||
id: cal_id,
|
||||
@@ -91,7 +75,7 @@ pub async fn route_import<C: CalendarStore, S: SubscriptionStore>(
|
||||
displayname,
|
||||
order: 0,
|
||||
description,
|
||||
color: None,
|
||||
color,
|
||||
},
|
||||
timezone_id,
|
||||
deleted_at: None,
|
||||
|
||||
@@ -87,17 +87,18 @@ pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
Some(tzid)
|
||||
} else if let Some(tz) = request.calendar_timezone {
|
||||
// TODO: Proper error (calendar-timezone precondition)
|
||||
let calendar = IcalParser::new(tz.as_bytes())
|
||||
let calendar = IcalParser::from_slice(tz.as_bytes())
|
||||
.next()
|
||||
.ok_or_else(|| rustical_dav::Error::BadRequest("No timezone data provided".to_owned()))?
|
||||
.map_err(|_| rustical_dav::Error::BadRequest("No timezone data provided".to_owned()))?;
|
||||
.map_err(|_| rustical_dav::Error::BadRequest("Error parsing timezone".to_owned()))?;
|
||||
|
||||
let timezone = calendar.timezones.first().ok_or_else(|| {
|
||||
let timezone = calendar.vtimezones.values().next().ok_or_else(|| {
|
||||
rustical_dav::Error::BadRequest("No timezone data provided".to_owned())
|
||||
})?;
|
||||
let timezone: chrono_tz::Tz = timezone
|
||||
.try_into()
|
||||
.map_err(|_| rustical_dav::Error::BadRequest("No timezone data provided".to_owned()))?;
|
||||
let timezone: Option<chrono_tz::Tz> = timezone.into();
|
||||
let timezone = timezone.ok_or_else(|| {
|
||||
rustical_dav::Error::BadRequest("Cannot translate VTIMEZONE into IANA TZID".to_owned())
|
||||
})?;
|
||||
|
||||
Some(timezone.name().to_owned())
|
||||
} else {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
store: &C,
|
||||
) -> Result<(Vec<CalendarObject>, Vec<String>), Error> {
|
||||
) -> Result<(Vec<(String, CalendarObject)>, Vec<String>), Error> {
|
||||
let mut result = vec![];
|
||||
let mut not_found = vec![];
|
||||
|
||||
@@ -32,7 +32,7 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
|
||||
let filename = filename.trim_start_matches('/');
|
||||
if let Some(object_id) = filename.strip_suffix(".ics") {
|
||||
match store.get_object(principal, cal_id, object_id, false).await {
|
||||
Ok(object) => result.push(object),
|
||||
Ok(object) => result.push((object_id.to_owned(), object)),
|
||||
Err(rustical_store::Error::NotFound) => not_found.push(href.to_string()),
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@ use crate::calendar::methods::report::calendar_query::{
|
||||
TimeRangeElement,
|
||||
prop_filter::{PropFilterElement, PropFilterable},
|
||||
};
|
||||
use ical::parser::ical::component::IcalTimeZone;
|
||||
use rustical_ical::{CalendarObject, CalendarObjectComponent, CalendarObjectType};
|
||||
use ical::{
|
||||
component::{CalendarInnerData, IcalAlarm, IcalCalendarObject, IcalEvent, IcalTodo},
|
||||
parser::{Component, ical::component::IcalTimeZone},
|
||||
};
|
||||
use rustical_xml::XmlDeserialize;
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
@@ -68,9 +70,98 @@ pub trait CompFilterable: PropFilterable + Sized {
|
||||
}
|
||||
}
|
||||
|
||||
impl CompFilterable for CalendarObject {
|
||||
impl CompFilterable for CalendarInnerData {
|
||||
fn get_comp_name(&self) -> &'static str {
|
||||
"VCALENDAR"
|
||||
match self {
|
||||
Self::Event(main, _) => main.get_comp_name(),
|
||||
Self::Journal(main, _) => main.get_comp_name(),
|
||||
Self::Todo(main, _) => main.get_comp_name(),
|
||||
}
|
||||
}
|
||||
|
||||
fn match_time_range(&self, time_range: &TimeRangeElement) -> bool {
|
||||
if let Some(start) = &time_range.start
|
||||
&& let Some(last_end) = self.get_last_occurence()
|
||||
&& start.to_utc() > last_end.utc()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(end) = &time_range.end
|
||||
&& let Some(first_start) = self.get_first_occurence()
|
||||
&& end.to_utc() < first_start.utc()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool {
|
||||
match self {
|
||||
Self::Event(main, overrides) => std::iter::once(main)
|
||||
.chain(overrides.iter())
|
||||
.flat_map(IcalEvent::get_alarms)
|
||||
.any(|alarm| alarm.matches(comp_filter)),
|
||||
Self::Todo(main, overrides) => std::iter::once(main)
|
||||
.chain(overrides.iter())
|
||||
.flat_map(IcalTodo::get_alarms)
|
||||
.any(|alarm| alarm.matches(comp_filter)),
|
||||
// VJOURNAL has no subcomponents
|
||||
Self::Journal(_, _) => comp_filter.is_not_defined.is_some(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalAlarm {
|
||||
fn get_named_properties<'a>(
|
||||
&'a self,
|
||||
name: &'a str,
|
||||
) -> impl Iterator<Item = &'a ical::property::ContentLine> {
|
||||
Component::get_named_properties(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl CompFilterable for IcalAlarm {
|
||||
fn get_comp_name(&self) -> &'static str {
|
||||
Component::get_comp_name(self)
|
||||
}
|
||||
|
||||
fn match_time_range(&self, _time_range: &TimeRangeElement) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool {
|
||||
comp_filter.is_not_defined.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for CalendarInnerData {
|
||||
#[allow(refining_impl_trait)]
|
||||
fn get_named_properties<'a>(
|
||||
&'a self,
|
||||
name: &'a str,
|
||||
) -> Box<dyn Iterator<Item = &'a ical::property::ContentLine> + 'a> {
|
||||
// TODO: If we were pedantic, we would have to do recurrence expansion first
|
||||
// and take into account the overrides :(
|
||||
match self {
|
||||
Self::Event(main, _) => Box::new(main.get_named_properties(name)),
|
||||
Self::Todo(main, _) => Box::new(main.get_named_properties(name)),
|
||||
Self::Journal(main, _) => Box::new(main.get_named_properties(name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalCalendarObject {
|
||||
fn get_named_properties<'a>(
|
||||
&'a self,
|
||||
name: &'a str,
|
||||
) -> impl Iterator<Item = &'a ical::property::ContentLine> {
|
||||
Component::get_named_properties(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl CompFilterable for IcalCalendarObject {
|
||||
fn get_comp_name(&self) -> &'static str {
|
||||
Component::get_comp_name(self)
|
||||
}
|
||||
|
||||
fn match_time_range(&self, _time_range: &TimeRangeElement) -> bool {
|
||||
@@ -83,72 +174,53 @@ impl CompFilterable for CalendarObject {
|
||||
.get_vtimezones()
|
||||
.values()
|
||||
.map(|tz| tz.matches(comp_filter))
|
||||
.chain([self.get_data().matches(comp_filter)]);
|
||||
.chain([self.get_inner().matches(comp_filter)]);
|
||||
|
||||
if comp_filter.is_not_defined.is_some() {
|
||||
matches.all(|x| x)
|
||||
matches.all(|x| !x)
|
||||
} else {
|
||||
matches.any(|x| x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalTimeZone {
|
||||
fn get_named_properties<'a>(
|
||||
&'a self,
|
||||
name: &'a str,
|
||||
) -> impl Iterator<Item = &'a ical::property::ContentLine> {
|
||||
Component::get_named_properties(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl CompFilterable for IcalTimeZone {
|
||||
fn get_comp_name(&self) -> &'static str {
|
||||
"VTIMEZONE"
|
||||
Component::get_comp_name(self)
|
||||
}
|
||||
|
||||
fn match_time_range(&self, _time_range: &TimeRangeElement) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn match_subcomponents(&self, _comp_filter: &CompFilterElement) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl CompFilterable for CalendarObjectComponent {
|
||||
fn get_comp_name(&self) -> &'static str {
|
||||
CalendarObjectType::from(self).as_str()
|
||||
}
|
||||
|
||||
fn match_time_range(&self, time_range: &TimeRangeElement) -> bool {
|
||||
if let Some(start) = &time_range.start
|
||||
&& let Some(last_occurence) = self.get_last_occurence().unwrap_or(None)
|
||||
&& **start > last_occurence.utc()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(end) = &time_range.end
|
||||
&& let Some(first_occurence) = self.get_first_occurence().unwrap_or(None)
|
||||
&& **end < first_occurence.utc()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn match_subcomponents(&self, _comp_filter: &CompFilterElement) -> bool {
|
||||
// TODO: Properly check subcomponents
|
||||
true
|
||||
fn match_subcomponents(&self, comp_filter: &CompFilterElement) -> bool {
|
||||
// VTIMEZONE has no subcomponents
|
||||
comp_filter.is_not_defined.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{TimeZone, Utc};
|
||||
use rustical_dav::xml::{MatchType, NegateCondition, TextCollation, TextMatchElement};
|
||||
use rustical_ical::{CalendarObject, UtcDateTime};
|
||||
|
||||
use crate::calendar::methods::report::calendar_query::{
|
||||
CompFilterable, TextMatchElement, TimeRangeElement,
|
||||
comp_filter::CompFilterElement,
|
||||
prop_filter::PropFilterElement,
|
||||
text_match::{NegateCondition, TextCollation},
|
||||
CompFilterElement, CompFilterable, PropFilterElement, TimeRangeElement,
|
||||
};
|
||||
|
||||
const ICS: &str = r"BEGIN:VCALENDAR
|
||||
CALSCALE:GREGORIAN
|
||||
VERSION:2.0
|
||||
PRODID:me
|
||||
BEGIN:VTIMEZONE
|
||||
TZID:Europe/Berlin
|
||||
X-LIC-LOCATION:Europe/Berlin
|
||||
@@ -168,7 +240,7 @@ END:VCALENDAR";
|
||||
|
||||
#[test]
|
||||
fn test_comp_filter_matching() {
|
||||
let object = CalendarObject::from_ics(ICS.to_string(), None).unwrap();
|
||||
let object = CalendarObject::from_ics(ICS.to_string()).unwrap();
|
||||
|
||||
let comp_filter = CompFilterElement {
|
||||
is_not_defined: Some(()),
|
||||
@@ -177,7 +249,10 @@ END:VCALENDAR";
|
||||
prop_filter: vec![],
|
||||
comp_filter: vec![],
|
||||
};
|
||||
assert!(!object.matches(&comp_filter), "filter: wants no VCALENDAR");
|
||||
assert!(
|
||||
!object.get_inner().matches(&comp_filter),
|
||||
"filter: wants no VCALENDAR"
|
||||
);
|
||||
|
||||
let comp_filter = CompFilterElement {
|
||||
is_not_defined: None,
|
||||
@@ -192,7 +267,10 @@ END:VCALENDAR";
|
||||
comp_filter: vec![],
|
||||
}],
|
||||
};
|
||||
assert!(!object.matches(&comp_filter), "filter matches VTODO");
|
||||
assert!(
|
||||
!object.get_inner().matches(&comp_filter),
|
||||
"filter matches VTODO"
|
||||
);
|
||||
|
||||
let comp_filter = CompFilterElement {
|
||||
is_not_defined: None,
|
||||
@@ -207,7 +285,10 @@ END:VCALENDAR";
|
||||
comp_filter: vec![],
|
||||
}],
|
||||
};
|
||||
assert!(object.matches(&comp_filter), "filter matches VEVENT");
|
||||
assert!(
|
||||
object.get_inner().matches(&comp_filter),
|
||||
"filter matches VEVENT"
|
||||
);
|
||||
|
||||
let comp_filter = CompFilterElement {
|
||||
is_not_defined: None,
|
||||
@@ -219,6 +300,7 @@ END:VCALENDAR";
|
||||
name: "VERSION".to_string(),
|
||||
time_range: None,
|
||||
text_match: Some(TextMatchElement {
|
||||
match_type: MatchType::Contains,
|
||||
needle: "2.0".to_string(),
|
||||
collation: TextCollation::default(),
|
||||
negate_condition: NegateCondition::default(),
|
||||
@@ -242,6 +324,7 @@ END:VCALENDAR";
|
||||
name: "SUMMARY".to_string(),
|
||||
time_range: None,
|
||||
text_match: Some(TextMatchElement {
|
||||
match_type: MatchType::Contains,
|
||||
collation: TextCollation::default(),
|
||||
negate_condition: NegateCondition(false),
|
||||
needle: "weekly".to_string(),
|
||||
@@ -252,13 +335,13 @@ END:VCALENDAR";
|
||||
}],
|
||||
};
|
||||
assert!(
|
||||
object.matches(&comp_filter),
|
||||
object.get_inner().matches(&comp_filter),
|
||||
"Some prop filters on VCALENDAR and VEVENT"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn test_comp_filter_time_range() {
|
||||
let object = CalendarObject::from_ics(ICS.to_string(), None).unwrap();
|
||||
let object = CalendarObject::from_ics(ICS.to_string()).unwrap();
|
||||
|
||||
let comp_filter = CompFilterElement {
|
||||
is_not_defined: None,
|
||||
@@ -281,7 +364,7 @@ END:VCALENDAR";
|
||||
}],
|
||||
};
|
||||
assert!(
|
||||
object.matches(&comp_filter),
|
||||
object.get_inner().matches(&comp_filter),
|
||||
"event should lie in time range"
|
||||
);
|
||||
|
||||
@@ -306,14 +389,14 @@ END:VCALENDAR";
|
||||
}],
|
||||
};
|
||||
assert!(
|
||||
!object.matches(&comp_filter),
|
||||
!object.get_inner().matches(&comp_filter),
|
||||
"event should not lie in time range"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_match_timezone() {
|
||||
let object = CalendarObject::from_ics(ICS.to_string(), None).unwrap();
|
||||
let object = CalendarObject::from_ics(ICS.to_string()).unwrap();
|
||||
|
||||
let comp_filter = CompFilterElement {
|
||||
is_not_defined: None,
|
||||
@@ -329,6 +412,7 @@ END:VCALENDAR";
|
||||
name: "TZID".to_string(),
|
||||
time_range: None,
|
||||
text_match: Some(TextMatchElement {
|
||||
match_type: MatchType::Contains,
|
||||
collation: TextCollation::AsciiCasemap,
|
||||
negate_condition: NegateCondition::default(),
|
||||
needle: "Europe/Berlin".to_string(),
|
||||
@@ -339,7 +423,7 @@ END:VCALENDAR";
|
||||
}],
|
||||
};
|
||||
assert!(
|
||||
object.matches(&comp_filter),
|
||||
object.get_inner().matches(&comp_filter),
|
||||
"Timezone should be Europe/Berlin"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
use crate::{
|
||||
calendar::methods::report::calendar_query::{
|
||||
TextMatchElement,
|
||||
comp_filter::{CompFilterElement, CompFilterable},
|
||||
},
|
||||
calendar_object::CalendarObjectPropWrapperName,
|
||||
};
|
||||
use rustical_dav::xml::PropfindType;
|
||||
use rustical_ical::{CalendarObject, UtcDateTime};
|
||||
use super::comp_filter::{CompFilterElement, CompFilterable};
|
||||
use crate::calendar_object::CalendarObjectPropWrapperName;
|
||||
use ical::{component::IcalCalendarObject, property::ContentLine};
|
||||
use rustical_dav::xml::{PropfindType, TextMatchElement};
|
||||
use rustical_ical::UtcDateTime;
|
||||
use rustical_store::calendar_store::CalendarQuery;
|
||||
use rustical_xml::XmlDeserialize;
|
||||
use rustical_xml::{XmlDeserialize, XmlRootTag};
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
@@ -32,7 +28,25 @@ pub struct ParamFilterElement {
|
||||
pub(crate) name: String,
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
impl ParamFilterElement {
|
||||
#[must_use]
|
||||
pub fn match_property(&self, prop: &ContentLine) -> bool {
|
||||
let Some(param) = prop.params.get_param(&self.name) else {
|
||||
return self.is_not_defined.is_some();
|
||||
};
|
||||
if self.is_not_defined.is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(text_match) = self.text_match.as_ref() else {
|
||||
return true;
|
||||
};
|
||||
text_match.match_text(param)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, XmlRootTag, Clone, Debug, PartialEq)]
|
||||
#[xml(root = "filter", ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
#[allow(dead_code)]
|
||||
// https://datatracker.ietf.org/doc/html/rfc4791#section-9.7
|
||||
pub struct FilterElement {
|
||||
@@ -43,7 +57,7 @@ pub struct FilterElement {
|
||||
|
||||
impl FilterElement {
|
||||
#[must_use]
|
||||
pub fn matches(&self, cal_object: &CalendarObject) -> bool {
|
||||
pub fn matches(&self, cal_object: &IcalCalendarObject) -> bool {
|
||||
cal_object.matches(&self.comp_filter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,47 +5,43 @@ use rustical_store::CalendarStore;
|
||||
mod comp_filter;
|
||||
mod elements;
|
||||
mod prop_filter;
|
||||
pub mod text_match;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[allow(unused_imports)]
|
||||
pub use comp_filter::{CompFilterElement, CompFilterable};
|
||||
pub use elements::*;
|
||||
#[allow(unused_imports)]
|
||||
pub use prop_filter::{PropFilterElement, PropFilterable};
|
||||
#[allow(unused_imports)]
|
||||
pub use text_match::TextMatchElement;
|
||||
pub use prop_filter::PropFilterElement;
|
||||
|
||||
pub async fn get_objects_calendar_query<C: CalendarStore>(
|
||||
cal_query: &CalendarQueryRequest,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
store: &C,
|
||||
) -> Result<Vec<CalendarObject>, Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error> {
|
||||
let mut objects = store
|
||||
.calendar_query(principal, cal_id, cal_query.into())
|
||||
.await?;
|
||||
if let Some(filter) = &cal_query.filter {
|
||||
objects.retain(|object| filter.matches(object));
|
||||
objects.retain(|(_id, object)| filter.matches(object.get_inner()));
|
||||
}
|
||||
Ok(objects)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rustical_dav::xml::PropElement;
|
||||
use rustical_xml::XmlDocument;
|
||||
|
||||
mod xml_tests {
|
||||
use super::{
|
||||
CalendarQueryRequest, FilterElement, ParamFilterElement, comp_filter::CompFilterElement,
|
||||
prop_filter::PropFilterElement,
|
||||
};
|
||||
use crate::{
|
||||
calendar::methods::report::{
|
||||
ReportRequest,
|
||||
calendar_query::{
|
||||
CalendarQueryRequest, FilterElement, ParamFilterElement, TextMatchElement,
|
||||
comp_filter::CompFilterElement,
|
||||
prop_filter::PropFilterElement,
|
||||
text_match::{NegateCondition, TextCollation},
|
||||
},
|
||||
},
|
||||
calendar::methods::report::ReportRequest,
|
||||
calendar_object::{CalendarData, CalendarObjectPropName, CalendarObjectPropWrapperName},
|
||||
};
|
||||
use rustical_dav::xml::{
|
||||
MatchType, NegateCondition, PropElement, TextCollation, TextMatchElement,
|
||||
};
|
||||
use rustical_xml::XmlDocument;
|
||||
|
||||
#[test]
|
||||
fn calendar_query_7_8_7() {
|
||||
@@ -57,16 +53,16 @@ mod tests {
|
||||
<C:calendar-data/>
|
||||
</D:prop>
|
||||
<C:filter>
|
||||
<C:comp-filter name="VCALENDAR">
|
||||
<C:comp-filter name="VEVENT">
|
||||
<C:prop-filter name="ATTENDEE">
|
||||
<C:text-match collation="i;ascii-casemap">mailto:lisa@example.com</C:text-match>
|
||||
<C:param-filter name="PARTSTAT">
|
||||
<C:text-match collation="i;ascii-casemap">NEEDS-ACTION</C:text-match>
|
||||
</C:param-filter>
|
||||
</C:prop-filter>
|
||||
<C:comp-filter name="VCALENDAR">
|
||||
<C:comp-filter name="VEVENT">
|
||||
<C:prop-filter name="ATTENDEE">
|
||||
<C:text-match collation="i;ascii-casemap">mailto:lisa@example.com</C:text-match>
|
||||
<C:param-filter name="PARTSTAT">
|
||||
<C:text-match collation="i;ascii-casemap">NEEDS-ACTION</C:text-match>
|
||||
</C:param-filter>
|
||||
</C:prop-filter>
|
||||
</C:comp-filter>
|
||||
</C:comp-filter>
|
||||
</C:comp-filter>
|
||||
</C:filter>
|
||||
</C:calendar-query>
|
||||
"#;
|
||||
@@ -101,6 +97,7 @@ mod tests {
|
||||
prop_filter: vec![PropFilterElement {
|
||||
name: "ATTENDEE".to_owned(),
|
||||
text_match: Some(TextMatchElement {
|
||||
match_type: MatchType::Contains,
|
||||
collation: TextCollation::AsciiCasemap,
|
||||
negate_condition: NegateCondition(false),
|
||||
needle: "mailto:lisa@example.com".to_string()
|
||||
@@ -110,6 +107,7 @@ mod tests {
|
||||
is_not_defined: None,
|
||||
name: "PARTSTAT".to_owned(),
|
||||
text_match: Some(TextMatchElement {
|
||||
match_type: MatchType::Contains,
|
||||
collation: TextCollation::AsciiCasemap,
|
||||
negate_condition: NegateCondition(false),
|
||||
needle: "NEEDS-ACTION".to_string()
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use ical::{
|
||||
generator::{IcalCalendar, IcalEvent},
|
||||
parser::{
|
||||
Component,
|
||||
ical::component::{IcalJournal, IcalTimeZone, IcalTodo},
|
||||
},
|
||||
property::Property,
|
||||
};
|
||||
use rustical_ical::{CalDateTime, CalendarObject, CalendarObjectComponent, UtcDateTime};
|
||||
use super::{ParamFilterElement, TimeRangeElement};
|
||||
use ical::{property::ContentLine, types::CalDateTime};
|
||||
use rustical_dav::xml::TextMatchElement;
|
||||
use rustical_ical::UtcDateTime;
|
||||
use rustical_xml::XmlDeserialize;
|
||||
|
||||
use crate::calendar::methods::report::calendar_query::{
|
||||
ParamFilterElement, TextMatchElement, TimeRangeElement,
|
||||
};
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.2
|
||||
@@ -32,22 +21,16 @@ pub struct PropFilterElement {
|
||||
pub(crate) name: String,
|
||||
}
|
||||
|
||||
impl PropFilterElement {
|
||||
pub fn match_component(&self, comp: &impl PropFilterable) -> bool {
|
||||
let property = comp.get_property(&self.name);
|
||||
let property = match (self.is_not_defined.is_some(), property) {
|
||||
// We are the component that's not supposed to be defined
|
||||
(true, Some(_))
|
||||
// We don't match
|
||||
| (false, None) => return false,
|
||||
// We shall not be and indeed we aren't
|
||||
(true, None) => return true,
|
||||
(false, Some(property)) => property
|
||||
};
|
||||
pub trait PropFilterable {
|
||||
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine>;
|
||||
}
|
||||
|
||||
impl PropFilterElement {
|
||||
#[must_use]
|
||||
pub fn match_property(&self, property: &ContentLine) -> bool {
|
||||
if let Some(TimeRangeElement { start, end }) = &self.time_range {
|
||||
// TODO: Respect timezones
|
||||
let Ok(timestamp) = CalDateTime::parse_prop(property, &HashMap::default()) else {
|
||||
let Ok(timestamp) = CalDateTime::parse_prop(property, None) else {
|
||||
return false;
|
||||
};
|
||||
let timestamp = timestamp.utc();
|
||||
@@ -70,58 +53,25 @@ impl PropFilterElement {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO: param-filter
|
||||
if !self
|
||||
.param_filter
|
||||
.iter()
|
||||
.all(|param_filter| param_filter.match_property(property))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub trait PropFilterable {
|
||||
fn get_property(&self, name: &str) -> Option<&Property>;
|
||||
}
|
||||
|
||||
impl PropFilterable for CalendarObject {
|
||||
fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
Self::get_property(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalEvent {
|
||||
fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
Component::get_property(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalTodo {
|
||||
fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
Component::get_property(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalJournal {
|
||||
fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
Component::get_property(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalCalendar {
|
||||
fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
Component::get_property(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for IcalTimeZone {
|
||||
fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
Component::get_property(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
impl PropFilterable for CalendarObjectComponent {
|
||||
fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
match self {
|
||||
Self::Event(event, _) => PropFilterable::get_property(&event.event, name),
|
||||
Self::Todo(todo, _) => PropFilterable::get_property(todo, name),
|
||||
Self::Journal(journal, _) => PropFilterable::get_property(journal, name),
|
||||
pub fn match_component(&self, comp: &impl PropFilterable) -> bool {
|
||||
let mut properties = comp.get_named_properties(&self.name);
|
||||
if self.is_not_defined.is_some() {
|
||||
return properties.next().is_none();
|
||||
}
|
||||
|
||||
// The filter matches when one property instance matches
|
||||
// Example where this matters: We have multiple attendees and want to match one
|
||||
properties.any(|prop| self.match_property(prop))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
use super::FilterElement;
|
||||
use rstest::rstest;
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_xml::XmlDocument;
|
||||
|
||||
const ICS_1: &str = r"BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Example Corp.//CalDAV Client//EN
|
||||
BEGIN:VTIMEZONE
|
||||
LAST-MODIFIED:20040110T032845Z
|
||||
TZID:US/Eastern
|
||||
BEGIN:DAYLIGHT
|
||||
DTSTART:20000404T020000
|
||||
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4
|
||||
TZNAME:EDT
|
||||
TZOFFSETFROM:-0500
|
||||
TZOFFSETTO:-0400
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
DTSTART:20001026T020000
|
||||
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
|
||||
TZNAME:EST
|
||||
TZOFFSETFROM:-0400
|
||||
TZOFFSETTO:-0500
|
||||
END:STANDARD
|
||||
END:VTIMEZONE
|
||||
BEGIN:VEVENT
|
||||
ATTENDEE;PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:cyrus@example.com
|
||||
ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:lisa@example.com
|
||||
DTSTAMP:20060206T001220Z
|
||||
DTSTART;TZID=US/Eastern:20060104T100000
|
||||
DURATION:PT1H
|
||||
LAST-MODIFIED:20060206T001330Z
|
||||
ORGANIZER:mailto:cyrus@example.com
|
||||
SEQUENCE:1
|
||||
STATUS:TENTATIVE
|
||||
SUMMARY:Event #3
|
||||
UID:DC6C50A017428C5216A2F1CD@example.com
|
||||
X-ABC-GUID:E1CX5Dr-0007ym-Hz@example.com
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
";
|
||||
|
||||
const FILTER_1: &str = r#"
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<C:filter xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<C:comp-filter name="VCALENDAR">
|
||||
<C:comp-filter name="VEVENT">
|
||||
<C:prop-filter name="ATTENDEE">
|
||||
<C:text-match collation="i;ascii-casemap">mailto:lisa@example.com</C:text-match>
|
||||
<C:param-filter name="PARTSTAT">
|
||||
<C:text-match collation="i;ascii-casemap">NEEDS-ACTION</C:text-match>
|
||||
</C:param-filter>
|
||||
</C:prop-filter>
|
||||
</C:comp-filter>
|
||||
</C:comp-filter>
|
||||
</C:filter>
|
||||
"#;
|
||||
|
||||
const FILTER_2: &str = r#"
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<C:filter xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<C:comp-filter name="VCALENDAR">
|
||||
<C:comp-filter name="VEVENT">
|
||||
<C:prop-filter name="ATTENDEE">
|
||||
<C:text-match collation="i;ascii-casemap">mailto:lisa@example.com</C:text-match>
|
||||
<C:param-filter name="PARTSTAT">
|
||||
<C:text-match collation="i;ascii-casemap">ACCEPTED</C:text-match>
|
||||
</C:param-filter>
|
||||
</C:prop-filter>
|
||||
</C:comp-filter>
|
||||
</C:comp-filter>
|
||||
</C:filter>
|
||||
"#;
|
||||
|
||||
#[rstest]
|
||||
#[case(ICS_1, FILTER_1, true)]
|
||||
#[case(ICS_1, FILTER_2, false)]
|
||||
fn yeet(#[case] ics: &str, #[case] filter: &str, #[case] matches: bool) {
|
||||
let obj = CalendarObject::from_ics(ics.to_owned()).unwrap();
|
||||
let filter = FilterElement::parse_str(filter).unwrap();
|
||||
assert_eq!(matches, filter.matches(obj.get_inner()));
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
use ical::property::Property;
|
||||
use rustical_xml::{ValueDeserialize, XmlDeserialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub enum TextCollation {
|
||||
#[default]
|
||||
AsciiCasemap,
|
||||
Octet,
|
||||
}
|
||||
|
||||
impl TextCollation {
|
||||
// Check whether a haystack contains a needle respecting the collation
|
||||
#[must_use]
|
||||
pub fn match_text(&self, needle: &str, haystack: &str) -> bool {
|
||||
match self {
|
||||
// https://datatracker.ietf.org/doc/html/rfc4790#section-9.2
|
||||
Self::AsciiCasemap => haystack
|
||||
.to_ascii_uppercase()
|
||||
.contains(&needle.to_ascii_uppercase()),
|
||||
Self::Octet => haystack.contains(needle),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for TextCollation {
|
||||
fn as_ref(&self) -> &str {
|
||||
match self {
|
||||
Self::AsciiCasemap => "i;ascii-casemap",
|
||||
Self::Octet => "i;octet",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ValueDeserialize for TextCollation {
|
||||
fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
|
||||
match val {
|
||||
"i;ascii-casemap" => Ok(Self::AsciiCasemap),
|
||||
"i;octet" => Ok(Self::Octet),
|
||||
_ => Err(rustical_xml::XmlError::InvalidVariant(format!(
|
||||
"Invalid collation: {val}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub struct NegateCondition(pub bool);
|
||||
|
||||
impl ValueDeserialize for NegateCondition {
|
||||
fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
|
||||
match val {
|
||||
"yes" => Ok(Self(true)),
|
||||
"no" => Ok(Self(false)),
|
||||
_ => Err(rustical_xml::XmlError::InvalidVariant(format!(
|
||||
"Invalid negate-condition parameter: {val}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
pub struct TextMatchElement {
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
pub collation: TextCollation,
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
pub(crate) negate_condition: NegateCondition,
|
||||
#[xml(ty = "text")]
|
||||
pub(crate) needle: String,
|
||||
}
|
||||
|
||||
impl TextMatchElement {
|
||||
#[must_use]
|
||||
pub fn match_property(&self, property: &Property) -> bool {
|
||||
let Self {
|
||||
collation,
|
||||
negate_condition,
|
||||
needle,
|
||||
} = self;
|
||||
|
||||
let matches = property
|
||||
.value
|
||||
.as_ref()
|
||||
.is_some_and(|haystack| collation.match_text(needle, haystack));
|
||||
|
||||
// XOR
|
||||
negate_condition.0 ^ matches
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::calendar::methods::report::calendar_query::text_match::TextCollation;
|
||||
|
||||
#[test]
|
||||
fn test_collation() {
|
||||
assert!(TextCollation::AsciiCasemap.match_text("GrüN", "grün"));
|
||||
assert!(!TextCollation::AsciiCasemap.match_text("GrÜN", "grün"));
|
||||
assert!(!TextCollation::Octet.match_text("GrÜN", "grün"));
|
||||
assert!(TextCollation::Octet.match_text("hallo", "hallo"));
|
||||
assert!(TextCollation::AsciiCasemap.match_text("HaLlo", "hAllo"));
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,7 @@ impl ReportRequest {
|
||||
}
|
||||
|
||||
fn objects_response(
|
||||
objects: Vec<CalendarObject>,
|
||||
objects: Vec<(String, CalendarObject)>,
|
||||
not_found: Vec<String>,
|
||||
path: &str,
|
||||
principal: &str,
|
||||
@@ -60,11 +60,12 @@ fn objects_response(
|
||||
prop: &PropfindType<CalendarObjectPropWrapperName>,
|
||||
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
|
||||
let mut responses = Vec::new();
|
||||
for object in objects {
|
||||
let path = format!("{}/{}.ics", path, object.get_id());
|
||||
for (object_id, object) in objects {
|
||||
let path = format!("{path}/{object_id}.ics");
|
||||
responses.push(
|
||||
CalendarObjectResource {
|
||||
object,
|
||||
object_id,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, prop, None, puri, user)?,
|
||||
@@ -174,7 +175,7 @@ mod tests {
|
||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
||||
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::Getetag),
|
||||
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::CalendarData(
|
||||
CalendarData { comp: None, expand: Some(ExpandElement {
|
||||
CalendarData { comp: None, prop: None, expand: Some(ExpandElement {
|
||||
start: <UtcDateTime as ValueDeserialize>::deserialize("20250426T220000Z").unwrap(),
|
||||
end: <UtcDateTime as ValueDeserialize>::deserialize("20250503T220000Z").unwrap(),
|
||||
}), limit_recurrence_set: None, limit_freebusy_set: None }
|
||||
|
||||
@@ -32,11 +32,12 @@ pub async fn handle_sync_collection<C: CalendarStore>(
|
||||
.await?;
|
||||
|
||||
let mut responses = Vec::new();
|
||||
for object in new_objects {
|
||||
let path = format!("{}/{}.ics", path, object.get_id());
|
||||
for (object_id, object) in new_objects {
|
||||
let path = format!("{}/{}.ics", path, &object_id);
|
||||
responses.push(
|
||||
CalendarObjectResource {
|
||||
object,
|
||||
object_id,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use derive_more::derive::{From, Into};
|
||||
use rustical_dav::xml::TextCollation;
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use strum_macros::VariantArray;
|
||||
|
||||
use crate::calendar::methods::report::calendar_query::text_match::TextCollation;
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq, From, Into)]
|
||||
pub struct SupportedCalendarComponent {
|
||||
#[xml(ty = "attr")]
|
||||
@@ -55,6 +54,7 @@ impl Default for SupportedCollationSet {
|
||||
fn default() -> Self {
|
||||
Self(vec![
|
||||
SupportedCollation(TextCollation::AsciiCasemap),
|
||||
SupportedCollation(TextCollation::UnicodeCasemap),
|
||||
SupportedCollation(TextCollation::Octet),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::calendar::prop::{ReportMethod, SupportedCollationSet};
|
||||
use chrono::{DateTime, Utc};
|
||||
use derive_more::derive::{From, Into};
|
||||
use ical::IcalParser;
|
||||
use ical::types::CalDateTime;
|
||||
use rustical_dav::extensions::{
|
||||
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
|
||||
};
|
||||
@@ -11,12 +12,12 @@ use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner, SupportedReportSet};
|
||||
use rustical_dav_push::{DavPushExtension, DavPushExtensionProp};
|
||||
use rustical_ical::CalDateTime;
|
||||
use rustical_store::Calendar;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_xml::{EnumVariants, PropName};
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use serde::Deserialize;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "CalendarPropName")]
|
||||
@@ -41,7 +42,7 @@ pub enum CalendarProp {
|
||||
SupportedCalendarData(SupportedCalendarData),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
||||
SupportedCollationSet(SupportedCollationSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
MaxResourceSize(i64),
|
||||
#[xml(skip_deserializing)]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
@@ -72,8 +73,8 @@ pub struct CalendarResource {
|
||||
}
|
||||
|
||||
impl ResourceName for CalendarResource {
|
||||
fn get_name(&self) -> String {
|
||||
self.cal.id.clone()
|
||||
fn get_name(&self) -> Cow<'_, str> {
|
||||
Cow::from(&self.cal.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +202,7 @@ impl Resource for CalendarResource {
|
||||
CalendarProp::CalendarTimezone(timezone) => {
|
||||
if let Some(tz) = timezone {
|
||||
// TODO: Proper error (calendar-timezone precondition)
|
||||
let calendar = IcalParser::new(tz.as_bytes())
|
||||
let calendar = IcalParser::from_slice(tz.as_bytes())
|
||||
.next()
|
||||
.ok_or_else(|| {
|
||||
rustical_dav::Error::BadRequest(
|
||||
@@ -214,13 +215,13 @@ impl Resource for CalendarResource {
|
||||
)
|
||||
})?;
|
||||
|
||||
let timezone = calendar.timezones.first().ok_or_else(|| {
|
||||
let timezone = calendar.vtimezones.values().next().ok_or_else(|| {
|
||||
rustical_dav::Error::BadRequest("No timezone data provided".to_owned())
|
||||
})?;
|
||||
let timezone: chrono_tz::Tz = timezone.try_into().map_err(|_| {
|
||||
let timezone: Option<chrono_tz::Tz> = timezone.into();
|
||||
let timezone = timezone.ok_or_else(|| {
|
||||
rustical_dav::Error::BadRequest("No timezone data provided".to_owned())
|
||||
})?;
|
||||
|
||||
self.cal.timezone_id = Some(timezone.name().to_owned());
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -78,8 +78,9 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
|
||||
.get_objects(principal, cal_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|object| CalendarObjectResource {
|
||||
.map(|(object_id, object)| CalendarObjectResource {
|
||||
object,
|
||||
object_id,
|
||||
principal: principal.to_owned(),
|
||||
})
|
||||
.collect())
|
||||
@@ -91,7 +92,7 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
|
||||
file: Self::Resource,
|
||||
) -> Result<(), Self::Error> {
|
||||
self.cal_store
|
||||
.update_calendar(principal.to_owned(), cal_id.to_owned(), file.into())
|
||||
.update_calendar(principal, cal_id, file.into())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
---
|
||||
source: crates/caldav/src/calendar/tests.rs
|
||||
expression: output
|
||||
---
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<response xmlns="DAV:">
|
||||
<href>/caldav/principal/user/calendar/</href>
|
||||
<propstat>
|
||||
<prop xmlns="DAV:">
|
||||
<calendar-timezone xmlns="urn:ietf:params:xml:ns:caldav">BEGIN:VCALENDAR
|
||||
PRODID:-//github.com/lennart-k/vzic-rs//RustiCal Calendar server//EN
|
||||
VERSION:2.0
|
||||
BEGIN:VTIMEZONE
|
||||
TZID:Europe/Berlin
|
||||
LAST-MODIFIED:20250723T190331Z
|
||||
X-LIC-LOCATION:Europe/Berlin
|
||||
X-PROLEPTIC-TZNAME:LMT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+005328
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:18930401T000000
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19160430T230000
|
||||
RDATE:19400401T020000
|
||||
RDATE:19430329T020000
|
||||
RDATE:19460414T020000
|
||||
RDATE:19470406T030000
|
||||
RDATE:19480418T020000
|
||||
RDATE:19490410T020000
|
||||
RDATE:19800406T020000
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19161001T010000
|
||||
RDATE:19421102T030000
|
||||
RDATE:19431004T030000
|
||||
RDATE:19441002T030000
|
||||
RDATE:19451118T030000
|
||||
RDATE:19461007T030000
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19170416T020000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=3MO;UNTIL=19180415T010000Z
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19170917T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=3MO;UNTIL=19180916T010000Z
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19440403T020000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1MO;UNTIL=19450402T010000Z
|
||||
END:DAYLIGHT
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEMT
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0300
|
||||
DTSTART:19450524T020000
|
||||
RDATE:19470511T030000
|
||||
END:DAYLIGHT
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0300
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19450924T030000
|
||||
RDATE:19470629T030000
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19460101T000000
|
||||
RDATE:19800101T000000
|
||||
END:STANDARD
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19471005T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=1SU;UNTIL=19491002T010000Z
|
||||
END:STANDARD
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19800928T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=-1SU;UNTIL=19950924T010000Z
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19810329T020000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19961027T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
|
||||
END:STANDARD
|
||||
END:VTIMEZONE
|
||||
END:VCALENDAR
|
||||
</calendar-timezone>
|
||||
<timezone-service-set xmlns="urn:ietf:params:xml:ns:caldav">
|
||||
<href xmlns="DAV:">https://www.iana.org/time-zones</href>
|
||||
</timezone-service-set>
|
||||
<calendar-timezone-id xmlns="urn:ietf:params:xml:ns:caldav">Europe/Berlin</calendar-timezone-id>
|
||||
<calendar-order xmlns="http://apple.com/ns/ical/">0</calendar-order>
|
||||
<supported-calendar-component-set xmlns="urn:ietf:params:xml:ns:caldav">
|
||||
<comp xmlns="urn:ietf:params:xml:ns:caldav" name="VEVENT"/>
|
||||
<comp xmlns="urn:ietf:params:xml:ns:caldav" name="VTODO"/>
|
||||
</supported-calendar-component-set>
|
||||
<supported-calendar-data xmlns="urn:ietf:params:xml:ns:caldav">
|
||||
<calendar-data xmlns="urn:ietf:params:xml:ns:caldav" content-type="text/calendar" version="2.0"/>
|
||||
</supported-calendar-data>
|
||||
<supported-collation-set xmlns="urn:ietf:params:xml:ns:caldav">
|
||||
<supported-collation xmlns="urn:ietf:params:xml:ns:caldav">i;ascii-casemap</supported-collation>
|
||||
<supported-collation xmlns="urn:ietf:params:xml:ns:caldav">i;unicode-casemap</supported-collation>
|
||||
<supported-collation xmlns="urn:ietf:params:xml:ns:caldav">i;octet</supported-collation>
|
||||
</supported-collation-set>
|
||||
<max-resource-size xmlns="urn:ietf:params:xml:ns:caldav">10000000</max-resource-size>
|
||||
<supported-report-set xmlns="DAV:">
|
||||
<supported-report xmlns="DAV:">
|
||||
<report xmlns="DAV:">
|
||||
<calendar-query xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
</report>
|
||||
</supported-report>
|
||||
<supported-report xmlns="DAV:">
|
||||
<report xmlns="DAV:">
|
||||
<calendar-multiget xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
</report>
|
||||
</supported-report>
|
||||
<supported-report xmlns="DAV:">
|
||||
<report xmlns="DAV:">
|
||||
<sync-collection xmlns="DAV:"/>
|
||||
</report>
|
||||
</supported-report>
|
||||
</supported-report-set>
|
||||
<min-date-time xmlns="urn:ietf:params:xml:ns:caldav">-2621430101T000000Z</min-date-time>
|
||||
<max-date-time xmlns="urn:ietf:params:xml:ns:caldav">+2621421231T235959Z</max-date-time>
|
||||
<sync-token xmlns="DAV:">github.com/lennart-k/rustical/ns/12</sync-token>
|
||||
<getctag xmlns="http://calendarserver.org/ns/">github.com/lennart-k/rustical/ns/12</getctag>
|
||||
<transports xmlns="https://bitfire.at/webdav-push">
|
||||
<web-push xmlns="https://bitfire.at/webdav-push"/>
|
||||
</transports>
|
||||
<topic xmlns="https://bitfire.at/webdav-push">b28b41e9-8801-4fc5-ae29-8efb5fadeb36</topic>
|
||||
<supported-triggers xmlns="https://bitfire.at/webdav-push">
|
||||
<content-update xmlns="https://bitfire.at/webdav-push">
|
||||
<depth xmlns="DAV:">1</depth>
|
||||
</content-update>
|
||||
<property-update xmlns="https://bitfire.at/webdav-push">
|
||||
<depth xmlns="DAV:">1</depth>
|
||||
</property-update>
|
||||
</supported-triggers>
|
||||
<resourcetype xmlns="DAV:">
|
||||
<collection xmlns="DAV:"/>
|
||||
<calendar xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
</resourcetype>
|
||||
<displayname xmlns="DAV:">Calendar</displayname>
|
||||
<current-user-principal xmlns="DAV:">
|
||||
<href xmlns="DAV:">/caldav/principal/user/</href>
|
||||
</current-user-principal>
|
||||
<current-user-privilege-set xmlns="DAV:">
|
||||
<privilege>
|
||||
<read/>
|
||||
</privilege>
|
||||
<privilege>
|
||||
<write-properties/>
|
||||
</privilege>
|
||||
<privilege>
|
||||
<read-acl/>
|
||||
</privilege>
|
||||
<privilege>
|
||||
<read-current-user-privilege-set/>
|
||||
</privilege>
|
||||
</current-user-privilege-set>
|
||||
<owner xmlns="DAV:">
|
||||
<href xmlns="DAV:">/caldav/principal/user/</href>
|
||||
</owner>
|
||||
</prop>
|
||||
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
|
||||
</propstat>
|
||||
</response>
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
source: crates/caldav/src/calendar/tests.rs
|
||||
expression: output
|
||||
---
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<response xmlns="DAV:">
|
||||
<href>/caldav/principal/user/calendar/</href>
|
||||
<propstat>
|
||||
<prop xmlns="DAV:">
|
||||
<calendar-color xmlns="http://apple.com/ns/ical/"/>
|
||||
<calendar-description xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<calendar-timezone xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<timezone-service-set xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<calendar-timezone-id xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<calendar-order xmlns="http://apple.com/ns/ical/"/>
|
||||
<supported-calendar-component-set xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<supported-calendar-data xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<supported-collation-set xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<max-resource-size xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<supported-report-set xmlns="DAV:"/>
|
||||
<source xmlns="http://calendarserver.org/ns/"/>
|
||||
<min-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<max-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<sync-token xmlns="DAV:"/>
|
||||
<getctag xmlns="http://calendarserver.org/ns/"/>
|
||||
<transports xmlns="https://bitfire.at/webdav-push"/>
|
||||
<topic xmlns="https://bitfire.at/webdav-push"/>
|
||||
<supported-triggers xmlns="https://bitfire.at/webdav-push"/>
|
||||
<resourcetype xmlns="DAV:"/>
|
||||
<displayname xmlns="DAV:"/>
|
||||
<current-user-principal xmlns="DAV:"/>
|
||||
<current-user-privilege-set xmlns="DAV:"/>
|
||||
<owner xmlns="DAV:"/>
|
||||
</prop>
|
||||
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
|
||||
</propstat>
|
||||
</response>
|
||||
@@ -1,230 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<response xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CARD="urn:ietf:params:xml:ns:carddav" xmlns:CS="http://calendarserver.org/ns/" xmlns:PUSH="https://bitfire.at/webdav-push">
|
||||
<href>/caldav/principal/user/calendar/</href>
|
||||
<propstat>
|
||||
<prop>
|
||||
<calendar-color xmlns="http://apple.com/ns/ical/"/>
|
||||
<calendar-description xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<calendar-timezone xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<timezone-service-set xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<calendar-timezone-id xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<calendar-order xmlns="http://apple.com/ns/ical/"/>
|
||||
<supported-calendar-component-set xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<supported-calendar-data xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<supported-collation-set xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<max-resource-size xmlns="DAV:"/>
|
||||
<supported-report-set xmlns="DAV:"/>
|
||||
<source xmlns="http://calendarserver.org/ns/"/>
|
||||
<min-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<max-date-time xmlns="urn:ietf:params:xml:ns:caldav"/>
|
||||
<sync-token xmlns="DAV:"/>
|
||||
<getctag xmlns="http://calendarserver.org/ns/"/>
|
||||
<transports xmlns="https://bitfire.at/webdav-push"/>
|
||||
<topic xmlns="https://bitfire.at/webdav-push"/>
|
||||
<supported-triggers xmlns="https://bitfire.at/webdav-push"/>
|
||||
<resourcetype xmlns="DAV:"/>
|
||||
<displayname xmlns="DAV:"/>
|
||||
<current-user-principal xmlns="DAV:"/>
|
||||
<current-user-privilege-set xmlns="DAV:"/>
|
||||
<owner xmlns="DAV:"/>
|
||||
</prop>
|
||||
<status>HTTP/1.1 200 OK</status>
|
||||
</propstat>
|
||||
</response>
|
||||
|
||||
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<response xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CARD="urn:ietf:params:xml:ns:carddav" xmlns:CS="http://calendarserver.org/ns/" xmlns:PUSH="https://bitfire.at/webdav-push">
|
||||
<href>/caldav/principal/user/calendar/</href>
|
||||
<propstat>
|
||||
<prop>
|
||||
<CAL:calendar-timezone>BEGIN:VCALENDAR
|
||||
PRODID:-//github.com/lennart-k/vzic-rs//RustiCal Calendar server//EN
|
||||
VERSION:2.0
|
||||
BEGIN:VTIMEZONE
|
||||
TZID:Europe/Berlin
|
||||
LAST-MODIFIED:20250723T190331Z
|
||||
X-LIC-LOCATION:Europe/Berlin
|
||||
X-PROLEPTIC-TZNAME:LMT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+005328
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:18930401T000000
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19160430T230000
|
||||
RDATE:19400401T020000
|
||||
RDATE:19430329T020000
|
||||
RDATE:19460414T020000
|
||||
RDATE:19470406T030000
|
||||
RDATE:19480418T020000
|
||||
RDATE:19490410T020000
|
||||
RDATE:19800406T020000
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19161001T010000
|
||||
RDATE:19421102T030000
|
||||
RDATE:19431004T030000
|
||||
RDATE:19441002T030000
|
||||
RDATE:19451118T030000
|
||||
RDATE:19461007T030000
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19170416T020000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=3MO;UNTIL=19180415T010000Z
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19170917T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=3MO;UNTIL=19180916T010000Z
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19440403T020000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1MO;UNTIL=19450402T010000Z
|
||||
END:DAYLIGHT
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEMT
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0300
|
||||
DTSTART:19450524T020000
|
||||
RDATE:19470511T030000
|
||||
END:DAYLIGHT
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0300
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19450924T030000
|
||||
RDATE:19470629T030000
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19460101T000000
|
||||
RDATE:19800101T000000
|
||||
END:STANDARD
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19471005T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=1SU;UNTIL=19491002T010000Z
|
||||
END:STANDARD
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19800928T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=-1SU;UNTIL=19950924T010000Z
|
||||
END:STANDARD
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19810329T020000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19961027T030000
|
||||
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
|
||||
END:STANDARD
|
||||
END:VTIMEZONE
|
||||
END:VCALENDAR
|
||||
</CAL:calendar-timezone>
|
||||
<CAL:timezone-service-set>
|
||||
<href>https://www.iana.org/time-zones</href>
|
||||
</CAL:timezone-service-set>
|
||||
<CAL:calendar-timezone-id>Europe/Berlin</CAL:calendar-timezone-id>
|
||||
<calendar-order xmlns="http://apple.com/ns/ical/">0</calendar-order>
|
||||
<CAL:supported-calendar-component-set>
|
||||
<CAL:comp name="VEVENT"/>
|
||||
<CAL:comp name="VTODO"/>
|
||||
</CAL:supported-calendar-component-set>
|
||||
<CAL:supported-calendar-data>
|
||||
<CAL:calendar-data content-type="text/calendar" version="2.0"/>
|
||||
</CAL:supported-calendar-data>
|
||||
<CAL:supported-collation-set>
|
||||
<CAL:supported-collation>i;ascii-casemap</CAL:supported-collation>
|
||||
<CAL:supported-collation>i;octet</CAL:supported-collation>
|
||||
</CAL:supported-collation-set>
|
||||
<max-resource-size>10000000</max-resource-size>
|
||||
<supported-report-set>
|
||||
<supported-report>
|
||||
<report>
|
||||
<CAL:calendar-query/>
|
||||
</report>
|
||||
</supported-report>
|
||||
<supported-report>
|
||||
<report>
|
||||
<CAL:calendar-multiget/>
|
||||
</report>
|
||||
</supported-report>
|
||||
<supported-report>
|
||||
<report>
|
||||
<sync-collection/>
|
||||
</report>
|
||||
</supported-report>
|
||||
</supported-report-set>
|
||||
<CAL:min-date-time>-2621430101T000000Z</CAL:min-date-time>
|
||||
<CAL:max-date-time>+2621421231T235959Z</CAL:max-date-time>
|
||||
<sync-token>github.com/lennart-k/rustical/ns/12</sync-token>
|
||||
<CS:getctag>github.com/lennart-k/rustical/ns/12</CS:getctag>
|
||||
<PUSH:transports>
|
||||
<PUSH:web-push/>
|
||||
</PUSH:transports>
|
||||
<PUSH:topic>b28b41e9-8801-4fc5-ae29-8efb5fadeb36</PUSH:topic>
|
||||
<PUSH:supported-triggers>
|
||||
<PUSH:content-update>
|
||||
<depth>1</depth>
|
||||
</PUSH:content-update>
|
||||
<PUSH:property-update>
|
||||
<depth>1</depth>
|
||||
</PUSH:property-update>
|
||||
</PUSH:supported-triggers>
|
||||
<resourcetype>
|
||||
<collection/>
|
||||
<CAL:calendar/>
|
||||
</resourcetype>
|
||||
<displayname>Calendar</displayname>
|
||||
<current-user-principal>
|
||||
<href>/caldav/principal/user/</href>
|
||||
</current-user-principal>
|
||||
<current-user-privilege-set>
|
||||
<privilege>
|
||||
<read/>
|
||||
</privilege>
|
||||
<privilege>
|
||||
<write-properties/>
|
||||
</privilege>
|
||||
<privilege>
|
||||
<read-acl/>
|
||||
</privilege>
|
||||
<privilege>
|
||||
<read-current-user-privilege-set/>
|
||||
</privilege>
|
||||
</current-user-privilege-set>
|
||||
<owner>
|
||||
<href>/caldav/principal/user/</href>
|
||||
</owner>
|
||||
</prop>
|
||||
<status>HTTP/1.1 200 OK</status>
|
||||
</propstat>
|
||||
</response>
|
||||
@@ -14,14 +14,9 @@ async fn test_propfind() {
|
||||
from_str(include_str!("./test_files/propfind.principals.json")).unwrap();
|
||||
let resources: Vec<CalendarResource> =
|
||||
from_str(include_str!("./test_files/propfind.resources.json")).unwrap();
|
||||
let outputs: Vec<_> = include_str!("./test_files/propfind.outputs")
|
||||
.trim()
|
||||
.split("\n\n")
|
||||
.collect();
|
||||
|
||||
for principal in principals {
|
||||
for ((request, resource), &expected_output) in requests.iter().zip(&resources).zip(&outputs)
|
||||
{
|
||||
for (request, resource) in requests.iter().zip(&resources) {
|
||||
let propfind = CalendarResource::parse_propfind(request).unwrap();
|
||||
|
||||
let response = resource
|
||||
@@ -33,13 +28,12 @@ async fn test_propfind() {
|
||||
&principal,
|
||||
)
|
||||
.unwrap();
|
||||
let expected_output = expected_output.trim();
|
||||
let output = response
|
||||
.serialize_to_string()
|
||||
.unwrap()
|
||||
.trim()
|
||||
.replace("\r\n", "\n");
|
||||
similar_asserts::assert_eq!(expected_output, output);
|
||||
insta::assert_snapshot!(output);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::TypedHeader;
|
||||
use headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||
use http::{HeaderMap, Method, StatusCode};
|
||||
use http::{HeaderMap, HeaderValue, Method, StatusCode};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::CalendarStore;
|
||||
use rustical_store::auth::Principal;
|
||||
@@ -42,7 +42,7 @@ pub async fn get_event<C: CalendarStore>(
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ETag::from_str(&event.get_etag()).unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/calendar").unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/calendar; charset=utf-8").unwrap());
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
@@ -73,18 +73,40 @@ pub async fn put_event<C: CalendarStore>(
|
||||
}
|
||||
|
||||
let overwrite = if let Some(TypedHeader(if_none_match)) = if_none_match {
|
||||
if_none_match == IfNoneMatch::any()
|
||||
// TODO: Put into transaction?
|
||||
let existing = match cal_store
|
||||
.get_object(&principal, &calendar_id, &object_id, false)
|
||||
.await
|
||||
{
|
||||
Ok(existing) => Some(existing),
|
||||
Err(rustical_store::Error::NotFound) => None,
|
||||
Err(err) => Err(err)?,
|
||||
};
|
||||
existing.is_none_or(|existing| {
|
||||
if_none_match.precondition_passes(
|
||||
&existing
|
||||
.get_etag()
|
||||
.parse()
|
||||
.expect("We only generate valid ETags"),
|
||||
)
|
||||
})
|
||||
} else {
|
||||
true
|
||||
};
|
||||
|
||||
let Ok(object) = CalendarObject::from_ics(body.clone(), Some(object_id)) else {
|
||||
let Ok(object) = CalendarObject::from_ics(body.clone()) else {
|
||||
debug!("invalid calendar data:\n{body}");
|
||||
return Err(Error::PreconditionFailed(Precondition::ValidCalendarData));
|
||||
};
|
||||
let etag = object.get_etag();
|
||||
cal_store
|
||||
.put_object(principal, calendar_id, object, overwrite)
|
||||
.put_object(&principal, &calendar_id, &object_id, object, overwrite)
|
||||
.await?;
|
||||
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"ETag",
|
||||
HeaderValue::from_str(&etag).expect("Contains no invalid characters"),
|
||||
);
|
||||
Ok((StatusCode::CREATED, headers).into_response())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use rustical_dav::extensions::CommonPropertiesProp;
|
||||
use rustical_ical::UtcDateTime;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
use rustical_xml::{EnumVariants, PropName, Unparsed, XmlDeserialize, XmlSerialize};
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Eq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "CalendarObjectPropName")]
|
||||
@@ -35,7 +35,9 @@ pub struct ExpandElement {
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Default, Eq, Hash)]
|
||||
pub struct CalendarData {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
pub(crate) comp: Option<()>,
|
||||
pub(crate) comp: Option<Unparsed>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
pub(crate) prop: Option<Unparsed>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
pub(crate) expand: Option<ExpandElement>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::prop::{
|
||||
};
|
||||
use crate::Error;
|
||||
use derive_more::derive::{From, Into};
|
||||
use ical::generator::Emitter;
|
||||
use rustical_dav::{
|
||||
extensions::CommonPropertiesExtension,
|
||||
privileges::UserPrivilegeSet,
|
||||
@@ -12,16 +13,18 @@ use rustical_dav::{
|
||||
};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::auth::Principal;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, From, Into)]
|
||||
pub struct CalendarObjectResource {
|
||||
pub object: CalendarObject,
|
||||
pub object_id: String,
|
||||
pub principal: String,
|
||||
}
|
||||
|
||||
impl ResourceName for CalendarObjectResource {
|
||||
fn get_name(&self) -> String {
|
||||
format!("{}.ics", self.object.get_id())
|
||||
fn get_name(&self) -> Cow<'_, str> {
|
||||
Cow::from(format!("{}.ics", self.object_id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,14 +54,18 @@ impl Resource for CalendarObjectResource {
|
||||
CalendarObjectProp::Getetag(self.object.get_etag())
|
||||
}
|
||||
CalendarObjectPropName::CalendarData(CalendarData { expand, .. }) => {
|
||||
CalendarObjectProp::CalendarData(if let Some(expand) = expand.as_ref() {
|
||||
self.object.expand_recurrence(
|
||||
Some(expand.start.to_utc()),
|
||||
Some(expand.end.to_utc()),
|
||||
)?
|
||||
} else {
|
||||
self.object.get_ics().to_owned()
|
||||
})
|
||||
CalendarObjectProp::CalendarData(expand.as_ref().map_or_else(
|
||||
|| self.object.get_ics().to_owned(),
|
||||
|expand| {
|
||||
self.object
|
||||
.get_inner()
|
||||
.expand_recurrence(
|
||||
Some(expand.start.to_utc()),
|
||||
Some(expand.end.to_utc()),
|
||||
)
|
||||
.generate()
|
||||
},
|
||||
))
|
||||
}
|
||||
CalendarObjectPropName::Getcontenttype => {
|
||||
CalendarObjectProp::Getcontenttype("text/calendar;charset=utf-8")
|
||||
|
||||
@@ -66,6 +66,7 @@ impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
|
||||
.await?;
|
||||
Ok(CalendarObjectResource {
|
||||
object,
|
||||
object_id: object_id.to_owned(),
|
||||
principal: principal.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -75,7 +75,8 @@ impl Error {
|
||||
Self::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
|
||||
Self::ChronoParseError(_) | Self::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::NotFound => StatusCode::NOT_FOUND,
|
||||
Self::IcalError(err) => err.status_code(),
|
||||
// TODO: Can also be Bad Request, if it's used input
|
||||
Self::IcalError(_err) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::PreconditionFailed(_err) => StatusCode::PRECONDITION_FAILED,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use rustical_dav::xml::{
|
||||
GroupMemberSet, GroupMembership, Resourcetype, ResourcetypeInner, SupportedReportSet,
|
||||
};
|
||||
use rustical_store::auth::Principal;
|
||||
use std::borrow::Cow;
|
||||
|
||||
mod service;
|
||||
pub use service::*;
|
||||
@@ -23,8 +24,8 @@ pub struct PrincipalResource {
|
||||
}
|
||||
|
||||
impl ResourceName for PrincipalResource {
|
||||
fn get_name(&self) -> String {
|
||||
self.principal.id.clone()
|
||||
fn get_name(&self) -> Cow<'_, str> {
|
||||
Cow::from(&self.principal.id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,51 +3,51 @@ 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">
|
||||
<response xmlns="DAV:">
|
||||
<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>
|
||||
<prop xmlns="DAV:">
|
||||
<calendar-user-type xmlns="urn:ietf:params:xml:ns:caldav">INDIVIDUAL</calendar-user-type>
|
||||
<calendar-user-address-set xmlns="urn:ietf:params:xml:ns:caldav">
|
||||
<href xmlns="DAV:">/caldav/principal/user/</href>
|
||||
</calendar-user-address-set>
|
||||
<principal-URL xmlns="DAV:">
|
||||
<href xmlns="DAV:">/caldav/principal/user/</href>
|
||||
</principal-URL>
|
||||
<group-membership>
|
||||
<href>/caldav/principal/group/</href>
|
||||
<group-membership xmlns="DAV:">
|
||||
<href xmlns="DAV:">/caldav/principal/group/</href>
|
||||
</group-membership>
|
||||
<group-member-set>
|
||||
<group-member-set xmlns="DAV:">
|
||||
</group-member-set>
|
||||
<alternate-URI-set/>
|
||||
<supported-report-set>
|
||||
<supported-report>
|
||||
<report>
|
||||
<principal-match/>
|
||||
<alternate-URI-set xmlns="DAV:"/>
|
||||
<supported-report-set xmlns="DAV:">
|
||||
<supported-report xmlns="DAV:">
|
||||
<report xmlns="DAV:">
|
||||
<principal-match xmlns="DAV:"/>
|
||||
</report>
|
||||
</supported-report>
|
||||
</supported-report-set>
|
||||
<CAL:calendar-home-set>
|
||||
<href>/caldav/principal/group/</href>
|
||||
<href>/caldav/principal/user/</href>
|
||||
</CAL:calendar-home-set>
|
||||
<resourcetype>
|
||||
<collection/>
|
||||
<principal/>
|
||||
<calendar-home-set xmlns="urn:ietf:params:xml:ns:caldav">
|
||||
<href xmlns="DAV:">/caldav/principal/group/</href>
|
||||
<href xmlns="DAV:">/caldav/principal/user/</href>
|
||||
</calendar-home-set>
|
||||
<resourcetype xmlns="DAV:">
|
||||
<collection xmlns="DAV:"/>
|
||||
<principal xmlns="DAV:"/>
|
||||
</resourcetype>
|
||||
<displayname>user</displayname>
|
||||
<current-user-principal>
|
||||
<href>/caldav/principal/user/</href>
|
||||
<displayname xmlns="DAV:">user</displayname>
|
||||
<current-user-principal xmlns="DAV:">
|
||||
<href xmlns="DAV:">/caldav/principal/user/</href>
|
||||
</current-user-principal>
|
||||
<current-user-privilege-set>
|
||||
<current-user-privilege-set xmlns="DAV:">
|
||||
<privilege>
|
||||
<all/>
|
||||
</privilege>
|
||||
</current-user-privilege-set>
|
||||
<owner>
|
||||
<href>/caldav/principal/user/</href>
|
||||
<owner xmlns="DAV:">
|
||||
<href xmlns="DAV:">/caldav/principal/user/</href>
|
||||
</owner>
|
||||
</prop>
|
||||
<status>HTTP/1.1 200 OK</status>
|
||||
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
|
||||
</propstat>
|
||||
</response>
|
||||
|
||||
@@ -5,32 +5,27 @@ use crate::{
|
||||
use rstest::rstest;
|
||||
use rustical_dav::resource::{Resource, ResourceService};
|
||||
use rustical_store::auth::{Principal, PrincipalType::Individual};
|
||||
use rustical_store_sqlite::{
|
||||
SqliteStore,
|
||||
calendar_store::SqliteCalendarStore,
|
||||
principal_store::SqlitePrincipalStore,
|
||||
tests::{get_test_calendar_store, get_test_principal_store, get_test_subscription_store},
|
||||
};
|
||||
use rustical_store_sqlite::tests::{TestStoreContext, test_store_context};
|
||||
use rustical_xml::XmlSerializeRoot;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_principal_resource(
|
||||
#[from(get_test_calendar_store)]
|
||||
#[future]
|
||||
cal_store: SqliteCalendarStore,
|
||||
#[from(get_test_principal_store)]
|
||||
#[future]
|
||||
auth_provider: SqlitePrincipalStore,
|
||||
#[from(get_test_subscription_store)]
|
||||
#[future]
|
||||
sub_store: SqliteStore,
|
||||
#[from(test_store_context)]
|
||||
context: TestStoreContext,
|
||||
) {
|
||||
let TestStoreContext {
|
||||
cal_store,
|
||||
sub_store,
|
||||
principal_store: auth_provider,
|
||||
..
|
||||
} = context.await;
|
||||
let service = PrincipalResourceService {
|
||||
cal_store: Arc::new(cal_store.await),
|
||||
sub_store: Arc::new(sub_store.await),
|
||||
auth_provider: Arc::new(auth_provider.await),
|
||||
cal_store: Arc::new(cal_store),
|
||||
sub_store: Arc::new(sub_store),
|
||||
auth_provider: Arc::new(auth_provider),
|
||||
simplified_home_set: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ base64.workspace = true
|
||||
serde.workspace = true
|
||||
tokio.workspace = true
|
||||
url.workspace = true
|
||||
rustical_dav.workspace = true
|
||||
rustical_dav = { workspace = true, features = ["ical"] }
|
||||
rustical_store.workspace = true
|
||||
chrono.workspace = true
|
||||
rustical_xml.workspace = true
|
||||
@@ -35,6 +35,7 @@ percent-encoding.workspace = true
|
||||
ical.workspace = true
|
||||
strum.workspace = true
|
||||
strum_macros.workspace = true
|
||||
rstest.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
insta.workspace = true
|
||||
|
||||
@@ -7,6 +7,7 @@ use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::TypedHeader;
|
||||
use axum_extra::headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||
use http::HeaderValue;
|
||||
use http::Method;
|
||||
use http::{HeaderMap, StatusCode};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
@@ -50,7 +51,7 @@ pub async fn get_object<AS: AddressbookStore>(
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ETag::from_str(&object.get_etag()).unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/vcard; charset=utf-8").unwrap());
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
@@ -81,15 +82,37 @@ pub async fn put_object<AS: AddressbookStore>(
|
||||
}
|
||||
|
||||
let overwrite = if let Some(TypedHeader(if_none_match)) = if_none_match {
|
||||
if_none_match == IfNoneMatch::any()
|
||||
// TODO: Put into transaction?
|
||||
let existing = match addr_store
|
||||
.get_object(&principal, &addressbook_id, &object_id, false)
|
||||
.await
|
||||
{
|
||||
Ok(existing) => Some(existing),
|
||||
Err(rustical_store::Error::NotFound) => None,
|
||||
Err(err) => Err(err)?,
|
||||
};
|
||||
existing.is_none_or(|existing| {
|
||||
if_none_match.precondition_passes(
|
||||
&existing
|
||||
.get_etag()
|
||||
.parse()
|
||||
.expect("We only generate valid ETags"),
|
||||
)
|
||||
})
|
||||
} else {
|
||||
true
|
||||
};
|
||||
|
||||
let object = AddressObject::from_vcf(object_id, body)?;
|
||||
let object = AddressObject::from_vcf(body)?;
|
||||
let etag = object.get_etag();
|
||||
addr_store
|
||||
.put_object(principal, addressbook_id, object, overwrite)
|
||||
.put_object(&principal, &addressbook_id, &object_id, object, overwrite)
|
||||
.await?;
|
||||
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"ETag",
|
||||
HeaderValue::from_str(&etag).expect("Contains no invalid characters"),
|
||||
);
|
||||
Ok((StatusCode::CREATED, headers).into_response())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::{
|
||||
Error,
|
||||
address_object::{
|
||||
@@ -6,6 +8,7 @@ use crate::{
|
||||
},
|
||||
};
|
||||
use derive_more::derive::{From, Into};
|
||||
use ical::parser::VcardFNProperty;
|
||||
use rustical_dav::{
|
||||
extensions::CommonPropertiesExtension,
|
||||
privileges::UserPrivilegeSet,
|
||||
@@ -19,11 +22,12 @@ use rustical_store::auth::Principal;
|
||||
pub struct AddressObjectResource {
|
||||
pub object: AddressObject,
|
||||
pub principal: String,
|
||||
pub object_id: String,
|
||||
}
|
||||
|
||||
impl ResourceName for AddressObjectResource {
|
||||
fn get_name(&self) -> String {
|
||||
format!("{}.vcf", self.object.get_id())
|
||||
fn get_name(&self) -> Cow<'_, str> {
|
||||
Cow::from(format!("{}.vcf", self.object_id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +71,11 @@ impl Resource for AddressObjectResource {
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
self.object.get_full_name()
|
||||
self.object
|
||||
.get_vcard()
|
||||
.full_name
|
||||
.first()
|
||||
.map(|VcardFNProperty(name, _)| name.as_str())
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
|
||||
@@ -57,6 +57,7 @@ impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS>
|
||||
.await?;
|
||||
Ok(AddressObjectResource {
|
||||
object,
|
||||
object_id: object_id.to_owned(),
|
||||
principal: principal.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ use http::{HeaderValue, Method, StatusCode, header};
|
||||
use percent_encoding::{CONTROLS, utf8_percent_encode};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
use rustical_dav::resource::Resource;
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||
use std::str::FromStr;
|
||||
@@ -40,13 +39,13 @@ pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
let objects = addr_store.get_objects(&principal, &addressbook_id).await?;
|
||||
let vcf = objects
|
||||
.iter()
|
||||
.map(AddressObject::get_vcf)
|
||||
.map(|(_id, obj)| obj.get_vcf())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\r\n");
|
||||
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/vcard; charset=utf-8").unwrap());
|
||||
let filename = format!("{principal}_{addressbook_id}.vcf");
|
||||
let filename = utf8_percent_encode(&filename, CONTROLS);
|
||||
hdrs.insert(
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::io::BufReader;
|
||||
|
||||
use crate::Error;
|
||||
use crate::addressbook::AddressbookResourceService;
|
||||
use axum::{
|
||||
@@ -9,7 +7,7 @@ use axum::{
|
||||
use http::StatusCode;
|
||||
use ical::{
|
||||
parser::{Component, ComponentMut, vcard},
|
||||
property::Property,
|
||||
property::ContentLine,
|
||||
};
|
||||
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use tracing::instrument;
|
||||
@@ -25,7 +23,7 @@ pub async fn route_import<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let parser = vcard::VcardParser::new(BufReader::new(body.as_bytes()));
|
||||
let parser = vcard::VcardParser::from_slice(body.as_bytes());
|
||||
|
||||
let mut objects = vec![];
|
||||
for res in parser {
|
||||
@@ -33,15 +31,16 @@ pub async fn route_import<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
let uid = card.get_uid();
|
||||
if uid.is_none() {
|
||||
let mut card_mut = card.mutable();
|
||||
card_mut.set_property(Property {
|
||||
card_mut.add_content_line(ContentLine {
|
||||
name: "UID".to_owned(),
|
||||
value: Some(uuid::Uuid::new_v4().to_string()),
|
||||
params: vec![],
|
||||
params: vec![].into(),
|
||||
});
|
||||
card = card_mut.verify().unwrap();
|
||||
card = card_mut.build(None).unwrap();
|
||||
}
|
||||
|
||||
objects.push(card.try_into().unwrap());
|
||||
// TODO: Make nicer
|
||||
let uid = card.get_uid().unwrap();
|
||||
objects.push((uid.to_owned(), card.into()));
|
||||
}
|
||||
|
||||
if objects.is_empty() {
|
||||
|
||||
@@ -29,7 +29,7 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
store: &AS,
|
||||
) -> Result<(Vec<AddressObject>, Vec<String>), Error> {
|
||||
) -> Result<(Vec<(String, AddressObject)>, Vec<String>), Error> {
|
||||
let mut result = vec![];
|
||||
let mut not_found = vec![];
|
||||
|
||||
@@ -43,7 +43,7 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
|
||||
.get_object(principal, addressbook_id, object_id, false)
|
||||
.await
|
||||
{
|
||||
Ok(object) => result.push(object),
|
||||
Ok(object) => result.push((object_id.to_owned(), object)),
|
||||
Err(rustical_store::Error::NotFound) => not_found.push(href.to_string()),
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
@@ -74,11 +74,12 @@ pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
|
||||
.await?;
|
||||
|
||||
let mut responses = Vec::new();
|
||||
for object in objects {
|
||||
let path = format!("{}/{}.vcf", path, object.get_id());
|
||||
for (object_id, object) in objects {
|
||||
let path = format!("{path}/{object_id}.vcf");
|
||||
responses.push(
|
||||
AddressObjectResource {
|
||||
object,
|
||||
object_id,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, prop, None, puri, user)?,
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
use crate::{
|
||||
address_object::AddressObjectPropWrapperName,
|
||||
addressbook::methods::report::addressbook_query::PropFilterElement,
|
||||
};
|
||||
use derive_more::{From, Into};
|
||||
use ical::property::ContentLine;
|
||||
use rustical_dav::xml::{PropfindType, TextMatchElement};
|
||||
use rustical_ical::{AddressObject, UtcDateTime};
|
||||
use rustical_xml::{ValueDeserialize, XmlDeserialize, XmlRootTag};
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
pub struct TimeRangeElement {
|
||||
#[xml(ty = "attr")]
|
||||
pub(crate) start: Option<UtcDateTime>,
|
||||
#[xml(ty = "attr")]
|
||||
pub(crate) end: Option<UtcDateTime>,
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
// https://www.rfc-editor.org/rfc/rfc4791#section-9.7.3
|
||||
pub struct ParamFilterElement {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
pub(crate) is_not_defined: Option<()>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
pub(crate) text_match: Option<TextMatchElement>,
|
||||
|
||||
#[xml(ty = "attr")]
|
||||
pub(crate) name: String,
|
||||
}
|
||||
|
||||
impl ParamFilterElement {
|
||||
#[must_use]
|
||||
pub fn match_property(&self, prop: &ContentLine) -> bool {
|
||||
let Some(param) = prop.params.get_param(&self.name) else {
|
||||
return self.is_not_defined.is_some();
|
||||
};
|
||||
if self.is_not_defined.is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(text_match) = self.text_match.as_ref() else {
|
||||
return true;
|
||||
};
|
||||
text_match.match_text(param)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default, From, Into)]
|
||||
pub struct Allof(pub bool);
|
||||
|
||||
impl ValueDeserialize for Allof {
|
||||
fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
|
||||
Ok(Self(match val {
|
||||
"allof" => true,
|
||||
"anyof" => false,
|
||||
_ => {
|
||||
return Err(rustical_xml::XmlError::InvalidVariant(format!(
|
||||
"Invalid test parameter: {val}"
|
||||
)));
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// <!ELEMENT filter (prop-filter*)>
|
||||
// <!ATTLIST filter test (anyof | allof) "anyof">
|
||||
// <!-- test value:
|
||||
// anyof logical OR for prop-filter matches
|
||||
// allof logical AND for prop-filter matches -->
|
||||
#[derive(XmlDeserialize, XmlRootTag, Clone, Debug, PartialEq, Eq)]
|
||||
#[xml(root = "filter", ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
#[allow(dead_code)]
|
||||
pub struct FilterElement {
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
pub test: Allof,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
|
||||
pub(crate) prop_filter: Vec<PropFilterElement>,
|
||||
}
|
||||
|
||||
impl FilterElement {
|
||||
#[must_use]
|
||||
pub fn matches(&self, addr_object: &AddressObject) -> bool {
|
||||
if self.prop_filter.is_empty() {
|
||||
// Filter empty
|
||||
return true;
|
||||
}
|
||||
|
||||
let Allof(allof) = self.test;
|
||||
let mut results = self
|
||||
.prop_filter
|
||||
.iter()
|
||||
.map(|prop_filter| prop_filter.match_component(addr_object));
|
||||
if allof {
|
||||
results.all(|x| x)
|
||||
} else {
|
||||
results.any(|x| x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
// <!ELEMENT addressbook-query ((DAV:allprop |
|
||||
// DAV:propname |
|
||||
// DAV:prop)?, filter, limit?)>
|
||||
pub struct AddressbookQueryRequest {
|
||||
#[xml(ty = "untagged")]
|
||||
pub prop: PropfindType<AddressObjectPropWrapperName>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
pub(crate) filter: FilterElement,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
pub(crate) limit: Option<LimitElement>,
|
||||
}
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/rfc5323#section-5.17
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LimitElement {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
pub nresults: NresultsElement,
|
||||
}
|
||||
|
||||
impl From<u64> for LimitElement {
|
||||
fn from(value: u64) -> Self {
|
||||
Self {
|
||||
nresults: NresultsElement(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LimitElement> for u64 {
|
||||
fn from(value: LimitElement) -> Self {
|
||||
value.nresults.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct NresultsElement(#[xml(ty = "text")] pub u64);
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::Error;
|
||||
mod elements;
|
||||
mod prop_filter;
|
||||
pub use elements::*;
|
||||
#[allow(unused_imports)]
|
||||
pub use prop_filter::{PropFilterElement, PropFilterable};
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::AddressbookStore;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub async fn get_objects_addressbook_query<AS: AddressbookStore>(
|
||||
addr_query: &AddressbookQueryRequest,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
store: &AS,
|
||||
) -> Result<Vec<(String, AddressObject)>, Error> {
|
||||
let mut objects = store.get_objects(principal, addressbook_id).await?;
|
||||
objects.retain(|(_id, object)| addr_query.filter.matches(object));
|
||||
Ok(objects)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use super::{Allof, ParamFilterElement};
|
||||
use ical::{parser::Component, property::ContentLine};
|
||||
use rustical_dav::xml::TextMatchElement;
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_xml::XmlDeserialize;
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
// <!ELEMENT prop-filter (is-not-defined |
|
||||
// (text-match*, param-filter*))>
|
||||
//
|
||||
// <!ATTLIST prop-filter name CDATA #REQUIRED
|
||||
// test (anyof | allof) "anyof">
|
||||
// <!-- name value: a vCard property name (e.g., "NICKNAME")
|
||||
// test value:
|
||||
// anyof logical OR for text-match/param-filter matches
|
||||
// allof logical AND for text-match/param-filter matches -->
|
||||
pub struct PropFilterElement {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
pub(crate) is_not_defined: Option<()>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
|
||||
pub(crate) text_match: Vec<TextMatchElement>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
|
||||
pub(crate) param_filter: Vec<ParamFilterElement>,
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
pub test: Allof,
|
||||
|
||||
#[xml(ty = "attr")]
|
||||
pub(crate) name: String,
|
||||
}
|
||||
|
||||
impl PropFilterElement {
|
||||
#[must_use]
|
||||
pub fn match_property(&self, property: &ContentLine) -> bool {
|
||||
if self.param_filter.is_empty() && self.text_match.is_empty() {
|
||||
// Filter empty
|
||||
return true;
|
||||
}
|
||||
let Allof(allof) = self.test;
|
||||
let text_matches = self
|
||||
.text_match
|
||||
.iter()
|
||||
.map(|text_match| text_match.match_property(property));
|
||||
|
||||
let param_matches = self
|
||||
.param_filter
|
||||
.iter()
|
||||
.map(|param_filter| param_filter.match_property(property));
|
||||
let mut matches = text_matches.chain(param_matches);
|
||||
|
||||
if allof {
|
||||
matches.all(|a| a)
|
||||
} else {
|
||||
matches.any(|a| a)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn match_component(&self, comp: &impl PropFilterable) -> bool {
|
||||
let mut properties = comp.get_named_properties(&self.name);
|
||||
if self.is_not_defined.is_some() {
|
||||
return properties.next().is_none();
|
||||
}
|
||||
|
||||
// The filter matches when one property instance matches
|
||||
properties.any(|prop| self.match_property(prop))
|
||||
}
|
||||
}
|
||||
|
||||
pub trait PropFilterable {
|
||||
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine>;
|
||||
}
|
||||
|
||||
impl PropFilterable for AddressObject {
|
||||
fn get_named_properties<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a ContentLine> {
|
||||
self.get_vcard().get_named_properties(name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use super::FilterElement;
|
||||
use rstest::rstest;
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_xml::XmlDocument;
|
||||
|
||||
const VCF_1: &str = r"BEGIN:VCARD
|
||||
VERSION:4.0
|
||||
FN:Simon Perreault
|
||||
N:Perreault;Simon;;;ing. jr,M.Sc.
|
||||
BDAY:--0203
|
||||
GENDER:M
|
||||
EMAIL;TYPE=work:simon.perreault@viagenie.ca
|
||||
END:VCARD";
|
||||
|
||||
const VCF_2: &str = r"BEGIN:VCARD
|
||||
VERSION:4.0
|
||||
N:Gump;Forrest;;Mr.;
|
||||
FN:Forrest Gump
|
||||
ORG:Bubba Gump Shrimp Co.
|
||||
TITLE:Shrimp Man
|
||||
PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif
|
||||
TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212
|
||||
TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212
|
||||
ADR;TYPE=WORK;PREF=1;LABEL=100 Waters Edge\\nBaytown\\, LA 30314\\nUnited S
|
||||
tates of America:;;100 Waters Edge;Baytown;LA;30314;United States of Ameri
|
||||
ca
|
||||
ADR;TYPE=HOME;LABEL=42 Plantation St.\\nBaytown\\, LA 30314\\nUnited States
|
||||
of America:;;42 Plantation St.;Baytown;LA;30314;United States of America
|
||||
EMAIL:forrestgump@example.com
|
||||
REV:20080424T195243Z
|
||||
x-qq:21588891
|
||||
UID:890a9da4-bb6d-4afb-9f32-b5eff6494a53
|
||||
END:VCARD
|
||||
";
|
||||
|
||||
const FILTER_1: &str = r#"
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<C:filter xmlns:C="urn:ietf:params:xml:ns:carddav">
|
||||
<C:prop-filter name="EMAIL" test="allof">
|
||||
<C:text-match collation="i;ascii-casemap">simon.perreault@viagenie.ca</C:text-match>
|
||||
<C:param-filter name="TYPE">
|
||||
<C:text-match match-type="equals" collation="i;unicode-casemap">WORK</C:text-match>
|
||||
</C:param-filter>
|
||||
</C:prop-filter>
|
||||
</C:filter>
|
||||
"#;
|
||||
|
||||
const FILTER_2: &str = r#"
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<C:filter xmlns:C="urn:ietf:params:xml:ns:carddav">
|
||||
<C:prop-filter name="EMAIL" test="anyof">
|
||||
<C:text-match collation="i;ascii-casemap">forrestgump@example.com</C:text-match>
|
||||
<C:param-filter name="TYPE">
|
||||
<C:text-match match-type="equals" collation="i;ascii-casemap">WORK</C:text-match>
|
||||
</C:param-filter>
|
||||
</C:prop-filter>
|
||||
</C:filter>
|
||||
"#;
|
||||
|
||||
#[rstest]
|
||||
#[case(VCF_1, FILTER_1, true)]
|
||||
#[case(VCF_2, FILTER_1, false)]
|
||||
#[case(VCF_1, FILTER_2, true)]
|
||||
#[case(VCF_2, FILTER_2, true)]
|
||||
fn test_filter(#[case] vcf: &str, #[case] filter: &str, #[case] matches: bool) {
|
||||
dbg!(vcf);
|
||||
let obj = AddressObject::from_vcf(vcf.to_owned()).unwrap();
|
||||
let filter = FilterElement::parse_str(filter).unwrap();
|
||||
assert_eq!(matches, filter.matches(&obj));
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
use crate::{
|
||||
CardDavPrincipalUri, Error, address_object::AddressObjectPropWrapperName,
|
||||
addressbook::AddressbookResourceService,
|
||||
CardDavPrincipalUri, Error,
|
||||
address_object::{
|
||||
AddressObjectPropWrapper, AddressObjectPropWrapperName, resource::AddressObjectResource,
|
||||
},
|
||||
addressbook::{
|
||||
AddressbookResourceService,
|
||||
methods::report::addressbook_query::{
|
||||
AddressbookQueryRequest, get_objects_addressbook_query,
|
||||
},
|
||||
},
|
||||
};
|
||||
use addressbook_multiget::{AddressbookMultigetRequest, handle_addressbook_multiget};
|
||||
use axum::{
|
||||
@@ -8,19 +16,30 @@ use axum::{
|
||||
extract::{OriginalUri, Path, State},
|
||||
response::IntoResponse,
|
||||
};
|
||||
use rustical_dav::xml::{PropfindType, sync_collection::SyncCollectionRequest};
|
||||
use http::StatusCode;
|
||||
use rustical_dav::{
|
||||
resource::{PrincipalUri, Resource},
|
||||
xml::{
|
||||
MultistatusElement, PropfindType, multistatus::ResponseElement,
|
||||
sync_collection::SyncCollectionRequest,
|
||||
},
|
||||
};
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_xml::{XmlDeserialize, XmlDocument};
|
||||
use sync_collection::handle_sync_collection;
|
||||
use tracing::instrument;
|
||||
|
||||
mod addressbook_multiget;
|
||||
mod addressbook_query;
|
||||
mod sync_collection;
|
||||
|
||||
#[derive(XmlDeserialize, XmlDocument, Clone, Debug, PartialEq)]
|
||||
pub(crate) enum ReportRequest {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
AddressbookMultiget(AddressbookMultigetRequest),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
AddressbookQuery(AddressbookQueryRequest),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
SyncCollection(SyncCollectionRequest<AddressObjectPropWrapperName>),
|
||||
}
|
||||
@@ -29,11 +48,50 @@ impl ReportRequest {
|
||||
const fn props(&self) -> &PropfindType<AddressObjectPropWrapperName> {
|
||||
match self {
|
||||
Self::AddressbookMultiget(AddressbookMultigetRequest { prop, .. })
|
||||
| Self::SyncCollection(SyncCollectionRequest { prop, .. }) => prop,
|
||||
| Self::SyncCollection(SyncCollectionRequest { prop, .. })
|
||||
| Self::AddressbookQuery(AddressbookQueryRequest { prop, .. }) => prop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn objects_response(
|
||||
objects: Vec<(String, AddressObject)>,
|
||||
not_found: Vec<String>,
|
||||
path: &str,
|
||||
principal: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
prop: &PropfindType<AddressObjectPropWrapperName>,
|
||||
) -> Result<MultistatusElement<AddressObjectPropWrapper, String>, Error> {
|
||||
let mut responses = Vec::new();
|
||||
for (object_id, object) in objects {
|
||||
let path = format!("{}/{}.vcf", path, &object_id);
|
||||
responses.push(
|
||||
AddressObjectResource {
|
||||
object,
|
||||
object_id,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, prop, None, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
let not_found_responses = not_found
|
||||
.into_iter()
|
||||
.map(|path| ResponseElement {
|
||||
href: path,
|
||||
status: Some(StatusCode::NOT_FOUND),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(MultistatusElement {
|
||||
responses,
|
||||
member_responses: not_found_responses,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
#[instrument(skip(addr_store))]
|
||||
pub async fn route_report_addressbook<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
@@ -75,13 +133,36 @@ pub async fn route_report_addressbook<AS: AddressbookStore, S: SubscriptionStore
|
||||
)
|
||||
.await?
|
||||
}
|
||||
ReportRequest::AddressbookQuery(addr_query) => {
|
||||
let objects = get_objects_addressbook_query(
|
||||
addr_query,
|
||||
&principal,
|
||||
&addressbook_id,
|
||||
addr_store.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
objects_response(
|
||||
objects,
|
||||
vec![],
|
||||
uri.path(),
|
||||
&principal,
|
||||
&puri,
|
||||
&user,
|
||||
&addr_query.prop,
|
||||
)?
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::address_object::AddressObjectPropName;
|
||||
use crate::{
|
||||
address_object::AddressObjectPropName,
|
||||
addressbook::methods::report::addressbook_query::{
|
||||
Allof, FilterElement, LimitElement, NresultsElement, PropFilterElement,
|
||||
},
|
||||
};
|
||||
use rustical_dav::xml::{PropElement, sync_collection::SyncLevel};
|
||||
|
||||
#[test]
|
||||
@@ -144,4 +225,50 @@ mod tests {
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xml_addressbook_query() {
|
||||
let report_request = ReportRequest::parse_str(
|
||||
r#"
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<card:addressbook-query xmlns:card="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:">
|
||||
<d:prop>
|
||||
<d:getetag/>
|
||||
</d:prop>
|
||||
<card:filter>
|
||||
<card:prop-filter name="FN"/>
|
||||
</card:filter>
|
||||
<card:limit>
|
||||
<card:nresults>100</card:nresults>
|
||||
</card:limit>
|
||||
</card:addressbook-query>
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
report_request,
|
||||
ReportRequest::AddressbookQuery(AddressbookQueryRequest {
|
||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(
|
||||
vec![AddressObjectPropWrapperName::AddressObject(
|
||||
AddressObjectPropName::Getetag
|
||||
),],
|
||||
vec![]
|
||||
)),
|
||||
filter: FilterElement {
|
||||
test: Allof::default(),
|
||||
prop_filter: vec![PropFilterElement {
|
||||
name: "FN".to_owned(),
|
||||
is_not_defined: None,
|
||||
text_match: vec![],
|
||||
param_filter: vec![],
|
||||
test: Allof::default()
|
||||
}],
|
||||
},
|
||||
limit: Some(LimitElement {
|
||||
nresults: NresultsElement(100)
|
||||
})
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,11 +32,12 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
|
||||
.await?;
|
||||
|
||||
let mut responses = Vec::new();
|
||||
for object in new_objects {
|
||||
let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object.get_id());
|
||||
for (object_id, object) in new_objects {
|
||||
let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object_id);
|
||||
responses.push(
|
||||
AddressObjectResource {
|
||||
object,
|
||||
object_id,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use derive_more::{From, Into};
|
||||
use rustical_dav::{
|
||||
extensions::{CommonPropertiesProp, SyncTokenExtensionProp},
|
||||
xml::SupportedReportSet,
|
||||
xml::{SupportedReportSet, TextCollation},
|
||||
};
|
||||
use rustical_dav_push::DavPushExtensionProp;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
@@ -14,9 +15,11 @@ pub enum AddressbookProp {
|
||||
AddressbookDescription(Option<String>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
|
||||
SupportedAddressData(SupportedAddressData),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
|
||||
SupportedCollationSet(SupportedCollationSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
||||
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
MaxResourceSize(i64),
|
||||
}
|
||||
|
||||
@@ -60,6 +63,29 @@ impl Default for SupportedAddressData {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq, From, Into)]
|
||||
pub struct SupportedCollation(#[xml(ty = "text")] pub TextCollation);
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, Eq)]
|
||||
pub struct SupportedCollationSet(
|
||||
#[xml(
|
||||
ns = "rustical_dav::namespace::NS_CARDDAV",
|
||||
flatten,
|
||||
rename = "supported-collation"
|
||||
)]
|
||||
pub Vec<SupportedCollation>,
|
||||
);
|
||||
|
||||
impl Default for SupportedCollationSet {
|
||||
fn default() -> Self {
|
||||
Self(vec![
|
||||
SupportedCollation(TextCollation::AsciiCasemap),
|
||||
SupportedCollation(TextCollation::UnicodeCasemap),
|
||||
SupportedCollation(TextCollation::Octet),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq, Eq, VariantArray)]
|
||||
pub enum ReportMethod {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::prop::SupportedAddressData;
|
||||
use crate::Error;
|
||||
use crate::addressbook::prop::{
|
||||
AddressbookProp, AddressbookPropName, AddressbookPropWrapper, AddressbookPropWrapperName,
|
||||
SupportedCollationSet,
|
||||
};
|
||||
use derive_more::derive::{From, Into};
|
||||
use rustical_dav::extensions::{CommonPropertiesExtension, SyncTokenExtension};
|
||||
@@ -11,13 +12,14 @@ use rustical_dav::xml::{Resourcetype, ResourcetypeInner, SupportedReportSet};
|
||||
use rustical_dav_push::DavPushExtension;
|
||||
use rustical_store::Addressbook;
|
||||
use rustical_store::auth::Principal;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug, From, Into)]
|
||||
pub struct AddressbookResource(pub(crate) Addressbook);
|
||||
|
||||
impl ResourceName for AddressbookResource {
|
||||
fn get_name(&self) -> String {
|
||||
self.0.id.clone()
|
||||
fn get_name(&self) -> Cow<'_, str> {
|
||||
Cow::from(&self.0.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +63,9 @@ impl Resource for AddressbookResource {
|
||||
AddressbookPropName::MaxResourceSize => {
|
||||
AddressbookProp::MaxResourceSize(10_000_000)
|
||||
}
|
||||
AddressbookPropName::SupportedCollationSet => {
|
||||
AddressbookProp::SupportedCollationSet(SupportedCollationSet::default())
|
||||
}
|
||||
AddressbookPropName::SupportedReportSet => {
|
||||
AddressbookProp::SupportedReportSet(SupportedReportSet::all())
|
||||
}
|
||||
@@ -93,6 +98,7 @@ impl Resource for AddressbookResource {
|
||||
Ok(())
|
||||
}
|
||||
AddressbookProp::MaxResourceSize(_)
|
||||
| AddressbookProp::SupportedCollationSet(_)
|
||||
| AddressbookProp::SupportedReportSet(_)
|
||||
| AddressbookProp::SupportedAddressData(_) => {
|
||||
Err(rustical_dav::Error::PropReadOnly)
|
||||
@@ -115,6 +121,7 @@ impl Resource for AddressbookResource {
|
||||
Ok(())
|
||||
}
|
||||
AddressbookPropName::MaxResourceSize
|
||||
| AddressbookPropName::SupportedCollationSet
|
||||
| AddressbookPropName::SupportedReportSet
|
||||
| AddressbookPropName::SupportedAddressData => {
|
||||
Err(rustical_dav::Error::PropReadOnly)
|
||||
|
||||
@@ -78,7 +78,8 @@ impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
|
||||
.get_objects(principal, addressbook_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|object| AddressObjectResource {
|
||||
.map(|(object_id, object)| AddressObjectResource {
|
||||
object_id,
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
})
|
||||
@@ -91,7 +92,7 @@ impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
|
||||
file: Self::Resource,
|
||||
) -> Result<(), Self::Error> {
|
||||
self.addr_store
|
||||
.update_addressbook(principal.to_owned(), addressbook_id.to_owned(), file.into())
|
||||
.update_addressbook(principal, addressbook_id, file.into())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -31,6 +31,23 @@ ResponseElement {
|
||||
},
|
||||
),
|
||||
),
|
||||
Addressbook(
|
||||
SupportedCollationSet(
|
||||
SupportedCollationSet(
|
||||
[
|
||||
SupportedCollation(
|
||||
AsciiCasemap,
|
||||
),
|
||||
SupportedCollation(
|
||||
UnicodeCasemap,
|
||||
),
|
||||
SupportedCollation(
|
||||
Octet,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Addressbook(
|
||||
SupportedReportSet(
|
||||
SupportedReportSet {
|
||||
|
||||
@@ -3,57 +3,62 @@ 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">
|
||||
<response xmlns="DAV:">
|
||||
<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/>
|
||||
<prop xmlns="DAV:">
|
||||
<supported-address-data xmlns="urn:ietf:params:xml:ns:carddav">
|
||||
<address-data-type xmlns="urn:ietf:params:xml:ns:carddav" content-type="text/vcard" version="3.0"/>
|
||||
<address-data-type xmlns="urn:ietf:params:xml:ns:carddav" content-type="text/vcard" version="4.0"/>
|
||||
</supported-address-data>
|
||||
<supported-collation-set xmlns="urn:ietf:params:xml:ns:carddav">
|
||||
<supported-collation xmlns="urn:ietf:params:xml:ns:carddav">i;ascii-casemap</supported-collation>
|
||||
<supported-collation xmlns="urn:ietf:params:xml:ns:carddav">i;unicode-casemap</supported-collation>
|
||||
<supported-collation xmlns="urn:ietf:params:xml:ns:carddav">i;octet</supported-collation>
|
||||
</supported-collation-set>
|
||||
<supported-report-set xmlns="DAV:">
|
||||
<supported-report xmlns="DAV:">
|
||||
<report xmlns="DAV:">
|
||||
<addressbook-multiget xmlns="urn:ietf:params:xml:ns:carddav"/>
|
||||
</report>
|
||||
</supported-report>
|
||||
<supported-report>
|
||||
<report>
|
||||
<sync-collection/>
|
||||
<supported-report xmlns="DAV:">
|
||||
<report xmlns="DAV:">
|
||||
<sync-collection xmlns="DAV:"/>
|
||||
</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/>
|
||||
<max-resource-size xmlns="urn:ietf:params:xml:ns:carddav">10000000</max-resource-size>
|
||||
<sync-token xmlns="DAV:">github.com/lennart-k/rustical/ns/0</sync-token>
|
||||
<getctag xmlns="http://calendarserver.org/ns/">github.com/lennart-k/rustical/ns/0</getctag>
|
||||
<transports xmlns="https://bitfire.at/webdav-push">
|
||||
<web-push xmlns="https://bitfire.at/webdav-push"/>
|
||||
</transports>
|
||||
<topic xmlns="https://bitfire.at/webdav-push">asdasd</topic>
|
||||
<supported-triggers xmlns="https://bitfire.at/webdav-push">
|
||||
<content-update xmlns="https://bitfire.at/webdav-push">
|
||||
<depth xmlns="DAV:">1</depth>
|
||||
</content-update>
|
||||
<property-update xmlns="https://bitfire.at/webdav-push">
|
||||
<depth xmlns="DAV:">1</depth>
|
||||
</property-update>
|
||||
</supported-triggers>
|
||||
<resourcetype xmlns="DAV:">
|
||||
<collection xmlns="DAV:"/>
|
||||
<addressbook xmlns="urn:ietf:params:xml:ns:carddav"/>
|
||||
</resourcetype>
|
||||
<current-user-principal>
|
||||
<href>/carddav/principal/user/</href>
|
||||
<current-user-principal xmlns="DAV:">
|
||||
<href xmlns="DAV:">/carddav/principal/user/</href>
|
||||
</current-user-principal>
|
||||
<current-user-privilege-set>
|
||||
<current-user-privilege-set xmlns="DAV:">
|
||||
<privilege>
|
||||
<all/>
|
||||
</privilege>
|
||||
</current-user-privilege-set>
|
||||
<owner>
|
||||
<href>/carddav/principal/user/</href>
|
||||
<owner xmlns="DAV:">
|
||||
<href xmlns="DAV:">/carddav/principal/user/</href>
|
||||
</owner>
|
||||
</prop>
|
||||
<status>HTTP/1.1 200 OK</status>
|
||||
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
|
||||
</propstat>
|
||||
</response>
|
||||
|
||||
@@ -43,7 +43,8 @@ impl Error {
|
||||
Self::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
|
||||
Self::ChronoParseError(_) | Self::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::NotFound => StatusCode::NOT_FOUND,
|
||||
Self::IcalError(err) => err.status_code(),
|
||||
// TODO: Can also be Bad Request, if it's used input
|
||||
Self::IcalError(_err) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::Error;
|
||||
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
@@ -21,8 +23,8 @@ pub struct PrincipalResource {
|
||||
}
|
||||
|
||||
impl ResourceName for PrincipalResource {
|
||||
fn get_name(&self) -> String {
|
||||
self.principal.id.clone()
|
||||
fn get_name(&self) -> Cow<'_, str> {
|
||||
Cow::from(&self.principal.id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,43 +3,43 @@ 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">
|
||||
<response xmlns="DAV:">
|
||||
<href>/carddav/principal/user/</href>
|
||||
<propstat>
|
||||
<prop>
|
||||
<principal-URL>
|
||||
<href>/carddav/principal/user/</href>
|
||||
<prop xmlns="DAV:">
|
||||
<principal-URL xmlns="DAV:">
|
||||
<href xmlns="DAV:">/carddav/principal/user/</href>
|
||||
</principal-URL>
|
||||
<group-membership>
|
||||
<href>/carddav/principal/group/</href>
|
||||
<group-membership xmlns="DAV:">
|
||||
<href xmlns="DAV:">/carddav/principal/group/</href>
|
||||
</group-membership>
|
||||
<group-member-set>
|
||||
<group-member-set xmlns="DAV:">
|
||||
</group-member-set>
|
||||
<alternate-URI-set/>
|
||||
<principal-collection-set>
|
||||
<href>/carddav/principal/</href>
|
||||
<alternate-URI-set xmlns="DAV:"/>
|
||||
<principal-collection-set xmlns="DAV:">
|
||||
<href xmlns="DAV:">/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/>
|
||||
<addressbook-home-set xmlns="urn:ietf:params:xml:ns:carddav">
|
||||
<href xmlns="DAV:">/carddav/principal/group/</href>
|
||||
<href xmlns="DAV:">/carddav/principal/user/</href>
|
||||
</addressbook-home-set>
|
||||
<resourcetype xmlns="DAV:">
|
||||
<collection xmlns="DAV:"/>
|
||||
<principal xmlns="DAV:"/>
|
||||
</resourcetype>
|
||||
<displayname>user</displayname>
|
||||
<current-user-principal>
|
||||
<href>/carddav/principal/user/</href>
|
||||
<displayname xmlns="DAV:">user</displayname>
|
||||
<current-user-principal xmlns="DAV:">
|
||||
<href xmlns="DAV:">/carddav/principal/user/</href>
|
||||
</current-user-principal>
|
||||
<current-user-privilege-set>
|
||||
<current-user-privilege-set xmlns="DAV:">
|
||||
<privilege>
|
||||
<all/>
|
||||
</privilege>
|
||||
</current-user-privilege-set>
|
||||
<owner>
|
||||
<href>/carddav/principal/user/</href>
|
||||
<owner xmlns="DAV:">
|
||||
<href xmlns="DAV:">/carddav/principal/user/</href>
|
||||
</owner>
|
||||
</prop>
|
||||
<status>HTTP/1.1 200 OK</status>
|
||||
<status xmlns="DAV:">HTTP/1.1 200 OK</status>
|
||||
</propstat>
|
||||
</response>
|
||||
|
||||
@@ -28,3 +28,7 @@ headers.workspace = true
|
||||
strum.workspace = true
|
||||
matchit.workspace = true
|
||||
matchit-serde.workspace = true
|
||||
ical = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
ical = ["dep:ical"]
|
||||
|
||||
@@ -52,12 +52,11 @@ pub async fn route_delete<R: ResourceService>(
|
||||
return Err(Error::Unauthorized.into());
|
||||
}
|
||||
|
||||
if let Some(if_match) = if_match {
|
||||
dbg!(&if_match);
|
||||
if !resource.satisfies_if_match(&if_match) {
|
||||
// Precondition failed
|
||||
return Err(crate::Error::PreconditionFailed.into());
|
||||
}
|
||||
if let Some(if_match) = if_match
|
||||
&& !resource.satisfies_if_match(&if_match)
|
||||
{
|
||||
// Precondition failed
|
||||
return Err(crate::Error::PreconditionFailed.into());
|
||||
}
|
||||
if let Some(if_none_match) = if_none_match
|
||||
&& resource.satisfies_if_none_match(&if_none_match)
|
||||
|
||||
@@ -11,6 +11,7 @@ pub use resource_service::ResourceService;
|
||||
use rustical_xml::{
|
||||
EnumVariants, NamespaceOwned, PropName, XmlDeserialize, XmlDocument, XmlSerialize,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
use std::str::FromStr;
|
||||
|
||||
mod axum_methods;
|
||||
@@ -30,7 +31,7 @@ pub trait ResourcePropName: FromStr {}
|
||||
impl<T: FromStr> ResourcePropName for T {}
|
||||
|
||||
pub trait ResourceName {
|
||||
fn get_name(&self) -> String;
|
||||
fn get_name(&self) -> Cow<'_, str>;
|
||||
}
|
||||
|
||||
pub trait Resource: Clone + Send + 'static {
|
||||
|
||||
@@ -15,3 +15,7 @@ mod report_set;
|
||||
pub use report_set::SupportedReportSet;
|
||||
mod group;
|
||||
pub use group::*;
|
||||
#[cfg(feature = "ical")]
|
||||
mod text_match;
|
||||
#[cfg(feature = "ical")]
|
||||
pub use text_match::*;
|
||||
|
||||
@@ -42,13 +42,6 @@ pub enum PropstatWrapper<T: XmlSerialize> {
|
||||
// responsedescription?) >
|
||||
#[derive(XmlSerialize, XmlRootTag, Debug)]
|
||||
#[xml(ns = "crate::namespace::NS_DAV", root = "response")]
|
||||
#[xml(ns_prefix(
|
||||
crate::namespace::NS_DAV = "",
|
||||
crate::namespace::NS_CARDDAV = "CARD",
|
||||
crate::namespace::NS_CALDAV = "CAL",
|
||||
crate::namespace::NS_CALENDARSERVER = "CS",
|
||||
crate::namespace::NS_DAVPUSH = "PUSH"
|
||||
))]
|
||||
pub struct ResponseElement<PropstatType: XmlSerialize> {
|
||||
pub href: String,
|
||||
#[xml(serialize_with = "xml_serialize_optional_status")]
|
||||
|
||||
@@ -45,7 +45,7 @@ impl<PN: XmlDeserialize> XmlDeserialize for PropElement<PN> {
|
||||
// start of a child element
|
||||
Event::Start(start) | Event::Empty(start) => {
|
||||
let empty = matches!(event, Event::Empty(_));
|
||||
let (ns, name) = reader.resolve_element(start.name());
|
||||
let (ns, name) = reader.resolver().resolve_element(start.name());
|
||||
let ns = match ns {
|
||||
ResolveResult::Bound(ns) => Some(NamespaceOwned::from(ns)),
|
||||
ResolveResult::Unknown(_ns) => todo!("handle error"),
|
||||
|
||||
154
crates/dav/src/xml/text_match.rs
Normal file
154
crates/dav/src/xml/text_match.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
use ical::property::ContentLine;
|
||||
use rustical_xml::{ValueDeserialize, XmlDeserialize};
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub enum TextCollation {
|
||||
#[default]
|
||||
AsciiCasemap,
|
||||
UnicodeCasemap,
|
||||
Octet,
|
||||
}
|
||||
|
||||
impl TextCollation {
|
||||
#[must_use]
|
||||
pub fn normalise<'a>(&self, value: &'a str) -> Cow<'a, str> {
|
||||
match self {
|
||||
// https://datatracker.ietf.org/doc/html/rfc4790#section-9.2
|
||||
Self::AsciiCasemap => Cow::from(value.to_ascii_uppercase()),
|
||||
Self::UnicodeCasemap => Cow::from(value.to_uppercase()),
|
||||
Self::Octet => Cow::from(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for TextCollation {
|
||||
fn as_ref(&self) -> &str {
|
||||
match self {
|
||||
Self::AsciiCasemap => "i;ascii-casemap",
|
||||
Self::UnicodeCasemap => "i;unicode-casemap",
|
||||
Self::Octet => "i;octet",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ValueDeserialize for TextCollation {
|
||||
fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
|
||||
match val {
|
||||
"i;ascii-casemap" => Ok(Self::AsciiCasemap),
|
||||
"i;unicode-casemap" => Ok(Self::UnicodeCasemap),
|
||||
"i;octet" => Ok(Self::Octet),
|
||||
_ => Err(rustical_xml::XmlError::InvalidVariant(format!(
|
||||
"Invalid collation: {val}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub struct NegateCondition(pub bool);
|
||||
|
||||
impl ValueDeserialize for NegateCondition {
|
||||
fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
|
||||
match val {
|
||||
"yes" => Ok(Self(true)),
|
||||
"no" => Ok(Self(false)),
|
||||
_ => Err(rustical_xml::XmlError::InvalidVariant(format!(
|
||||
"Invalid negate-condition parameter: {val}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub enum MatchType {
|
||||
Equals,
|
||||
#[default]
|
||||
Contains,
|
||||
StartsWith,
|
||||
EndsWith,
|
||||
}
|
||||
|
||||
impl MatchType {
|
||||
#[must_use]
|
||||
pub fn match_text(&self, collation: &TextCollation, needle: &str, haystack: &str) -> bool {
|
||||
let haystack = collation.normalise(haystack);
|
||||
let needle = collation.normalise(needle);
|
||||
|
||||
match &self {
|
||||
Self::Equals => haystack == needle,
|
||||
Self::Contains => haystack.contains(needle.as_ref()),
|
||||
Self::StartsWith => haystack.starts_with(needle.as_ref()),
|
||||
Self::EndsWith => haystack.ends_with(needle.as_ref()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ValueDeserialize for MatchType {
|
||||
fn deserialize(val: &str) -> Result<Self, rustical_xml::XmlError> {
|
||||
Ok(match val {
|
||||
"equals" => Self::Equals,
|
||||
"contains" => Self::Contains,
|
||||
"starts-with" => Self::StartsWith,
|
||||
"ends-with" => Self::EndsWith,
|
||||
_ => {
|
||||
return Err(rustical_xml::XmlError::InvalidVariant(format!(
|
||||
"Invalid match-type parameter: {val}"
|
||||
)));
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
pub struct TextMatchElement {
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
pub collation: TextCollation,
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
pub negate_condition: NegateCondition,
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
pub match_type: MatchType,
|
||||
#[xml(ty = "text")]
|
||||
pub needle: String,
|
||||
}
|
||||
|
||||
impl TextMatchElement {
|
||||
#[must_use]
|
||||
pub fn match_text(&self, haystack: &str) -> bool {
|
||||
let Self {
|
||||
collation,
|
||||
negate_condition,
|
||||
needle,
|
||||
match_type,
|
||||
} = self;
|
||||
|
||||
let matches = match_type.match_text(collation, needle, haystack);
|
||||
// XOR
|
||||
negate_condition.0 ^ matches
|
||||
}
|
||||
#[must_use]
|
||||
pub fn match_property(&self, property: &ContentLine) -> bool {
|
||||
let text = property.value.as_deref().unwrap_or("");
|
||||
self.match_text(text)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::TextCollation;
|
||||
use crate::xml::MatchType;
|
||||
|
||||
#[test]
|
||||
fn test_collation() {
|
||||
assert!(!MatchType::Contains.match_text(&TextCollation::AsciiCasemap, "GrÜN", "grünsd"));
|
||||
assert!(MatchType::Contains.match_text(&TextCollation::AsciiCasemap, "GrüN", "grün"));
|
||||
assert!(!MatchType::Contains.match_text(&TextCollation::Octet, "GrüN", "grün"));
|
||||
assert!(MatchType::Contains.match_text(&TextCollation::UnicodeCasemap, "GrÜN", "grün"));
|
||||
assert!(MatchType::Contains.match_text(&TextCollation::AsciiCasemap, "GrüN", "grün"));
|
||||
assert!(MatchType::Contains.match_text(&TextCollation::AsciiCasemap, "GrüN", "grün"));
|
||||
assert!(MatchType::StartsWith.match_text(&TextCollation::Octet, "hello", "hello you"));
|
||||
assert!(MatchType::EndsWith.match_text(&TextCollation::Octet, "mama", "joe mama"));
|
||||
assert!(MatchType::Equals.match_text(&TextCollation::UnicodeCasemap, "GrÜN", "grün"));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
]
|
||||
},
|
||||
"imports": {
|
||||
"@deno/vite-plugin": "npm:@deno/vite-plugin@^1.0.5",
|
||||
"@deno/vite-plugin": "npm:@deno/vite-plugin@^1.0.6",
|
||||
"lit": "npm:lit@^3.3.1",
|
||||
"vite": "npm:vite@^7.3.0"
|
||||
}
|
||||
|
||||
8
crates/frontend/js-components/deno.lock
generated
8
crates/frontend/js-components/deno.lock
generated
@@ -1,14 +1,14 @@
|
||||
{
|
||||
"version": "5",
|
||||
"specifiers": {
|
||||
"npm:@deno/vite-plugin@^1.0.5": "1.0.5_vite@7.3.0__picomatch@4.0.3",
|
||||
"npm:@deno/vite-plugin@^1.0.6": "1.0.6_vite@7.3.0__picomatch@4.0.3",
|
||||
"npm:lit@^3.3.1": "3.3.1",
|
||||
"npm:vite@*": "7.3.0_picomatch@4.0.3",
|
||||
"npm:vite@^7.3.0": "7.3.0_picomatch@4.0.3"
|
||||
},
|
||||
"npm": {
|
||||
"@deno/vite-plugin@1.0.5_vite@7.3.0__picomatch@4.0.3": {
|
||||
"integrity": "sha512-tLja5n4dyMhcze1NzvSs2iiriBymfBlDCZIrjMTxb9O2ru0gvmV6mn5oBD2teNw5Sd92cj3YJzKwsAs8tMJXlg==",
|
||||
"@deno/vite-plugin@1.0.6_vite@7.3.0__picomatch@4.0.3": {
|
||||
"integrity": "sha512-Sh5XqvFuKAwjARTesi0n6xRpEXm1V0UeqKh+SxIrexCofxOaieNDMqXZD02RiZCg0mrJ43V8eCMuVrDfq6mLmg==",
|
||||
"dependencies": [
|
||||
"vite"
|
||||
]
|
||||
@@ -415,7 +415,7 @@
|
||||
},
|
||||
"workspace": {
|
||||
"dependencies": [
|
||||
"npm:@deno/vite-plugin@^1.0.5",
|
||||
"npm:@deno/vite-plugin@^1.0.6",
|
||||
"npm:lit@^3.3.1",
|
||||
"npm:vite@^7.3.0"
|
||||
]
|
||||
|
||||
@@ -9,9 +9,9 @@ use axum::{
|
||||
extract::Path,
|
||||
response::{Html, IntoResponse, Response},
|
||||
};
|
||||
use axum_extra::{TypedHeader, extract::Host};
|
||||
use axum_extra::TypedHeader;
|
||||
use chrono::{Duration, Utc};
|
||||
use headers::UserAgent;
|
||||
use headers::{Host, UserAgent};
|
||||
use http::StatusCode;
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -21,7 +21,7 @@ use tracing::instrument;
|
||||
pub async fn post_nextcloud_login(
|
||||
Extension(state): Extension<Arc<NextcloudFlows>>,
|
||||
TypedHeader(user_agent): TypedHeader<UserAgent>,
|
||||
Host(host): Host,
|
||||
TypedHeader(host): TypedHeader<Host>,
|
||||
) -> Json<NextcloudLoginResponse> {
|
||||
let flow_id = uuid::Uuid::new_v4().to_string();
|
||||
let token = uuid::Uuid::new_v4().to_string();
|
||||
@@ -150,7 +150,7 @@ pub async fn post_nextcloud_flow(
|
||||
user: Principal,
|
||||
Extension(state): Extension<Arc<NextcloudFlows>>,
|
||||
Path(flow_id): Path<String>,
|
||||
Host(host): Host,
|
||||
TypedHeader(host): TypedHeader<Host>,
|
||||
Form(form): Form<NextcloudAuthorizeForm>,
|
||||
) -> Result<Response, rustical_store::Error> {
|
||||
if let Some(flow) = state.flows.write().await.get_mut(&flow_id) {
|
||||
|
||||
@@ -7,8 +7,8 @@ use axum::{
|
||||
extract::Path,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
};
|
||||
use axum_extra::extract::Host;
|
||||
use headers::{ContentType, HeaderMapExt};
|
||||
use axum_extra::TypedHeader;
|
||||
use headers::{ContentType, HeaderMapExt, Host};
|
||||
use http::{HeaderValue, StatusCode, header};
|
||||
use percent_encoding::{CONTROLS, utf8_percent_encode};
|
||||
use rand::{Rng, distr::Alphanumeric};
|
||||
@@ -50,7 +50,7 @@ pub async fn route_post_app_token<AP: AuthenticationProvider>(
|
||||
user: Principal,
|
||||
Extension(auth_provider): Extension<Arc<AP>>,
|
||||
Path(user_id): Path<String>,
|
||||
Host(hostname): Host,
|
||||
TypedHeader(host): TypedHeader<Host>,
|
||||
Form(PostAppTokenForm { apple, name }): Form<PostAppTokenForm>,
|
||||
) -> Result<Response, rustical_store::Error> {
|
||||
assert!(!name.is_empty());
|
||||
@@ -66,10 +66,10 @@ pub async fn route_post_app_token<AP: AuthenticationProvider>(
|
||||
if apple {
|
||||
let profile = AppleConfig {
|
||||
token_name: name,
|
||||
account_description: format!("{}@{}", &user.id, &hostname),
|
||||
hostname: hostname.clone(),
|
||||
caldav_principal_url: format!("https://{hostname}/caldav-compat/principal/{user_id}"),
|
||||
carddav_principal_url: format!("https://{hostname}/carddav/principal/{user_id}"),
|
||||
account_description: format!("{}@{}", &user.id, &host),
|
||||
hostname: host.to_string(),
|
||||
caldav_principal_url: format!("https://{host}/caldav-compat/principal/{user_id}"),
|
||||
carddav_principal_url: format!("https://{host}/carddav/principal/{user_id}"),
|
||||
user: user.id.clone(),
|
||||
token,
|
||||
caldav_profile_uuid: Uuid::new_v4(),
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{FrontendConfig, OidcConfig, pages::DefaultLayoutData};
|
||||
use askama::Template;
|
||||
use askama_web::WebTemplate;
|
||||
@@ -8,10 +6,12 @@ use axum::{
|
||||
extract::Query,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
};
|
||||
use axum_extra::extract::Host;
|
||||
use axum_extra::TypedHeader;
|
||||
use headers::Host;
|
||||
use http::StatusCode;
|
||||
use rustical_store::auth::AuthenticationProvider;
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use tower_sessions::Session;
|
||||
use tracing::{instrument, warn};
|
||||
use url::Url;
|
||||
@@ -73,7 +73,7 @@ pub async fn route_post_login<AP: AuthenticationProvider>(
|
||||
Extension(auth_provider): Extension<Arc<AP>>,
|
||||
Extension(config): Extension<FrontendConfig>,
|
||||
session: Session,
|
||||
Host(host): Host,
|
||||
TypedHeader(host): TypedHeader<Host>,
|
||||
Form(PostLoginForm {
|
||||
username,
|
||||
password,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::pages::user::{Section, UserPage};
|
||||
use askama::Template;
|
||||
use askama_web::WebTemplate;
|
||||
use axum::{
|
||||
@@ -7,13 +8,11 @@ use axum::{
|
||||
extract::Path,
|
||||
response::{IntoResponse, Redirect},
|
||||
};
|
||||
use axum_extra::{TypedHeader, extract::Host};
|
||||
use headers::UserAgent;
|
||||
use axum_extra::TypedHeader;
|
||||
use headers::{Host, UserAgent};
|
||||
use http::StatusCode;
|
||||
use rustical_store::auth::{AppToken, AuthenticationProvider, Principal};
|
||||
|
||||
use crate::pages::user::{Section, UserPage};
|
||||
|
||||
impl Section for ProfileSection {
|
||||
fn name() -> &'static str {
|
||||
"profile"
|
||||
@@ -33,7 +32,7 @@ pub async fn route_user_named<AP: AuthenticationProvider>(
|
||||
Path(user_id): Path<String>,
|
||||
Extension(auth_provider): Extension<Arc<AP>>,
|
||||
TypedHeader(user_agent): TypedHeader<UserAgent>,
|
||||
Host(host): Host,
|
||||
TypedHeader(host): TypedHeader<Host>,
|
||||
user: Principal,
|
||||
) -> impl IntoResponse {
|
||||
if user_id != user.id {
|
||||
@@ -41,7 +40,10 @@ pub async fn route_user_named<AP: AuthenticationProvider>(
|
||||
}
|
||||
|
||||
let is_apple = user_agent.as_str().contains("Apple") || user_agent.as_str().contains("Mac OS");
|
||||
let davx5_hostname = user_agent.as_str().contains("Android").then_some(host);
|
||||
let davx5_hostname = user_agent
|
||||
.as_str()
|
||||
.contains("Android")
|
||||
.then_some(host.to_string());
|
||||
|
||||
UserPage {
|
||||
section: ProfileSection {
|
||||
|
||||
@@ -21,3 +21,5 @@ rrule.workspace = true
|
||||
serde.workspace = true
|
||||
sha2.workspace = true
|
||||
axum.workspace = true
|
||||
rstest.workspace = true
|
||||
similar-asserts.workspace = true
|
||||
|
||||
@@ -1,59 +1,45 @@
|
||||
use crate::{CalDateTime, LOCAL_DATE};
|
||||
use crate::{CalendarObject, Error};
|
||||
use chrono::Datelike;
|
||||
use ical::generator::Emitter;
|
||||
use ical::parser::{
|
||||
Component,
|
||||
vcard::{self, component::VcardContact},
|
||||
use chrono::{NaiveDate, Utc};
|
||||
use ical::component::{
|
||||
CalendarInnerDataBuilder, IcalAlarmBuilder, IcalCalendarObjectBuilder, IcalEventBuilder,
|
||||
};
|
||||
use ical::generator::Emitter;
|
||||
use ical::parser::vcard::{self, component::VcardContact};
|
||||
use ical::parser::{
|
||||
Calscale, ComponentMut, IcalCALSCALEProperty, IcalDTENDProperty, IcalDTSTAMPProperty,
|
||||
IcalDTSTARTProperty, IcalPRODIDProperty, IcalRRULEProperty, IcalSUMMARYProperty,
|
||||
IcalUIDProperty, IcalVERSIONProperty, IcalVersion, VcardANNIVERSARYProperty, VcardBDAYProperty,
|
||||
VcardFNProperty,
|
||||
};
|
||||
use ical::property::ContentLine;
|
||||
use ical::types::{CalDate, PartialDate};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::HashMap, io::BufReader};
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AddressObject {
|
||||
id: String,
|
||||
vcf: String,
|
||||
vcard: VcardContact,
|
||||
}
|
||||
|
||||
impl TryFrom<VcardContact> for AddressObject {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(vcard: VcardContact) -> Result<Self, Self::Error> {
|
||||
let uid = vcard
|
||||
.get_uid()
|
||||
.ok_or_else(|| Error::InvalidData("missing UID".to_owned()))?
|
||||
.to_owned();
|
||||
impl From<VcardContact> for AddressObject {
|
||||
fn from(vcard: VcardContact) -> Self {
|
||||
let vcf = vcard.generate();
|
||||
Ok(Self {
|
||||
vcf,
|
||||
vcard,
|
||||
id: uid,
|
||||
})
|
||||
Self { vcf, vcard }
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressObject {
|
||||
pub fn from_vcf(id: String, vcf: String) -> Result<Self, Error> {
|
||||
let mut parser = vcard::VcardParser::new(BufReader::new(vcf.as_bytes()));
|
||||
let vcard = parser.next().ok_or(Error::MissingContact)??;
|
||||
if parser.next().is_some() {
|
||||
return Err(Error::InvalidData(
|
||||
"multiple vcards, only one allowed".to_owned(),
|
||||
));
|
||||
}
|
||||
Ok(Self { id, vcf, vcard })
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_id(&self) -> &str {
|
||||
&self.id
|
||||
pub fn from_vcf(vcf: String) -> Result<Self, Error> {
|
||||
let parser = vcard::VcardParser::from_slice(vcf.as_bytes());
|
||||
let vcard = parser.expect_one()?;
|
||||
Ok(Self { vcf, vcard })
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_etag(&self) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(self.get_id());
|
||||
hasher.update(self.get_vcf());
|
||||
format!("\"{:x}\"", hasher.finalize())
|
||||
}
|
||||
@@ -63,120 +49,119 @@ impl AddressObject {
|
||||
&self.vcf
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_anniversary(&self) -> Option<(CalDateTime, bool)> {
|
||||
let prop = self.vcard.get_property("ANNIVERSARY")?.value.as_deref()?;
|
||||
CalDateTime::parse_vcard(prop).ok()
|
||||
}
|
||||
fn get_significant_date_object(
|
||||
&self,
|
||||
date: &PartialDate,
|
||||
summary_prefix: &str,
|
||||
suffix: &str,
|
||||
) -> Result<Option<CalendarObject>, Error> {
|
||||
let Some(uid) = self.vcard.get_uid() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let uid = format!("{uid}{suffix}");
|
||||
let year = date.get_year();
|
||||
let year_suffix = year.map(|year| format!(" {year}")).unwrap_or_default();
|
||||
let Some(month) = date.get_month() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(day) = date.get_day() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(dtstart) = NaiveDate::from_ymd_opt(year.unwrap_or(1900), month, day) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let start_date = CalDate(dtstart, ical::types::Timezone::Local);
|
||||
let Some(end_date) = start_date.succ_opt() else {
|
||||
// start_date is MAX_DATE, this should never happen but FAPP also not raise an error
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(VcardFNProperty(fullname, _)) = self.vcard.full_name.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let summary = format!("{summary_prefix} {fullname}{year_suffix}");
|
||||
|
||||
#[must_use]
|
||||
pub fn get_birthday(&self) -> Option<(CalDateTime, bool)> {
|
||||
let prop = self.vcard.get_property("BDAY")?.value.as_deref()?;
|
||||
CalDateTime::parse_vcard(prop).ok()
|
||||
}
|
||||
let event = IcalEventBuilder {
|
||||
properties: vec![
|
||||
IcalDTSTAMPProperty(Utc::now().into(), vec![].into()).into(),
|
||||
IcalDTSTARTProperty(start_date.into(), vec![].into()).into(),
|
||||
IcalDTENDProperty(end_date.into(), vec![].into()).into(),
|
||||
IcalUIDProperty(uid, vec![].into()).into(),
|
||||
IcalRRULEProperty(
|
||||
rrule::RRule::from_str("FREQ=YEARLY").unwrap(),
|
||||
vec![].into(),
|
||||
)
|
||||
.into(),
|
||||
IcalSUMMARYProperty(summary.clone(), vec![].into()).into(),
|
||||
ContentLine {
|
||||
name: "TRANSP".to_owned(),
|
||||
value: Some("TRANSPARENT".to_owned()),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
alarms: vec![IcalAlarmBuilder {
|
||||
properties: vec![
|
||||
ContentLine {
|
||||
name: "TRIGGER".to_owned(),
|
||||
value: Some("-PT0M".to_owned()),
|
||||
params: vec![("VALUE".to_owned(), vec!["DURATION".to_owned()])].into(),
|
||||
},
|
||||
ContentLine {
|
||||
name: "ACTION".to_owned(),
|
||||
value: Some("DISPLAY".to_owned()),
|
||||
..Default::default()
|
||||
},
|
||||
ContentLine {
|
||||
name: "DESCRIPTION".to_owned(),
|
||||
value: Some(summary),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
}],
|
||||
};
|
||||
|
||||
#[must_use]
|
||||
pub fn get_full_name(&self) -> Option<&str> {
|
||||
let prop = self.vcard.get_property("FN")?;
|
||||
prop.value.as_deref()
|
||||
Ok(Some(
|
||||
IcalCalendarObjectBuilder {
|
||||
properties: vec![
|
||||
IcalVERSIONProperty(IcalVersion::Version2_0, vec![].into()).into(),
|
||||
IcalCALSCALEProperty(Calscale::Gregorian, vec![].into()).into(),
|
||||
IcalPRODIDProperty(
|
||||
"-//github.com/lennart-k/rustical birthday calendar//EN".to_owned(),
|
||||
vec![].into(),
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
inner: Some(CalendarInnerDataBuilder::Event(vec![event])),
|
||||
vtimezones: HashMap::default(),
|
||||
}
|
||||
.build(None)?
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_anniversary_object(&self) -> Result<Option<CalendarObject>, Error> {
|
||||
Ok(
|
||||
if let Some((anniversary, contains_year)) = self.get_anniversary() {
|
||||
let Some(fullname) = self.get_full_name() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let anniversary = anniversary.date();
|
||||
let year = contains_year.then_some(anniversary.year());
|
||||
let anniversary_start = anniversary.format(LOCAL_DATE);
|
||||
let anniversary_end = anniversary
|
||||
.succ_opt()
|
||||
.unwrap_or(anniversary)
|
||||
.format(LOCAL_DATE);
|
||||
let uid = format!("{}-anniversary", self.get_id());
|
||||
let Some(VcardANNIVERSARYProperty(anniversary, _)) = &self.vcard.anniversary else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(date) = &anniversary.date else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let year_suffix = year.map(|year| format!(" ({year})")).unwrap_or_default();
|
||||
Some(CalendarObject::from_ics(
|
||||
format!(
|
||||
r"BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
CALSCALE:GREGORIAN
|
||||
PRODID:-//github.com/lennart-k/rustical birthday calendar//EN
|
||||
BEGIN:VEVENT
|
||||
DTSTART;VALUE=DATE:{anniversary_start}
|
||||
DTEND;VALUE=DATE:{anniversary_end}
|
||||
UID:{uid}
|
||||
RRULE:FREQ=YEARLY
|
||||
SUMMARY:💍 {fullname}{year_suffix}
|
||||
TRANSP:TRANSPARENT
|
||||
BEGIN:VALARM
|
||||
TRIGGER;VALUE=DURATION:-PT0M
|
||||
ACTION:DISPLAY
|
||||
DESCRIPTION:💍 {fullname}{year_suffix}
|
||||
END:VALARM
|
||||
END:VEVENT
|
||||
END:VCALENDAR",
|
||||
),
|
||||
None,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
self.get_significant_date_object(date, "💍", "-anniversary")
|
||||
}
|
||||
|
||||
pub fn get_birthday_object(&self) -> Result<Option<CalendarObject>, Error> {
|
||||
Ok(
|
||||
if let Some((birthday, contains_year)) = self.get_birthday() {
|
||||
let Some(fullname) = self.get_full_name() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let birthday = birthday.date();
|
||||
let year = contains_year.then_some(birthday.year());
|
||||
let birthday_start = birthday.format(LOCAL_DATE);
|
||||
let birthday_end = birthday.succ_opt().unwrap_or(birthday).format(LOCAL_DATE);
|
||||
let uid = format!("{}-birthday", self.get_id());
|
||||
let Some(VcardBDAYProperty(bday, _)) = &self.vcard.birthday else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(date) = &bday.date else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let year_suffix = year.map(|year| format!(" ({year})")).unwrap_or_default();
|
||||
Some(CalendarObject::from_ics(
|
||||
format!(
|
||||
r"BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
CALSCALE:GREGORIAN
|
||||
PRODID:-//github.com/lennart-k/rustical birthday calendar//EN
|
||||
BEGIN:VEVENT
|
||||
DTSTART;VALUE=DATE:{birthday_start}
|
||||
DTEND;VALUE=DATE:{birthday_end}
|
||||
UID:{uid}
|
||||
RRULE:FREQ=YEARLY
|
||||
SUMMARY:🎂 {fullname}{year_suffix}
|
||||
TRANSP:TRANSPARENT
|
||||
BEGIN:VALARM
|
||||
TRIGGER;VALUE=DURATION:-PT0M
|
||||
ACTION:DISPLAY
|
||||
DESCRIPTION:🎂 {fullname}{year_suffix}
|
||||
END:VALARM
|
||||
END:VEVENT
|
||||
END:VCALENDAR",
|
||||
),
|
||||
None,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
self.get_significant_date_object(date, "🎂", "-birthday")
|
||||
}
|
||||
|
||||
/// Get significant dates associated with this address object
|
||||
pub fn get_significant_dates(&self) -> Result<HashMap<&'static str, CalendarObject>, Error> {
|
||||
let mut out = HashMap::new();
|
||||
if let Some(birthday) = self.get_birthday_object()? {
|
||||
out.insert("birthday", birthday);
|
||||
}
|
||||
if let Some(anniversary) = self.get_anniversary_object()? {
|
||||
out.insert("anniversary", anniversary);
|
||||
}
|
||||
Ok(out)
|
||||
#[must_use]
|
||||
pub const fn get_vcard(&self) -> &VcardContact {
|
||||
&self.vcard
|
||||
}
|
||||
}
|
||||
|
||||
120
crates/ical/src/calendar_object.rs
Normal file
120
crates/ical/src/calendar_object.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
use crate::Error;
|
||||
use derive_more::Display;
|
||||
use ical::IcalObjectParser;
|
||||
use ical::component::CalendarInnerData;
|
||||
use ical::component::IcalCalendarObject;
|
||||
use ical::generator::Emitter;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display)]
|
||||
// specified in https://datatracker.ietf.org/doc/html/rfc5545#section-3.6
|
||||
pub enum CalendarObjectType {
|
||||
#[serde(rename = "VEVENT")]
|
||||
Event = 0,
|
||||
#[serde(rename = "VTODO")]
|
||||
Todo = 1,
|
||||
#[serde(rename = "VJOURNAL")]
|
||||
Journal = 2,
|
||||
}
|
||||
|
||||
impl From<&IcalCalendarObject> for CalendarObjectType {
|
||||
fn from(value: &IcalCalendarObject) -> Self {
|
||||
match value.get_inner() {
|
||||
CalendarInnerData::Event(_, _) => Self::Event,
|
||||
CalendarInnerData::Todo(_, _) => Self::Todo,
|
||||
CalendarInnerData::Journal(_, _) => Self::Journal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CalendarObjectType {
|
||||
#[must_use]
|
||||
pub const fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Event => "VEVENT",
|
||||
Self::Todo => "VTODO",
|
||||
Self::Journal => "VJOURNAL",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustical_xml::ValueSerialize for CalendarObjectType {
|
||||
fn serialize(&self) -> String {
|
||||
self.as_str().to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl rustical_xml::ValueDeserialize for CalendarObjectType {
|
||||
fn deserialize(val: &str) -> std::result::Result<Self, rustical_xml::XmlError> {
|
||||
match <String as rustical_xml::ValueDeserialize>::deserialize(val)?.as_str() {
|
||||
"VEVENT" => Ok(Self::Event),
|
||||
"VTODO" => Ok(Self::Todo),
|
||||
"VJOURNAL" => Ok(Self::Journal),
|
||||
_ => Err(rustical_xml::XmlError::InvalidValue(
|
||||
rustical_xml::ParseValueError::Other(format!(
|
||||
"Invalid value '{val}', must be VEVENT, VTODO, or VJOURNAL"
|
||||
)),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CalendarObject {
|
||||
inner: IcalCalendarObject,
|
||||
ics: String,
|
||||
}
|
||||
|
||||
impl CalendarObject {
|
||||
pub fn from_ics(ics: String) -> Result<Self, Error> {
|
||||
let parser = IcalObjectParser::from_slice(ics.as_bytes());
|
||||
let inner = parser.expect_one()?;
|
||||
|
||||
Ok(Self { inner, ics })
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn get_inner(&self) -> &IcalCalendarObject {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_uid(&self) -> &str {
|
||||
self.inner.get_uid()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_etag(&self) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(self.get_uid());
|
||||
hasher.update(self.get_ics());
|
||||
format!("\"{:x}\"", hasher.finalize())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_ics(&self) -> &str {
|
||||
&self.ics
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_object_type(&self) -> CalendarObjectType {
|
||||
(&self.inner).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CalendarObject> for IcalCalendarObject {
|
||||
fn from(value: CalendarObject) -> Self {
|
||||
value.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl From<IcalCalendarObject> for CalendarObject {
|
||||
fn from(value: IcalCalendarObject) -> Self {
|
||||
Self {
|
||||
ics: value.generate(),
|
||||
inner: value,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
use axum::{http::StatusCode, response::IntoResponse};
|
||||
|
||||
use crate::CalDateTimeError;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
#[error("Invalid ics/vcf input: {0}")]
|
||||
InvalidData(String),
|
||||
|
||||
#[error("Missing calendar")]
|
||||
MissingCalendar,
|
||||
|
||||
#[error("Missing contact")]
|
||||
MissingContact,
|
||||
|
||||
#[error(transparent)]
|
||||
ParserError(#[from] ical::parser::ParserError),
|
||||
|
||||
#[error(transparent)]
|
||||
CalDateTimeError(#[from] CalDateTimeError),
|
||||
|
||||
#[error(transparent)]
|
||||
RRuleError(#[from] rrule::RRuleError),
|
||||
}
|
||||
|
||||
impl Error {
|
||||
#[must_use]
|
||||
pub const fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
Self::InvalidData(_) | Self::MissingCalendar | Self::MissingContact => {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for Error {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
(self.status_code(), self.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
use crate::CalDateTime;
|
||||
use crate::Error;
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use ical::parser::ComponentMut;
|
||||
use ical::{generator::IcalEvent, parser::Component, property::Property};
|
||||
use rrule::{RRule, RRuleSet};
|
||||
use std::{collections::HashMap, str::FromStr};
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EventObject {
|
||||
pub event: IcalEvent,
|
||||
// If a timezone is None that means that in the VCALENDAR object there's a timezone defined
|
||||
// with that name but its not from the Olson DB
|
||||
pub timezones: HashMap<String, Option<chrono_tz::Tz>>,
|
||||
}
|
||||
|
||||
impl EventObject {
|
||||
#[must_use]
|
||||
pub fn get_uid(&self) -> &str {
|
||||
self.event.get_uid()
|
||||
}
|
||||
|
||||
pub fn get_dtstart(&self) -> Result<Option<CalDateTime>, Error> {
|
||||
if let Some(dtstart) = self.event.get_dtstart() {
|
||||
Ok(Some(CalDateTime::parse_prop(dtstart, &self.timezones)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_dtend(&self) -> Result<Option<CalDateTime>, Error> {
|
||||
if let Some(dtend) = self.event.get_dtend() {
|
||||
Ok(Some(CalDateTime::parse_prop(dtend, &self.timezones)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_last_occurence(&self) -> Result<Option<CalDateTime>, Error> {
|
||||
if self.event.get_rrule().is_some() {
|
||||
// TODO: understand recurrence rules
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if let Some(dtend) = self.get_dtend()? {
|
||||
return Ok(Some(dtend));
|
||||
}
|
||||
|
||||
let duration = self.event.get_duration().unwrap_or(Duration::days(1));
|
||||
|
||||
let first_occurence = self.get_dtstart()?;
|
||||
Ok(first_occurence.map(|first_occurence| first_occurence + duration))
|
||||
}
|
||||
|
||||
pub fn recurrence_ruleset(&self) -> Result<Option<rrule::RRuleSet>, Error> {
|
||||
let dtstart: DateTime<rrule::Tz> = if let Some(dtstart) = self.get_dtstart()? {
|
||||
if let Some(dtend) = self.get_dtend()? {
|
||||
// DTSTART and DTEND MUST have the same timezone
|
||||
assert_eq!(dtstart.timezone(), dtend.timezone());
|
||||
}
|
||||
|
||||
dtstart
|
||||
.as_datetime()
|
||||
.with_timezone(&dtstart.timezone().into())
|
||||
} else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let mut rrule_set = RRuleSet::new(dtstart);
|
||||
|
||||
for prop in &self.event.properties {
|
||||
rrule_set = match prop.name.as_str() {
|
||||
"RRULE" => {
|
||||
let rrule = RRule::from_str(prop.value.as_ref().ok_or_else(|| {
|
||||
Error::RRuleError(rrule::ParseError::MissingDateGenerationRules.into())
|
||||
})?)?
|
||||
.validate(dtstart)
|
||||
.unwrap();
|
||||
rrule_set.rrule(rrule)
|
||||
}
|
||||
"RDATE" => {
|
||||
let rdate = CalDateTime::parse_prop(prop, &self.timezones)?.into();
|
||||
rrule_set.rdate(rdate)
|
||||
}
|
||||
"EXDATE" => {
|
||||
let exdate = CalDateTime::parse_prop(prop, &self.timezones)?.into();
|
||||
rrule_set.exdate(exdate)
|
||||
}
|
||||
_ => rrule_set,
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(rrule_set))
|
||||
}
|
||||
|
||||
pub fn expand_recurrence(
|
||||
&self,
|
||||
start: Option<DateTime<Utc>>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
overrides: &[Self],
|
||||
) -> Result<Vec<IcalEvent>, Error> {
|
||||
if let Some(mut rrule_set) = self.recurrence_ruleset()? {
|
||||
if let Some(start) = start {
|
||||
rrule_set = rrule_set.after(start.with_timezone(&rrule::Tz::UTC));
|
||||
}
|
||||
if let Some(end) = end {
|
||||
rrule_set = rrule_set.before(end.with_timezone(&rrule::Tz::UTC));
|
||||
}
|
||||
let mut events = vec![];
|
||||
let dates = rrule_set.all(2048).dates;
|
||||
let dtstart = self.get_dtstart()?.expect("We must have a DTSTART here");
|
||||
let computed_duration = self
|
||||
.get_dtend()?
|
||||
.map(|dtend| dtend.as_datetime().into_owned() - dtstart.as_datetime().into_owned());
|
||||
|
||||
'recurrence: for date in dates {
|
||||
let date = CalDateTime::from(date);
|
||||
let dateformat = if dtstart.is_date() {
|
||||
date.format_date()
|
||||
} else {
|
||||
date.format()
|
||||
};
|
||||
|
||||
for ev_override in overrides {
|
||||
if let Some(override_id) = &ev_override
|
||||
.event
|
||||
.get_recurrence_id()
|
||||
.as_ref()
|
||||
.expect("overrides have a recurrence id")
|
||||
.value
|
||||
&& override_id == &dateformat
|
||||
{
|
||||
// We have an override for this occurence
|
||||
//
|
||||
events.push(ev_override.event.clone());
|
||||
continue 'recurrence;
|
||||
}
|
||||
}
|
||||
|
||||
let mut ev = self.event.clone().mutable();
|
||||
ev.remove_property("RRULE");
|
||||
ev.remove_property("RDATE");
|
||||
ev.remove_property("EXDATE");
|
||||
ev.remove_property("EXRULE");
|
||||
let dtstart_prop = ev
|
||||
.get_property("DTSTART")
|
||||
.expect("We must have a DTSTART here")
|
||||
.clone();
|
||||
ev.remove_property("DTSTART");
|
||||
ev.remove_property("DTEND");
|
||||
|
||||
ev.set_property(Property {
|
||||
name: "RECURRENCE-ID".to_string(),
|
||||
value: Some(dateformat.clone()),
|
||||
params: vec![],
|
||||
});
|
||||
ev.set_property(Property {
|
||||
name: "DTSTART".to_string(),
|
||||
value: Some(dateformat),
|
||||
params: dtstart_prop.params.clone(),
|
||||
});
|
||||
if let Some(duration) = computed_duration {
|
||||
let dtend = date + duration;
|
||||
let dtendformat = if dtstart.is_date() {
|
||||
dtend.format_date()
|
||||
} else {
|
||||
dtend.format()
|
||||
};
|
||||
ev.set_property(Property {
|
||||
name: "DTEND".to_string(),
|
||||
value: Some(dtendformat),
|
||||
params: dtstart_prop.params,
|
||||
});
|
||||
}
|
||||
events.push(ev.verify()?);
|
||||
}
|
||||
Ok(events)
|
||||
} else {
|
||||
Ok(vec![self.event.clone()])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::CalendarObject;
|
||||
use ical::generator::Emitter;
|
||||
|
||||
const ICS: &str = r"BEGIN:VCALENDAR
|
||||
CALSCALE:GREGORIAN
|
||||
VERSION:2.0
|
||||
BEGIN:VTIMEZONE
|
||||
TZID:Europe/Berlin
|
||||
X-LIC-LOCATION:Europe/Berlin
|
||||
END:VTIMEZONE
|
||||
|
||||
BEGIN:VEVENT
|
||||
UID:318ec6503573d9576818daf93dac07317058d95c
|
||||
DTSTAMP:20250502T132758Z
|
||||
DTSTART;TZID=Europe/Berlin:20250506T090000
|
||||
DTEND;TZID=Europe/Berlin:20250506T092500
|
||||
SEQUENCE:2
|
||||
SUMMARY:weekly stuff
|
||||
TRANSP:OPAQUE
|
||||
RRULE:FREQ=WEEKLY;COUNT=4;INTERVAL=2;BYDAY=TU,TH,SU
|
||||
END:VEVENT
|
||||
END:VCALENDAR";
|
||||
|
||||
const EXPANDED: [&str; 4] = [
|
||||
"BEGIN:VEVENT\r
|
||||
UID:318ec6503573d9576818daf93dac07317058d95c\r
|
||||
DTSTAMP:20250502T132758Z\r
|
||||
SEQUENCE:2\r
|
||||
SUMMARY:weekly stuff\r
|
||||
TRANSP:OPAQUE\r
|
||||
RECURRENCE-ID:20250506T090000\r
|
||||
DTSTART;TZID=Europe/Berlin:20250506T090000\r
|
||||
DTEND;TZID=Europe/Berlin:20250506T092500\r
|
||||
END:VEVENT\r\n",
|
||||
"BEGIN:VEVENT\r
|
||||
UID:318ec6503573d9576818daf93dac07317058d95c\r
|
||||
DTSTAMP:20250502T132758Z\r
|
||||
SEQUENCE:2\r
|
||||
SUMMARY:weekly stuff\r
|
||||
TRANSP:OPAQUE\r
|
||||
RECURRENCE-ID:20250508T090000\r
|
||||
DTSTART;TZID=Europe/Berlin:20250508T090000\r
|
||||
DTEND;TZID=Europe/Berlin:20250508T092500\r
|
||||
END:VEVENT\r\n",
|
||||
"BEGIN:VEVENT\r
|
||||
UID:318ec6503573d9576818daf93dac07317058d95c\r
|
||||
DTSTAMP:20250502T132758Z\r
|
||||
SEQUENCE:2\r
|
||||
SUMMARY:weekly stuff\r
|
||||
TRANSP:OPAQUE\r
|
||||
RECURRENCE-ID:20250511T090000\r
|
||||
DTSTART;TZID=Europe/Berlin:20250511T090000\r
|
||||
DTEND;TZID=Europe/Berlin:20250511T092500\r
|
||||
END:VEVENT\r\n",
|
||||
"BEGIN:VEVENT\r
|
||||
UID:318ec6503573d9576818daf93dac07317058d95c\r
|
||||
DTSTAMP:20250502T132758Z\r
|
||||
SEQUENCE:2\r
|
||||
SUMMARY:weekly stuff\r
|
||||
TRANSP:OPAQUE\r
|
||||
RECURRENCE-ID:20250520T090000\r
|
||||
DTSTART;TZID=Europe/Berlin:20250520T090000\r
|
||||
DTEND;TZID=Europe/Berlin:20250520T092500\r
|
||||
END:VEVENT\r\n",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn test_expand_recurrence() {
|
||||
let event = CalendarObject::from_ics(ICS.to_string(), None).unwrap();
|
||||
let crate::CalendarObjectComponent::Event(event, overrides) = event.get_data() else {
|
||||
panic!()
|
||||
};
|
||||
|
||||
let events: Vec<String> = event
|
||||
.expand_recurrence(None, None, overrides)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|event| Emitter::generate(&event))
|
||||
.collect();
|
||||
assert_eq!(events.as_slice()[0], EXPANDED[0]);
|
||||
assert_eq!(events.as_slice(), &EXPANDED);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
mod event;
|
||||
mod object;
|
||||
|
||||
pub use event::*;
|
||||
pub use object::*;
|
||||
@@ -1,331 +0,0 @@
|
||||
use super::EventObject;
|
||||
use crate::CalDateTime;
|
||||
use crate::Error;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use derive_more::Display;
|
||||
use ical::generator::{Emitter, IcalCalendar};
|
||||
use ical::parser::ical::component::IcalJournal;
|
||||
use ical::parser::ical::component::IcalTimeZone;
|
||||
use ical::parser::ical::component::IcalTodo;
|
||||
use ical::property::Property;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::HashMap, io::BufReader};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display)]
|
||||
// specified in https://datatracker.ietf.org/doc/html/rfc5545#section-3.6
|
||||
pub enum CalendarObjectType {
|
||||
#[serde(rename = "VEVENT")]
|
||||
Event = 0,
|
||||
#[serde(rename = "VTODO")]
|
||||
Todo = 1,
|
||||
#[serde(rename = "VJOURNAL")]
|
||||
Journal = 2,
|
||||
}
|
||||
|
||||
impl CalendarObjectType {
|
||||
#[must_use]
|
||||
pub const fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Event => "VEVENT",
|
||||
Self::Todo => "VTODO",
|
||||
Self::Journal => "VJOURNAL",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustical_xml::ValueSerialize for CalendarObjectType {
|
||||
fn serialize(&self) -> String {
|
||||
self.as_str().to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl rustical_xml::ValueDeserialize for CalendarObjectType {
|
||||
fn deserialize(val: &str) -> std::result::Result<Self, rustical_xml::XmlError> {
|
||||
match <String as rustical_xml::ValueDeserialize>::deserialize(val)?.as_str() {
|
||||
"VEVENT" => Ok(Self::Event),
|
||||
"VTODO" => Ok(Self::Todo),
|
||||
"VJOURNAL" => Ok(Self::Journal),
|
||||
_ => Err(rustical_xml::XmlError::InvalidValue(
|
||||
rustical_xml::ParseValueError::Other(format!(
|
||||
"Invalid value '{val}', must be VEVENT, VTODO, or VJOURNAL"
|
||||
)),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum CalendarObjectComponent {
|
||||
Event(EventObject, Vec<EventObject>),
|
||||
Todo(IcalTodo, Vec<IcalTodo>),
|
||||
Journal(IcalJournal, Vec<IcalJournal>),
|
||||
}
|
||||
|
||||
impl CalendarObjectComponent {
|
||||
#[must_use]
|
||||
pub fn get_uid(&self) -> &str {
|
||||
match &self {
|
||||
// We've made sure before that the first component exists and all components share the
|
||||
// same UID
|
||||
Self::Todo(todo, _) => todo.get_uid(),
|
||||
Self::Event(event, _) => event.event.get_uid(),
|
||||
Self::Journal(journal, _) => journal.get_uid(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&CalendarObjectComponent> for CalendarObjectType {
|
||||
fn from(value: &CalendarObjectComponent) -> Self {
|
||||
match value {
|
||||
CalendarObjectComponent::Event(..) => Self::Event,
|
||||
CalendarObjectComponent::Todo(..) => Self::Todo,
|
||||
CalendarObjectComponent::Journal(..) => Self::Journal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CalendarObjectComponent {
|
||||
fn from_events(mut events: Vec<EventObject>) -> Result<Self, Error> {
|
||||
let main_event = events
|
||||
.extract_if(.., |event| event.event.get_recurrence_id().is_none())
|
||||
.next()
|
||||
.expect("there must be one main event");
|
||||
let overrides = events;
|
||||
for event in &overrides {
|
||||
if event.get_uid() != main_event.get_uid() {
|
||||
return Err(Error::InvalidData(
|
||||
"Calendar object contains multiple UIDs".to_owned(),
|
||||
));
|
||||
}
|
||||
if event.event.get_recurrence_id().is_none() {
|
||||
return Err(Error::InvalidData(
|
||||
"Calendar object can only contain one main component".to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(Self::Event(main_event, overrides))
|
||||
}
|
||||
fn from_todos(mut todos: Vec<IcalTodo>) -> Result<Self, Error> {
|
||||
let main_todo = todos
|
||||
.extract_if(.., |todo| todo.get_recurrence_id().is_none())
|
||||
.next()
|
||||
.expect("there must be one main event");
|
||||
let overrides = todos;
|
||||
for todo in &overrides {
|
||||
if todo.get_uid() != main_todo.get_uid() {
|
||||
return Err(Error::InvalidData(
|
||||
"Calendar object contains multiple UIDs".to_owned(),
|
||||
));
|
||||
}
|
||||
if todo.get_recurrence_id().is_none() {
|
||||
return Err(Error::InvalidData(
|
||||
"Calendar object can only contain one main component".to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(Self::Todo(main_todo, overrides))
|
||||
}
|
||||
fn from_journals(mut journals: Vec<IcalJournal>) -> Result<Self, Error> {
|
||||
let main_journal = journals
|
||||
.extract_if(.., |journal| journal.get_recurrence_id().is_none())
|
||||
.next()
|
||||
.expect("there must be one main event");
|
||||
let overrides = journals;
|
||||
for journal in &overrides {
|
||||
if journal.get_uid() != main_journal.get_uid() {
|
||||
return Err(Error::InvalidData(
|
||||
"Calendar object contains multiple UIDs".to_owned(),
|
||||
));
|
||||
}
|
||||
if journal.get_recurrence_id().is_none() {
|
||||
return Err(Error::InvalidData(
|
||||
"Calendar object can only contain one main component".to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(Self::Journal(main_journal, overrides))
|
||||
}
|
||||
|
||||
pub fn get_first_occurence(&self) -> Result<Option<CalDateTime>, Error> {
|
||||
match &self {
|
||||
Self::Event(main_event, overrides) => Ok(overrides
|
||||
.iter()
|
||||
.chain(std::iter::once(main_event))
|
||||
.map(super::event::EventObject::get_dtstart)
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min()),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_last_occurence(&self) -> Result<Option<CalDateTime>, Error> {
|
||||
match &self {
|
||||
Self::Event(main_event, overrides) => Ok(overrides
|
||||
.iter()
|
||||
.chain(std::iter::once(main_event))
|
||||
.map(super::event::EventObject::get_last_occurence)
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.max()),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CalendarObject {
|
||||
data: CalendarObjectComponent,
|
||||
properties: Vec<Property>,
|
||||
id: String,
|
||||
ics: String,
|
||||
vtimezones: HashMap<String, IcalTimeZone>,
|
||||
}
|
||||
|
||||
impl CalendarObject {
|
||||
pub fn from_ics(ics: String, id: Option<String>) -> Result<Self, Error> {
|
||||
let mut parser = ical::IcalParser::new(BufReader::new(ics.as_bytes()));
|
||||
let cal = parser.next().ok_or(Error::MissingCalendar)??;
|
||||
if parser.next().is_some() {
|
||||
return Err(Error::InvalidData(
|
||||
"multiple calendars, only one allowed".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
if u8::from(!cal.events.is_empty())
|
||||
+ u8::from(!cal.todos.is_empty())
|
||||
+ u8::from(!cal.journals.is_empty())
|
||||
+ u8::from(!cal.free_busys.is_empty())
|
||||
!= 1
|
||||
{
|
||||
// https://datatracker.ietf.org/doc/html/rfc4791#section-4.1
|
||||
return Err(Error::InvalidData(
|
||||
"iCalendar object must have exactly one component type".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
let timezones: HashMap<String, Option<chrono_tz::Tz>> = cal
|
||||
.timezones
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|timezone| (timezone.get_tzid().to_owned(), (&timezone).try_into().ok()))
|
||||
.collect();
|
||||
|
||||
let vtimezones = cal
|
||||
.timezones
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|timezone| (timezone.get_tzid().to_owned(), timezone))
|
||||
.collect();
|
||||
|
||||
let data = if !cal.events.is_empty() {
|
||||
CalendarObjectComponent::from_events(
|
||||
cal.events
|
||||
.into_iter()
|
||||
.map(|event| EventObject {
|
||||
event,
|
||||
timezones: timezones.clone(),
|
||||
})
|
||||
.collect(),
|
||||
)?
|
||||
} else if !cal.todos.is_empty() {
|
||||
CalendarObjectComponent::from_todos(cal.todos)?
|
||||
} else if !cal.journals.is_empty() {
|
||||
CalendarObjectComponent::from_journals(cal.journals)?
|
||||
} else {
|
||||
return Err(Error::InvalidData(
|
||||
"iCalendar component type not supported :(".to_owned(),
|
||||
));
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
id: id.unwrap_or_else(|| data.get_uid().to_owned()),
|
||||
data,
|
||||
properties: cal.properties,
|
||||
ics,
|
||||
vtimezones,
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn get_vtimezones(&self) -> &HashMap<String, IcalTimeZone> {
|
||||
&self.vtimezones
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn get_data(&self) -> &CalendarObjectComponent {
|
||||
&self.data
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_uid(&self) -> &str {
|
||||
self.data.get_uid()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_etag(&self) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(self.get_uid());
|
||||
hasher.update(self.get_ics());
|
||||
format!("\"{:x}\"", hasher.finalize())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_ics(&self) -> &str {
|
||||
&self.ics
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_component_name(&self) -> &str {
|
||||
self.get_object_type().as_str()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_object_type(&self) -> CalendarObjectType {
|
||||
(&self.data).into()
|
||||
}
|
||||
|
||||
pub fn get_first_occurence(&self) -> Result<Option<CalDateTime>, Error> {
|
||||
self.data.get_first_occurence()
|
||||
}
|
||||
|
||||
pub fn get_last_occurence(&self) -> Result<Option<CalDateTime>, Error> {
|
||||
self.data.get_last_occurence()
|
||||
}
|
||||
|
||||
pub fn expand_recurrence(
|
||||
&self,
|
||||
start: Option<DateTime<Utc>>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
) -> Result<String, Error> {
|
||||
// Only events can be expanded
|
||||
match &self.data {
|
||||
CalendarObjectComponent::Event(main_event, overrides) => {
|
||||
let cal = IcalCalendar {
|
||||
properties: self.properties.clone(),
|
||||
events: main_event.expand_recurrence(start, end, overrides)?,
|
||||
..Default::default()
|
||||
};
|
||||
Ok(cal.generate())
|
||||
}
|
||||
_ => Ok(self.get_ics().to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_property(&self, name: &str) -> Option<&Property> {
|
||||
self.properties
|
||||
.iter()
|
||||
.find(|property| property.name == name)
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
|
||||
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]
|
||||
mod timestamp;
|
||||
mod timezone;
|
||||
use ical::parser::ParserError;
|
||||
pub use timestamp::*;
|
||||
pub use timezone::*;
|
||||
|
||||
mod icalendar;
|
||||
pub use icalendar::*;
|
||||
|
||||
mod error;
|
||||
pub use error::Error;
|
||||
mod calendar_object;
|
||||
pub use calendar_object::*;
|
||||
|
||||
mod address_object;
|
||||
pub use address_object::AddressObject;
|
||||
|
||||
pub type Error = ParserError;
|
||||
|
||||
@@ -1,35 +1,8 @@
|
||||
use super::timezone::ICalTimezone;
|
||||
use chrono::{DateTime, Datelike, Duration, Local, NaiveDate, NaiveDateTime, NaiveTime, Utc};
|
||||
use chrono_tz::Tz;
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
use derive_more::derive::Deref;
|
||||
use ical::property::Property;
|
||||
use rustical_xml::{ValueDeserialize, ValueSerialize};
|
||||
use std::{borrow::Cow, collections::HashMap, ops::Add, sync::LazyLock};
|
||||
|
||||
static RE_VCARD_DATE_MM_DD: LazyLock<regex::Regex> =
|
||||
LazyLock::new(|| regex::Regex::new(r"^--(?<m>\d{2})(?<d>\d{2})$").unwrap());
|
||||
|
||||
const LOCAL_DATE_TIME: &str = "%Y%m%dT%H%M%S";
|
||||
const UTC_DATE_TIME: &str = "%Y%m%dT%H%M%SZ";
|
||||
pub const LOCAL_DATE: &str = "%Y%m%d";
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum CalDateTimeError {
|
||||
#[error(
|
||||
"Timezone has X-LIC-LOCATION property to specify a timezone from the Olson database, however its value {0} is invalid"
|
||||
)]
|
||||
InvalidOlson(String),
|
||||
#[error("TZID {0} does not refer to a valid timezone")]
|
||||
InvalidTZID(String),
|
||||
#[error("Timestamp doesn't exist because of gap in local time")]
|
||||
LocalTimeGap,
|
||||
#[error("Datetime string {0} has an invalid format")]
|
||||
InvalidDatetimeFormat(String),
|
||||
#[error("Could not parse datetime {0}")]
|
||||
ParseError(String),
|
||||
#[error("Duration string {0} has an invalid format")]
|
||||
InvalidDurationFormat(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deref, PartialEq, Eq, Hash)]
|
||||
pub struct UtcDateTime(pub DateTime<Utc>);
|
||||
@@ -54,367 +27,3 @@ impl ValueSerialize for UtcDateTime {
|
||||
format!("{}", self.0.format(UTC_DATE_TIME))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CalDateTime {
|
||||
// Form 1, example: 19980118T230000 -> Local
|
||||
// Form 2, example: 19980119T070000Z -> UTC
|
||||
// Form 3, example: TZID=America/New_York:19980119T020000 -> Olson
|
||||
// https://en.wikipedia.org/wiki/Tz_database
|
||||
DateTime(DateTime<ICalTimezone>),
|
||||
Date(NaiveDate, ICalTimezone),
|
||||
}
|
||||
|
||||
impl From<CalDateTime> for DateTime<rrule::Tz> {
|
||||
fn from(value: CalDateTime) -> Self {
|
||||
value
|
||||
.as_datetime()
|
||||
.into_owned()
|
||||
.with_timezone(&value.timezone().into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DateTime<rrule::Tz>> for CalDateTime {
|
||||
fn from(value: DateTime<rrule::Tz>) -> Self {
|
||||
Self::DateTime(value.with_timezone(&value.timezone().into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for CalDateTime {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for CalDateTime {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
match (&self, &other) {
|
||||
(Self::DateTime(a), Self::DateTime(b)) => a.cmp(b),
|
||||
(Self::DateTime(a), Self::Date(..)) => a.cmp(&other.as_datetime()),
|
||||
(Self::Date(..), Self::DateTime(b)) => self.as_datetime().as_ref().cmp(b),
|
||||
(Self::Date(..), Self::Date(..)) => self.as_datetime().cmp(&other.as_datetime()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DateTime<Local>> for CalDateTime {
|
||||
fn from(value: DateTime<Local>) -> Self {
|
||||
Self::DateTime(value.with_timezone(&ICalTimezone::Local))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DateTime<Utc>> for CalDateTime {
|
||||
fn from(value: DateTime<Utc>) -> Self {
|
||||
Self::DateTime(value.with_timezone(&ICalTimezone::Olson(chrono_tz::UTC)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Add<Duration> for CalDateTime {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, duration: Duration) -> Self::Output {
|
||||
match self {
|
||||
Self::DateTime(datetime) => Self::DateTime(datetime + duration),
|
||||
Self::Date(date, tz) => Self::DateTime(
|
||||
date.and_time(NaiveTime::default())
|
||||
.and_local_timezone(tz)
|
||||
.earliest()
|
||||
.expect("Local timezone has constant offset")
|
||||
+ duration,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CalDateTime {
|
||||
pub fn parse_prop(
|
||||
prop: &Property,
|
||||
timezones: &HashMap<String, Option<chrono_tz::Tz>>,
|
||||
) -> Result<Self, CalDateTimeError> {
|
||||
let prop_value = prop
|
||||
.value
|
||||
.as_ref()
|
||||
.ok_or_else(|| CalDateTimeError::InvalidDatetimeFormat("empty property".into()))?;
|
||||
|
||||
let timezone = if let Some(tzid) = prop.get_param("TZID") {
|
||||
if let Some(timezone) = timezones.get(tzid) {
|
||||
timezone.to_owned()
|
||||
} else {
|
||||
// TZID refers to timezone that does not exist
|
||||
return Err(CalDateTimeError::InvalidTZID(tzid.to_string()));
|
||||
}
|
||||
} else {
|
||||
// No explicit timezone specified.
|
||||
// This is valid and will be localtime or UTC depending on the value
|
||||
// We will stick to this default as documented in https://github.com/lennart-k/rustical/issues/102
|
||||
None
|
||||
};
|
||||
|
||||
Self::parse(prop_value, timezone)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn format(&self) -> String {
|
||||
match self {
|
||||
Self::DateTime(datetime) => match datetime.timezone() {
|
||||
ICalTimezone::Olson(chrono_tz::UTC) => datetime.format(UTC_DATE_TIME).to_string(),
|
||||
_ => datetime.format(LOCAL_DATE_TIME).to_string(),
|
||||
},
|
||||
Self::Date(date, _) => date.format(LOCAL_DATE).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn format_date(&self) -> String {
|
||||
match self {
|
||||
Self::DateTime(datetime) => datetime.format(LOCAL_DATE).to_string(),
|
||||
Self::Date(date, _) => date.format(LOCAL_DATE).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn date(&self) -> NaiveDate {
|
||||
match self {
|
||||
Self::DateTime(datetime) => datetime.date_naive(),
|
||||
Self::Date(date, _) => date.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn is_date(&self) -> bool {
|
||||
matches!(&self, Self::Date(_, _))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn as_datetime(&self) -> Cow<'_, DateTime<ICalTimezone>> {
|
||||
match self {
|
||||
Self::DateTime(datetime) => Cow::Borrowed(datetime),
|
||||
Self::Date(date, tz) => Cow::Owned(
|
||||
date.and_time(NaiveTime::default())
|
||||
.and_local_timezone(tz.to_owned())
|
||||
.earliest()
|
||||
.expect("Midnight always exists"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str, timezone: Option<Tz>) -> Result<Self, CalDateTimeError> {
|
||||
if let Ok(datetime) = NaiveDateTime::parse_from_str(value, LOCAL_DATE_TIME) {
|
||||
if let Some(timezone) = timezone {
|
||||
return Ok(Self::DateTime(
|
||||
datetime
|
||||
.and_local_timezone(timezone.into())
|
||||
.earliest()
|
||||
.ok_or(CalDateTimeError::LocalTimeGap)?,
|
||||
));
|
||||
}
|
||||
return Ok(Self::DateTime(
|
||||
datetime
|
||||
.and_local_timezone(ICalTimezone::Local)
|
||||
.earliest()
|
||||
.ok_or(CalDateTimeError::LocalTimeGap)?,
|
||||
));
|
||||
}
|
||||
|
||||
if let Ok(datetime) = NaiveDateTime::parse_from_str(value, UTC_DATE_TIME) {
|
||||
return Ok(datetime.and_utc().into());
|
||||
}
|
||||
let timezone = timezone.map_or(ICalTimezone::Local, ICalTimezone::Olson);
|
||||
if let Ok(date) = NaiveDate::parse_from_str(value, LOCAL_DATE) {
|
||||
return Ok(Self::Date(date, timezone));
|
||||
}
|
||||
|
||||
if let Ok(date) = NaiveDate::parse_from_str(value, "%Y-%m-%d") {
|
||||
return Ok(Self::Date(date, timezone));
|
||||
}
|
||||
if let Ok(date) = NaiveDate::parse_from_str(value, "%Y%m%d") {
|
||||
return Ok(Self::Date(date, timezone));
|
||||
}
|
||||
|
||||
Err(CalDateTimeError::InvalidDatetimeFormat(value.to_string()))
|
||||
}
|
||||
|
||||
// Also returns whether the date contains a year
|
||||
pub fn parse_vcard(value: &str) -> Result<(Self, bool), CalDateTimeError> {
|
||||
if let Ok(datetime) = Self::parse(value, None) {
|
||||
return Ok((datetime, true));
|
||||
}
|
||||
|
||||
if let Some(captures) = RE_VCARD_DATE_MM_DD.captures(value) {
|
||||
// Because 1972 is a leap year
|
||||
let year = 1972;
|
||||
// Cannot fail because of the regex
|
||||
let month = captures.name("m").unwrap().as_str().parse().ok().unwrap();
|
||||
let day = captures.name("d").unwrap().as_str().parse().ok().unwrap();
|
||||
|
||||
return Ok((
|
||||
Self::Date(
|
||||
NaiveDate::from_ymd_opt(year, month, day)
|
||||
.ok_or_else(|| CalDateTimeError::ParseError(value.to_string()))?,
|
||||
ICalTimezone::Local,
|
||||
),
|
||||
false,
|
||||
));
|
||||
}
|
||||
Err(CalDateTimeError::InvalidDatetimeFormat(value.to_string()))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn utc(&self) -> DateTime<Utc> {
|
||||
self.as_datetime().to_utc()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn timezone(&self) -> ICalTimezone {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.timezone(),
|
||||
Self::Date(_, tz) => tz.to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CalDateTime> for DateTime<Utc> {
|
||||
fn from(value: CalDateTime) -> Self {
|
||||
value.utc()
|
||||
}
|
||||
}
|
||||
|
||||
impl Datelike for CalDateTime {
|
||||
fn year(&self) -> i32 {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.year(),
|
||||
Self::Date(date, _) => date.year(),
|
||||
}
|
||||
}
|
||||
fn month(&self) -> u32 {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.month(),
|
||||
Self::Date(date, _) => date.month(),
|
||||
}
|
||||
}
|
||||
|
||||
fn month0(&self) -> u32 {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.month0(),
|
||||
Self::Date(date, _) => date.month0(),
|
||||
}
|
||||
}
|
||||
fn day(&self) -> u32 {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.day(),
|
||||
Self::Date(date, _) => date.day(),
|
||||
}
|
||||
}
|
||||
fn day0(&self) -> u32 {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.day0(),
|
||||
Self::Date(date, _) => date.day0(),
|
||||
}
|
||||
}
|
||||
fn ordinal(&self) -> u32 {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.ordinal(),
|
||||
Self::Date(date, _) => date.ordinal(),
|
||||
}
|
||||
}
|
||||
fn ordinal0(&self) -> u32 {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.ordinal0(),
|
||||
Self::Date(date, _) => date.ordinal0(),
|
||||
}
|
||||
}
|
||||
fn weekday(&self) -> chrono::Weekday {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.weekday(),
|
||||
Self::Date(date, _) => date.weekday(),
|
||||
}
|
||||
}
|
||||
fn iso_week(&self) -> chrono::IsoWeek {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => datetime.iso_week(),
|
||||
Self::Date(date, _) => date.iso_week(),
|
||||
}
|
||||
}
|
||||
fn with_year(&self, year: i32) -> Option<Self> {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => Some(Self::DateTime(datetime.with_year(year)?)),
|
||||
Self::Date(date, tz) => Some(Self::Date(date.with_year(year)?, tz.to_owned())),
|
||||
}
|
||||
}
|
||||
fn with_month(&self, month: u32) -> Option<Self> {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => Some(Self::DateTime(datetime.with_month(month)?)),
|
||||
Self::Date(date, tz) => Some(Self::Date(date.with_month(month)?, tz.to_owned())),
|
||||
}
|
||||
}
|
||||
fn with_month0(&self, month0: u32) -> Option<Self> {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => Some(Self::DateTime(datetime.with_month0(month0)?)),
|
||||
Self::Date(date, tz) => Some(Self::Date(date.with_month0(month0)?, tz.to_owned())),
|
||||
}
|
||||
}
|
||||
fn with_day(&self, day: u32) -> Option<Self> {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => Some(Self::DateTime(datetime.with_day(day)?)),
|
||||
Self::Date(date, tz) => Some(Self::Date(date.with_day(day)?, tz.to_owned())),
|
||||
}
|
||||
}
|
||||
fn with_day0(&self, day0: u32) -> Option<Self> {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => Some(Self::DateTime(datetime.with_day0(day0)?)),
|
||||
Self::Date(date, tz) => Some(Self::Date(date.with_day0(day0)?, tz.to_owned())),
|
||||
}
|
||||
}
|
||||
fn with_ordinal(&self, ordinal: u32) -> Option<Self> {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => Some(Self::DateTime(datetime.with_ordinal(ordinal)?)),
|
||||
Self::Date(date, tz) => Some(Self::Date(date.with_ordinal(ordinal)?, tz.to_owned())),
|
||||
}
|
||||
}
|
||||
fn with_ordinal0(&self, ordinal0: u32) -> Option<Self> {
|
||||
match &self {
|
||||
Self::DateTime(datetime) => Some(Self::DateTime(datetime.with_ordinal0(ordinal0)?)),
|
||||
Self::Date(date, tz) => Some(Self::Date(date.with_ordinal0(ordinal0)?, tz.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::CalDateTime;
|
||||
use chrono::NaiveDate;
|
||||
|
||||
#[test]
|
||||
fn test_vcard_date() {
|
||||
assert_eq!(
|
||||
CalDateTime::parse_vcard("19850412").unwrap(),
|
||||
(
|
||||
CalDateTime::Date(
|
||||
NaiveDate::from_ymd_opt(1985, 4, 12).unwrap(),
|
||||
crate::ICalTimezone::Local
|
||||
),
|
||||
true
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
CalDateTime::parse_vcard("1985-04-12").unwrap(),
|
||||
(
|
||||
CalDateTime::Date(
|
||||
NaiveDate::from_ymd_opt(1985, 4, 12).unwrap(),
|
||||
crate::ICalTimezone::Local
|
||||
),
|
||||
true
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
CalDateTime::parse_vcard("--0412").unwrap(),
|
||||
(
|
||||
CalDateTime::Date(
|
||||
NaiveDate::from_ymd_opt(1972, 4, 12).unwrap(),
|
||||
crate::ICalTimezone::Local
|
||||
),
|
||||
false
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
use chrono::{Local, NaiveDate, NaiveDateTime, TimeZone};
|
||||
use chrono_tz::Tz;
|
||||
use derive_more::{Display, From};
|
||||
|
||||
#[derive(Debug, Clone, From, PartialEq, Eq)]
|
||||
pub enum ICalTimezone {
|
||||
Local,
|
||||
Olson(Tz),
|
||||
}
|
||||
|
||||
impl From<ICalTimezone> for rrule::Tz {
|
||||
fn from(value: ICalTimezone) -> Self {
|
||||
match value {
|
||||
ICalTimezone::Local => Self::LOCAL,
|
||||
ICalTimezone::Olson(tz) => Self::Tz(tz),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<rrule::Tz> for ICalTimezone {
|
||||
fn from(value: rrule::Tz) -> Self {
|
||||
match value {
|
||||
rrule::Tz::Local(_) => Self::Local,
|
||||
rrule::Tz::Tz(tz) => Self::Olson(tz),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Display)]
|
||||
pub enum CalTimezoneOffset {
|
||||
Local(chrono::FixedOffset),
|
||||
Olson(chrono_tz::TzOffset),
|
||||
}
|
||||
|
||||
impl chrono::Offset for CalTimezoneOffset {
|
||||
fn fix(&self) -> chrono::FixedOffset {
|
||||
match self {
|
||||
Self::Local(local) => local.fix(),
|
||||
Self::Olson(olson) => olson.fix(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TimeZone for ICalTimezone {
|
||||
type Offset = CalTimezoneOffset;
|
||||
|
||||
fn from_offset(offset: &Self::Offset) -> Self {
|
||||
match offset {
|
||||
CalTimezoneOffset::Local(_) => Self::Local,
|
||||
CalTimezoneOffset::Olson(offset) => Self::Olson(Tz::from_offset(offset)),
|
||||
}
|
||||
}
|
||||
|
||||
fn offset_from_local_date(&self, local: &NaiveDate) -> chrono::MappedLocalTime<Self::Offset> {
|
||||
match self {
|
||||
Self::Local => Local
|
||||
.offset_from_local_date(local)
|
||||
.map(CalTimezoneOffset::Local),
|
||||
Self::Olson(tz) => tz
|
||||
.offset_from_local_date(local)
|
||||
.map(CalTimezoneOffset::Olson),
|
||||
}
|
||||
}
|
||||
|
||||
fn offset_from_local_datetime(
|
||||
&self,
|
||||
local: &NaiveDateTime,
|
||||
) -> chrono::MappedLocalTime<Self::Offset> {
|
||||
match self {
|
||||
Self::Local => Local
|
||||
.offset_from_local_datetime(local)
|
||||
.map(CalTimezoneOffset::Local),
|
||||
Self::Olson(tz) => tz
|
||||
.offset_from_local_datetime(local)
|
||||
.map(CalTimezoneOffset::Olson),
|
||||
}
|
||||
}
|
||||
|
||||
fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
|
||||
match self {
|
||||
Self::Local => CalTimezoneOffset::Local(Local.offset_from_utc_datetime(utc)),
|
||||
Self::Olson(tz) => CalTimezoneOffset::Olson(tz.offset_from_utc_datetime(utc)),
|
||||
}
|
||||
}
|
||||
|
||||
fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset {
|
||||
match self {
|
||||
Self::Local => CalTimezoneOffset::Local(Local.offset_from_utc_date(utc)),
|
||||
Self::Olson(tz) => CalTimezoneOffset::Olson(tz.offset_from_utc_date(utc)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,6 @@ END:VCALENDAR
|
||||
|
||||
#[test]
|
||||
fn parse_calendar_object() {
|
||||
let object = CalendarObject::from_ics(MULTI_VEVENT.to_string(), None).unwrap();
|
||||
object.expand_recurrence(None, None).unwrap();
|
||||
let object = CalendarObject::from_ics(MULTI_VEVENT.to_string()).unwrap();
|
||||
object.get_inner().expand_recurrence(None, None);
|
||||
}
|
||||
|
||||
@@ -5,10 +5,11 @@ use axum::{
|
||||
extract::Query,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
};
|
||||
use axum_extra::extract::Host;
|
||||
use axum_extra::TypedHeader;
|
||||
pub use config::OidcConfig;
|
||||
use config::UserIdClaim;
|
||||
use error::OidcError;
|
||||
use headers::Host;
|
||||
use openidconnect::{
|
||||
AuthenticationFlow, AuthorizationCode, CsrfToken, EndpointMaybeSet, EndpointNotSet,
|
||||
EndpointSet, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, PkceCodeVerifier,
|
||||
@@ -100,7 +101,7 @@ pub struct GetOidcForm {
|
||||
pub async fn route_post_oidc(
|
||||
Extension(oidc_config): Extension<OidcConfig>,
|
||||
session: Session,
|
||||
Host(host): Host,
|
||||
TypedHeader(host): TypedHeader<Host>,
|
||||
Form(GetOidcForm { redirect_uri }): Form<GetOidcForm>,
|
||||
) -> Result<Response, OidcError> {
|
||||
let callback_uri = format!("https://{host}/frontend/login/oidc/callback");
|
||||
@@ -155,7 +156,7 @@ pub async fn route_get_oidc_callback<US: UserStore + Clone>(
|
||||
Extension(service_config): Extension<OidcServiceConfig>,
|
||||
session: Session,
|
||||
Query(AuthCallbackQuery { code, iss, state }): Query<AuthCallbackQuery>,
|
||||
Host(host): Host,
|
||||
TypedHeader(host): TypedHeader<Host>,
|
||||
) -> Result<Response, OidcError> {
|
||||
let callback_uri = format!("https://{host}/frontend/login/oidc/callback");
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ pub trait AddressbookStore: Send + Sync + 'static {
|
||||
|
||||
async fn update_addressbook(
|
||||
&self,
|
||||
principal: String,
|
||||
id: String,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
addressbook: Addressbook,
|
||||
) -> Result<(), Error>;
|
||||
async fn insert_addressbook(&self, addressbook: Addressbook) -> Result<(), Error>;
|
||||
@@ -33,7 +33,7 @@ pub trait AddressbookStore: Send + Sync + 'static {
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<AddressObject>, Vec<String>, i64), Error>;
|
||||
) -> Result<(Vec<(String, AddressObject)>, Vec<String>, i64), Error>;
|
||||
|
||||
async fn addressbook_metadata(
|
||||
&self,
|
||||
@@ -45,7 +45,7 @@ pub trait AddressbookStore: Send + Sync + 'static {
|
||||
&self,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
) -> Result<Vec<AddressObject>, Error>;
|
||||
) -> Result<Vec<(String, AddressObject)>, Error>;
|
||||
async fn get_object(
|
||||
&self,
|
||||
principal: &str,
|
||||
@@ -55,8 +55,9 @@ pub trait AddressbookStore: Send + Sync + 'static {
|
||||
) -> Result<AddressObject, Error>;
|
||||
async fn put_object(
|
||||
&self,
|
||||
principal: String,
|
||||
addressbook_id: String,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
object_id: &str,
|
||||
object: AddressObject,
|
||||
overwrite: bool,
|
||||
) -> Result<(), Error>;
|
||||
@@ -77,7 +78,7 @@ pub trait AddressbookStore: Send + Sync + 'static {
|
||||
async fn import_addressbook(
|
||||
&self,
|
||||
addressbook: Addressbook,
|
||||
objects: Vec<AddressObject>,
|
||||
objects: Vec<(String, AddressObject)>,
|
||||
merge_existing: bool,
|
||||
) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ pub trait CalendarStore: Send + Sync + 'static {
|
||||
|
||||
async fn update_calendar(
|
||||
&self,
|
||||
principal: String,
|
||||
id: String,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
calendar: Calendar,
|
||||
) -> Result<(), Error>;
|
||||
async fn insert_calendar(&self, calendar: Calendar) -> Result<(), Error>;
|
||||
@@ -46,7 +46,7 @@ pub trait CalendarStore: Send + Sync + 'static {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error>;
|
||||
) -> Result<(Vec<(String, CalendarObject)>, Vec<String>, i64), Error>;
|
||||
|
||||
/// Since the <calendar-query> rules are rather complex this function
|
||||
/// is only meant to do some prefiltering
|
||||
@@ -55,7 +55,7 @@ pub trait CalendarStore: Send + Sync + 'static {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
_query: CalendarQuery,
|
||||
) -> Result<Vec<CalendarObject>, Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error> {
|
||||
self.get_objects(principal, cal_id).await
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ pub trait CalendarStore: Send + Sync + 'static {
|
||||
&self,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
) -> Result<Vec<CalendarObject>, Error>;
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error>;
|
||||
async fn get_object(
|
||||
&self,
|
||||
principal: &str,
|
||||
@@ -77,13 +77,29 @@ pub trait CalendarStore: Send + Sync + 'static {
|
||||
object_id: &str,
|
||||
show_deleted: bool,
|
||||
) -> Result<CalendarObject, Error>;
|
||||
async fn put_object(
|
||||
async fn put_objects(
|
||||
&self,
|
||||
principal: String,
|
||||
cal_id: String,
|
||||
object: CalendarObject,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
objects: Vec<(String, CalendarObject)>,
|
||||
overwrite: bool,
|
||||
) -> Result<(), Error>;
|
||||
async fn put_object(
|
||||
&self,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
object_id: &str,
|
||||
object: CalendarObject,
|
||||
overwrite: bool,
|
||||
) -> Result<(), Error> {
|
||||
self.put_objects(
|
||||
principal,
|
||||
cal_id,
|
||||
vec![(object_id.to_owned(), object)],
|
||||
overwrite,
|
||||
)
|
||||
.await
|
||||
}
|
||||
async fn delete_object(
|
||||
&self,
|
||||
principal: &str,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::CalendarStore;
|
||||
use crate::{Calendar, CalendarStore, calendar_store::CalendarQuery};
|
||||
use async_trait::async_trait;
|
||||
use rustical_ical::CalendarObject;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
pub trait PrefixedCalendarStore: CalendarStore {
|
||||
@@ -51,11 +52,11 @@ impl CalendarStore for CombinedCalendarStore {
|
||||
|
||||
async fn update_calendar(
|
||||
&self,
|
||||
principal: String,
|
||||
id: String,
|
||||
calendar: crate::Calendar,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
calendar: Calendar,
|
||||
) -> Result<(), crate::Error> {
|
||||
self.store_for_id(&id)
|
||||
self.store_for_id(id)
|
||||
.update_calendar(principal, id, calendar)
|
||||
.await
|
||||
}
|
||||
@@ -88,7 +89,7 @@ impl CalendarStore for CombinedCalendarStore {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<rustical_ical::CalendarObject>, Vec<String>, i64), crate::Error> {
|
||||
) -> Result<(Vec<(String, CalendarObject)>, Vec<String>, i64), crate::Error> {
|
||||
self.store_for_id(cal_id)
|
||||
.sync_changes(principal, cal_id, synctoken)
|
||||
.await
|
||||
@@ -97,7 +98,7 @@ impl CalendarStore for CombinedCalendarStore {
|
||||
async fn import_calendar(
|
||||
&self,
|
||||
calendar: crate::Calendar,
|
||||
objects: Vec<rustical_ical::CalendarObject>,
|
||||
objects: Vec<CalendarObject>,
|
||||
merge_existing: bool,
|
||||
) -> Result<(), crate::Error> {
|
||||
self.store_for_id(&calendar.id)
|
||||
@@ -109,8 +110,8 @@ impl CalendarStore for CombinedCalendarStore {
|
||||
&self,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
query: crate::calendar_store::CalendarQuery,
|
||||
) -> Result<Vec<rustical_ical::CalendarObject>, crate::Error> {
|
||||
query: CalendarQuery,
|
||||
) -> Result<Vec<(String, CalendarObject)>, crate::Error> {
|
||||
self.store_for_id(cal_id)
|
||||
.calendar_query(principal, cal_id, query)
|
||||
.await
|
||||
@@ -141,21 +142,21 @@ impl CalendarStore for CombinedCalendarStore {
|
||||
&self,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
) -> Result<Vec<rustical_ical::CalendarObject>, crate::Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, crate::Error> {
|
||||
self.store_for_id(cal_id)
|
||||
.get_objects(principal, cal_id)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn put_object(
|
||||
async fn put_objects(
|
||||
&self,
|
||||
principal: String,
|
||||
cal_id: String,
|
||||
object: rustical_ical::CalendarObject,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
objects: Vec<(String, CalendarObject)>,
|
||||
overwrite: bool,
|
||||
) -> Result<(), crate::Error> {
|
||||
self.store_for_id(&cal_id)
|
||||
.put_object(principal, cal_id, object, overwrite)
|
||||
self.store_for_id(cal_id)
|
||||
.put_objects(principal, cal_id, objects, overwrite)
|
||||
.await
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ pub enum Error {
|
||||
Other(#[from] anyhow::Error),
|
||||
|
||||
#[error(transparent)]
|
||||
IcalError(#[from] rustical_ical::Error),
|
||||
IcalError(#[from] ical::parser::ParserError),
|
||||
}
|
||||
|
||||
impl Error {
|
||||
@@ -36,7 +36,8 @@ impl Error {
|
||||
Self::NotFound => StatusCode::NOT_FOUND,
|
||||
Self::AlreadyExists => StatusCode::CONFLICT,
|
||||
Self::ReadOnly => StatusCode::FORBIDDEN,
|
||||
Self::IcalError(err) => err.status_code(),
|
||||
// TODO: Can also be Bad Request, depending on when this is raised
|
||||
Self::IcalError(_err) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::InvalidPrincipalType(_) => StatusCode::BAD_REQUEST,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
|
||||
@@ -11,10 +11,16 @@ publish = false
|
||||
[features]
|
||||
test = ["dep:rstest"]
|
||||
|
||||
[[bench]]
|
||||
name = "insert_calendar_object"
|
||||
harness = false
|
||||
|
||||
[dev-dependencies]
|
||||
rstest.workspace = true
|
||||
criterion.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ical.workspace = true
|
||||
tokio.workspace = true
|
||||
rustical_store.workspace = true
|
||||
async-trait.workspace = true
|
||||
@@ -31,3 +37,4 @@ pbkdf2.workspace = true
|
||||
rustical_ical.workspace = true
|
||||
rstest = { workspace = true, optional = true }
|
||||
sha2.workspace = true
|
||||
regex.workspace = true
|
||||
|
||||
47
crates/store_sqlite/benches/ical_event.ics
Normal file
47
crates/store_sqlite/benches/ical_event.ics
Normal file
@@ -0,0 +1,47 @@
|
||||
BEGIN:VCALENDAR
|
||||
CALSCALE:GREGORIAN
|
||||
PRODID:-//Ximian//NONSGML Evolution Calendar//EN
|
||||
VERSION:2.0
|
||||
|
||||
BEGIN:VTIMEZONE
|
||||
TZID:Europe/Berlin
|
||||
X-LIC-LOCATION:Europe/Berlin
|
||||
BEGIN:DAYLIGHT
|
||||
TZNAME:CEST
|
||||
TZOFFSETFROM:+0100
|
||||
TZOFFSETTO:+0200
|
||||
DTSTART:19810329T020000
|
||||
RRULE:FREQ=YEARLY;UNTIL=20370329T010000Z;BYDAY=-1SU;BYMONTH=3
|
||||
END:DAYLIGHT
|
||||
BEGIN:STANDARD
|
||||
TZNAME:CET
|
||||
TZOFFSETFROM:+0200
|
||||
TZOFFSETTO:+0100
|
||||
DTSTART:19961027T030000
|
||||
RRULE:FREQ=YEARLY;UNTIL=20361026T010000Z;BYDAY=-1SU;BYMONTH=10
|
||||
END:STANDARD
|
||||
END:VTIMEZONE
|
||||
|
||||
|
||||
BEGIN:VEVENT
|
||||
UID:fa915b604e6e3f36772501ff869439e6a3c5cf67
|
||||
DTSTAMP:20250726T112617Z
|
||||
DTSTART;VALUE=DATE:20250806
|
||||
DTEND;VALUE=DATE:20250807
|
||||
SEQUENCE:2
|
||||
SUMMARY:all day event
|
||||
TRANSP:OPAQUE
|
||||
CLASS:PUBLIC
|
||||
CREATED:20250726T144426Z
|
||||
LAST-MODIFIED:20250726T144426Z
|
||||
BEGIN:VALARM
|
||||
TRIGGER:-PT30M
|
||||
REPEAT:2
|
||||
DURATION:PT15M
|
||||
ACTION:DISPLAY
|
||||
DESCRIPTION:Breakfast meeting with executive\n
|
||||
team at 8:30 AM EST.
|
||||
END:VALARM
|
||||
END:VEVENT
|
||||
|
||||
END:VCALENDAR
|
||||
73
crates/store_sqlite/benches/insert_calendar_object.rs
Normal file
73
crates/store_sqlite/benches/insert_calendar_object.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use rustical_ical::{CalendarObject, CalendarObjectType};
|
||||
use rustical_store::{Calendar, CalendarMetadata, CalendarStore};
|
||||
use rustical_store_sqlite::tests::test_store_context;
|
||||
|
||||
fn benchmark(c: &mut Criterion) {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let cal_store = runtime.block_on(async {
|
||||
let cal_store = test_store_context().await.cal_store;
|
||||
|
||||
cal_store
|
||||
.insert_calendar(Calendar {
|
||||
meta: CalendarMetadata {
|
||||
displayname: Some("Yeet".to_owned()),
|
||||
order: 0,
|
||||
description: None,
|
||||
color: None,
|
||||
},
|
||||
principal: "user".to_owned(),
|
||||
id: "okwow".to_owned(),
|
||||
timezone_id: None,
|
||||
deleted_at: None,
|
||||
synctoken: 0,
|
||||
subscription_url: None,
|
||||
push_topic: "asd".to_owned(),
|
||||
components: vec![
|
||||
CalendarObjectType::Event,
|
||||
CalendarObjectType::Todo,
|
||||
CalendarObjectType::Journal,
|
||||
],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
cal_store
|
||||
});
|
||||
|
||||
let row = (
|
||||
"asd".to_owned(),
|
||||
CalendarObject::from_ics(include_str!("ical_event.ics").to_owned()).unwrap(),
|
||||
);
|
||||
|
||||
let batch_size = 1000;
|
||||
let objects: Vec<_> = std::iter::repeat_n(row.clone(), batch_size).collect();
|
||||
|
||||
c.bench_function("put_batch", |b| {
|
||||
b.to_async(&runtime).iter(async || {
|
||||
// yeet
|
||||
cal_store
|
||||
.put_objects("user", "okwow", objects.clone(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
});
|
||||
|
||||
c.bench_function("put_single", |b| {
|
||||
b.to_async(&runtime).iter(async || {
|
||||
// yeet
|
||||
for _ in 0..1000 {
|
||||
cal_store
|
||||
.put_object("user", "okwow", &row.0, row.1.clone(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
runtime
|
||||
.block_on(cal_store.delete_calendar("user", "okwow", false))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
criterion_group!(benches, benchmark);
|
||||
criterion_main!(benches);
|
||||
@@ -1,14 +1,13 @@
|
||||
use crate::addressbook_store::SqliteAddressbookStore;
|
||||
use async_trait::async_trait;
|
||||
use chrono::NaiveDateTime;
|
||||
use rustical_ical::{AddressObject, CalendarObject, CalendarObjectType};
|
||||
use rustical_ical::{CalendarObject, CalendarObjectType};
|
||||
use rustical_store::{
|
||||
Addressbook, AddressbookStore, Calendar, CalendarMetadata, CalendarStore, CollectionMetadata,
|
||||
Error, PrefixedCalendarStore,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::{Executor, Sqlite};
|
||||
use std::collections::HashMap;
|
||||
use tracing::instrument;
|
||||
|
||||
pub const BIRTHDAYS_PREFIX: &str = "_birthdays_";
|
||||
@@ -269,17 +268,18 @@ impl CalendarStore for SqliteAddressbookStore {
|
||||
#[instrument]
|
||||
async fn update_calendar(
|
||||
&self,
|
||||
principal: String,
|
||||
id: String,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
mut calendar: Calendar,
|
||||
) -> Result<(), Error> {
|
||||
assert_eq!(principal, calendar.principal);
|
||||
assert_eq!(id, calendar.id);
|
||||
calendar.id = calendar
|
||||
.id
|
||||
.strip_prefix(BIRTHDAYS_PREFIX)
|
||||
.ok_or(Error::NotFound)?
|
||||
.to_string();
|
||||
Self::_update_birthday_calendar(&self.db, &principal, &calendar).await
|
||||
Self::_update_birthday_calendar(&self.db, principal, &calendar).await
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
@@ -324,19 +324,35 @@ impl CalendarStore for SqliteAddressbookStore {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error> {
|
||||
) -> Result<(Vec<(String, CalendarObject)>, Vec<String>, i64), Error> {
|
||||
let cal_id = cal_id
|
||||
.strip_prefix(BIRTHDAYS_PREFIX)
|
||||
.ok_or(Error::NotFound)?;
|
||||
let (objects, deleted_objects, new_synctoken) =
|
||||
AddressbookStore::sync_changes(self, principal, cal_id, synctoken).await?;
|
||||
let objects: Result<Vec<Option<CalendarObject>>, rustical_ical::Error> = objects
|
||||
.iter()
|
||||
.map(AddressObject::get_birthday_object)
|
||||
.collect();
|
||||
let objects = objects?.into_iter().flatten().collect();
|
||||
|
||||
Ok((objects, deleted_objects, new_synctoken))
|
||||
let mut out_objects = vec![];
|
||||
|
||||
for (object_id, object) in objects {
|
||||
if let Some(birthday) = object.get_birthday_object()? {
|
||||
out_objects.push((format!("{object_id}-birthday"), birthday));
|
||||
}
|
||||
if let Some(anniversary) = object.get_anniversary_object()? {
|
||||
out_objects.push((format!("{object_id}-anniversayr"), anniversary));
|
||||
}
|
||||
}
|
||||
|
||||
let deleted_objects = deleted_objects
|
||||
.into_iter()
|
||||
.flat_map(|object_id| {
|
||||
[
|
||||
format!("{object_id}-birthday"),
|
||||
format!("{object_id}-anniversary"),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok((out_objects, deleted_objects, new_synctoken))
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
@@ -356,21 +372,19 @@ impl CalendarStore for SqliteAddressbookStore {
|
||||
&self,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
) -> Result<Vec<CalendarObject>, Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error> {
|
||||
let mut objects = vec![];
|
||||
let cal_id = cal_id
|
||||
.strip_prefix(BIRTHDAYS_PREFIX)
|
||||
.ok_or(Error::NotFound)?;
|
||||
let objects: Result<Vec<HashMap<&'static str, CalendarObject>>, rustical_ical::Error> =
|
||||
AddressbookStore::get_objects(self, principal, cal_id)
|
||||
.await?
|
||||
.iter()
|
||||
.map(AddressObject::get_significant_dates)
|
||||
.collect();
|
||||
let objects = objects?
|
||||
.into_iter()
|
||||
.flat_map(HashMap::into_values)
|
||||
.collect();
|
||||
|
||||
for (object_id, object) in AddressbookStore::get_objects(self, principal, cal_id).await? {
|
||||
if let Some(birthday) = object.get_birthday_object()? {
|
||||
objects.push((format!("{object_id}-birthday"), birthday));
|
||||
}
|
||||
if let Some(anniversary) = object.get_anniversary_object()? {
|
||||
objects.push((format!("{object_id}-anniversayr"), anniversary));
|
||||
}
|
||||
}
|
||||
Ok(objects)
|
||||
}
|
||||
|
||||
@@ -386,19 +400,22 @@ impl CalendarStore for SqliteAddressbookStore {
|
||||
.strip_prefix(BIRTHDAYS_PREFIX)
|
||||
.ok_or(Error::NotFound)?;
|
||||
let (addressobject_id, date_type) = object_id.rsplit_once('-').ok_or(Error::NotFound)?;
|
||||
AddressbookStore::get_object(self, principal, cal_id, addressobject_id, show_deleted)
|
||||
.await?
|
||||
.get_significant_dates()?
|
||||
.remove(date_type)
|
||||
.ok_or(Error::NotFound)
|
||||
let obj =
|
||||
AddressbookStore::get_object(self, principal, cal_id, addressobject_id, show_deleted)
|
||||
.await?;
|
||||
match date_type {
|
||||
"birthday" => Ok(obj.get_birthday_object()?.ok_or(Error::NotFound)?),
|
||||
"anniversary" => Ok(obj.get_anniversary_object()?.ok_or(Error::NotFound)?),
|
||||
_ => Err(Error::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
async fn put_object(
|
||||
async fn put_objects(
|
||||
&self,
|
||||
_principal: String,
|
||||
_cal_id: String,
|
||||
_object: CalendarObject,
|
||||
_principal: &str,
|
||||
_cal_id: &str,
|
||||
_objects: Vec<(String, CalendarObject)>,
|
||||
_overwrite: bool,
|
||||
) -> Result<(), Error> {
|
||||
Err(Error::ReadOnly)
|
||||
|
||||
@@ -19,15 +19,15 @@ struct AddressObjectRow {
|
||||
vcf: String,
|
||||
}
|
||||
|
||||
impl TryFrom<AddressObjectRow> for AddressObject {
|
||||
impl TryFrom<AddressObjectRow> for (String, AddressObject) {
|
||||
type Error = rustical_store::Error;
|
||||
|
||||
fn try_from(value: AddressObjectRow) -> Result<Self, Self::Error> {
|
||||
Ok(Self::from_vcf(value.id, value.vcf)?)
|
||||
Ok((value.id, AddressObject::from_vcf(value.vcf)?))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Constructor)]
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct SqliteAddressbookStore {
|
||||
db: SqlitePool,
|
||||
sender: Sender<CollectionOperation>,
|
||||
@@ -290,7 +290,7 @@ impl SqliteAddressbookStore {
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<AddressObject>, Vec<String>, i64), rustical_store::Error> {
|
||||
) -> Result<(Vec<(String, AddressObject)>, Vec<String>, i64), rustical_store::Error> {
|
||||
struct Row {
|
||||
object_id: String,
|
||||
synctoken: i64,
|
||||
@@ -318,7 +318,7 @@ impl SqliteAddressbookStore {
|
||||
for Row { object_id, .. } in changes {
|
||||
match Self::_get_object(&mut *conn, principal, addressbook_id, &object_id, false).await
|
||||
{
|
||||
Ok(object) => objects.push(object),
|
||||
Ok(object) => objects.push((object_id, object)),
|
||||
Err(rustical_store::Error::NotFound) => deleted_objects.push(object_id),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
@@ -353,7 +353,7 @@ impl SqliteAddressbookStore {
|
||||
executor: E,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
) -> Result<Vec<AddressObject>, rustical_store::Error> {
|
||||
) -> Result<Vec<(String, AddressObject)>, rustical_store::Error> {
|
||||
sqlx::query_as!(
|
||||
AddressObjectRow,
|
||||
"SELECT id, vcf FROM addressobjects WHERE principal = ? AND addressbook_id = ? AND deleted_at IS NULL",
|
||||
@@ -374,7 +374,7 @@ impl SqliteAddressbookStore {
|
||||
object_id: &str,
|
||||
show_deleted: bool,
|
||||
) -> Result<AddressObject, rustical_store::Error> {
|
||||
sqlx::query_as!(
|
||||
let (id, object) = sqlx::query_as!(
|
||||
AddressObjectRow,
|
||||
"SELECT id, vcf FROM addressobjects WHERE (principal, addressbook_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
|
||||
principal,
|
||||
@@ -385,17 +385,20 @@ impl SqliteAddressbookStore {
|
||||
.fetch_one(executor)
|
||||
.await
|
||||
.map_err(crate::Error::from)?
|
||||
.try_into()
|
||||
.try_into()?;
|
||||
assert_eq!(id, object_id);
|
||||
Ok(object)
|
||||
}
|
||||
|
||||
async fn _put_object<'e, E: Executor<'e, Database = Sqlite>>(
|
||||
executor: E,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
object_id: &str,
|
||||
object: &AddressObject,
|
||||
overwrite: bool,
|
||||
) -> Result<(), rustical_store::Error> {
|
||||
let (object_id, vcf) = (object.get_id(), object.get_vcf());
|
||||
let vcf = object.get_vcf();
|
||||
|
||||
(if overwrite {
|
||||
sqlx::query!(
|
||||
@@ -500,11 +503,13 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
#[instrument]
|
||||
async fn update_addressbook(
|
||||
&self,
|
||||
principal: String,
|
||||
id: String,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
addressbook: Addressbook,
|
||||
) -> Result<(), rustical_store::Error> {
|
||||
Self::_update_addressbook(&self.db, &principal, &id, &addressbook).await
|
||||
assert_eq!(principal, &addressbook.principal);
|
||||
assert_eq!(id, &addressbook.id);
|
||||
Self::_update_addressbook(&self.db, principal, id, &addressbook).await
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
@@ -569,7 +574,7 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<AddressObject>, Vec<String>, i64), rustical_store::Error> {
|
||||
) -> Result<(Vec<(String, AddressObject)>, Vec<String>, i64), rustical_store::Error> {
|
||||
Self::_sync_changes(&self.db, principal, addressbook_id, synctoken).await
|
||||
}
|
||||
|
||||
@@ -601,7 +606,7 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
&self,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
) -> Result<Vec<AddressObject>, rustical_store::Error> {
|
||||
) -> Result<Vec<(String, AddressObject)>, rustical_store::Error> {
|
||||
Self::_get_objects(&self.db, principal, addressbook_id).await
|
||||
}
|
||||
|
||||
@@ -619,8 +624,9 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
#[instrument]
|
||||
async fn put_object(
|
||||
&self,
|
||||
principal: String,
|
||||
addressbook_id: String,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
object_id: &str,
|
||||
object: AddressObject,
|
||||
overwrite: bool,
|
||||
) -> Result<(), rustical_store::Error> {
|
||||
@@ -630,15 +636,21 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
.await
|
||||
.map_err(crate::Error::from)?;
|
||||
|
||||
let object_id = object.get_id().to_owned();
|
||||
|
||||
Self::_put_object(&mut *tx, &principal, &addressbook_id, &object, overwrite).await?;
|
||||
Self::_put_object(
|
||||
&mut *tx,
|
||||
principal,
|
||||
addressbook_id,
|
||||
object_id,
|
||||
&object,
|
||||
overwrite,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let sync_token = Self::log_object_operation(
|
||||
&mut tx,
|
||||
&principal,
|
||||
&addressbook_id,
|
||||
&object_id,
|
||||
principal,
|
||||
addressbook_id,
|
||||
object_id,
|
||||
ChangeOperation::Add,
|
||||
)
|
||||
.await
|
||||
@@ -648,7 +660,7 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
|
||||
self.send_push_notification(
|
||||
CollectionOperationInfo::Content { sync_token },
|
||||
self.get_addressbook(&principal, &addressbook_id, false)
|
||||
self.get_addressbook(principal, addressbook_id, false)
|
||||
.await?
|
||||
.push_topic,
|
||||
);
|
||||
@@ -733,7 +745,7 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
async fn import_addressbook(
|
||||
&self,
|
||||
addressbook: Addressbook,
|
||||
objects: Vec<AddressObject>,
|
||||
objects: Vec<(String, AddressObject)>,
|
||||
merge_existing: bool,
|
||||
) -> Result<(), Error> {
|
||||
let mut tx = self
|
||||
@@ -758,11 +770,12 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
}
|
||||
|
||||
let mut sync_token = None;
|
||||
for object in objects {
|
||||
for (object_id, object) in objects {
|
||||
Self::_put_object(
|
||||
&mut *tx,
|
||||
&addressbook.principal,
|
||||
&addressbook.id,
|
||||
&object_id,
|
||||
&object,
|
||||
false,
|
||||
)
|
||||
@@ -773,7 +786,7 @@ impl AddressbookStore for SqliteAddressbookStore {
|
||||
&mut tx,
|
||||
&addressbook.principal,
|
||||
&addressbook.id,
|
||||
object.get_id(),
|
||||
&object_id,
|
||||
ChangeOperation::Add,
|
||||
)
|
||||
.await?,
|
||||
|
||||
@@ -3,7 +3,9 @@ use crate::BEGIN_IMMEDIATE;
|
||||
use async_trait::async_trait;
|
||||
use chrono::TimeDelta;
|
||||
use derive_more::derive::Constructor;
|
||||
use rustical_ical::{CalDateTime, CalendarObject, CalendarObjectType};
|
||||
use ical::types::CalDateTime;
|
||||
use regex::Regex;
|
||||
use rustical_ical::{CalendarObject, CalendarObjectType};
|
||||
use rustical_store::calendar_store::CalendarQuery;
|
||||
use rustical_store::synctoken::format_synctoken;
|
||||
use rustical_store::{Calendar, CalendarMetadata, CalendarStore, CollectionMetadata, Error};
|
||||
@@ -20,21 +22,20 @@ struct CalendarObjectRow {
|
||||
uid: String,
|
||||
}
|
||||
|
||||
impl TryFrom<CalendarObjectRow> for CalendarObject {
|
||||
impl TryFrom<CalendarObjectRow> for (String, CalendarObject) {
|
||||
type Error = rustical_store::Error;
|
||||
|
||||
fn try_from(value: CalendarObjectRow) -> Result<Self, Self::Error> {
|
||||
let object = Self::from_ics(value.ics, Some(value.id))?;
|
||||
if object.get_uid() != value.uid {
|
||||
return Err(rustical_store::Error::IcalError(
|
||||
rustical_ical::Error::InvalidData(format!(
|
||||
"uid={} and UID={} don't match",
|
||||
value.uid,
|
||||
object.get_uid()
|
||||
)),
|
||||
));
|
||||
fn try_from(row: CalendarObjectRow) -> Result<Self, Self::Error> {
|
||||
let object = CalendarObject::from_ics(row.ics)?;
|
||||
if object.get_uid() != row.uid {
|
||||
warn!(
|
||||
"Calendar object {}.ics: UID={} and row uid={} do not match",
|
||||
row.id,
|
||||
object.get_uid(),
|
||||
row.uid
|
||||
);
|
||||
}
|
||||
Ok(object)
|
||||
Ok((row.id, object))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +88,7 @@ impl From<CalendarRow> for Calendar {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Constructor)]
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct SqliteCalendarStore {
|
||||
db: SqlitePool,
|
||||
sender: Sender<CollectionOperation>,
|
||||
@@ -145,6 +146,83 @@ impl SqliteCalendarStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// In the past exports generated objects with invalid VERSION:4.0
|
||||
/// This repair sets them to VERSION:2.0
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub async fn repair_invalid_version_4_0(&self) -> Result<(), Error> {
|
||||
struct Row {
|
||||
principal: String,
|
||||
cal_id: String,
|
||||
id: String,
|
||||
ics: String,
|
||||
}
|
||||
|
||||
let mut tx = self
|
||||
.db
|
||||
.begin_with(BEGIN_IMMEDIATE)
|
||||
.await
|
||||
.map_err(crate::Error::from)?;
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
let version_pattern = Regex::new(r"(?mi)^VERSION:4.0").unwrap();
|
||||
|
||||
let repairs: Vec<Row> = sqlx::query_as!(
|
||||
Row,
|
||||
r#"SELECT principal, cal_id, id, ics FROM calendarobjects WHERE ics LIKE '%VERSION:4.0%';"#
|
||||
)
|
||||
.fetch_all(&mut *tx)
|
||||
.await
|
||||
.map_err(crate::Error::from)?
|
||||
.into_iter()
|
||||
.filter_map(|mut row| {
|
||||
version_pattern.find(&row.ics)?;
|
||||
let new_ics = version_pattern.replace(&row.ics, "VERSION:2.0");
|
||||
// Safeguard that we really only changed the version
|
||||
assert_eq!(row.ics.len(), new_ics.len());
|
||||
row.ics = new_ics.to_string();
|
||||
Some(row)
|
||||
})
|
||||
.collect();
|
||||
|
||||
if repairs.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
warn!(
|
||||
"Found {} calendar objects with invalid VERSION:4.0. Repairing by setting to VERSION:2.0",
|
||||
repairs.len()
|
||||
);
|
||||
|
||||
for repair in &repairs {
|
||||
// calendarobjectchangelog is used by sync-collection to fetch changes
|
||||
// By deleting entries we will later regenerate new entries such that clients will notice
|
||||
// the objects have changed
|
||||
warn!(
|
||||
"Repairing VERSION for {}/{}/{}.ics",
|
||||
repair.principal, repair.cal_id, repair.id
|
||||
);
|
||||
sqlx::query!(
|
||||
"DELETE FROM calendarobjectchangelog WHERE (principal, cal_id, object_id) = (?, ?, ?);",
|
||||
repair.principal, repair.cal_id, repair.id
|
||||
).execute(&mut *tx).await
|
||||
.map_err(crate::Error::from)?;
|
||||
|
||||
sqlx::query!(
|
||||
"UPDATE calendarobjects SET ics = ? WHERE (principal, cal_id, id) = (?, ?, ?);",
|
||||
repair.ics,
|
||||
repair.principal,
|
||||
repair.cal_id,
|
||||
repair.id
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(crate::Error::from)?;
|
||||
}
|
||||
|
||||
tx.commit().await.map_err(crate::Error::from)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Commit "orphaned" objects to the changelog table
|
||||
pub async fn repair_orphans(&self) -> Result<(), Error> {
|
||||
struct Row {
|
||||
@@ -279,8 +357,8 @@ impl SqliteCalendarStore {
|
||||
|
||||
async fn _update_calendar<'e, E: Executor<'e, Database = Sqlite>>(
|
||||
executor: E,
|
||||
principal: String,
|
||||
id: String,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
calendar: Calendar,
|
||||
) -> Result<(), Error> {
|
||||
let comp_event = calendar.components.contains(&CalendarObjectType::Event);
|
||||
@@ -378,7 +456,7 @@ impl SqliteCalendarStore {
|
||||
executor: E,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
) -> Result<Vec<CalendarObject>, Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error> {
|
||||
sqlx::query_as!(
|
||||
CalendarObjectRow,
|
||||
"SELECT id, uid, ics FROM calendarobjects WHERE principal = ? AND cal_id = ? AND deleted_at IS NULL",
|
||||
@@ -397,7 +475,7 @@ impl SqliteCalendarStore {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
query: CalendarQuery,
|
||||
) -> Result<Vec<CalendarObject>, Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error> {
|
||||
// We extend our query interval by one day in each direction since we really don't want to
|
||||
// miss any objects because of timezone differences
|
||||
// I've previously tried NaiveDate::MIN,MAX, but it seems like sqlite cannot handle these
|
||||
@@ -433,7 +511,7 @@ impl SqliteCalendarStore {
|
||||
object_id: &str,
|
||||
show_deleted: bool,
|
||||
) -> Result<CalendarObject, Error> {
|
||||
sqlx::query_as!(
|
||||
let (row_id, object) = sqlx::query_as!(
|
||||
CalendarObjectRow,
|
||||
"SELECT id, uid, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
|
||||
principal,
|
||||
@@ -444,7 +522,9 @@ impl SqliteCalendarStore {
|
||||
.fetch_one(executor)
|
||||
.await
|
||||
.map_err(crate::Error::from)?
|
||||
.try_into()
|
||||
.try_into()?;
|
||||
assert_eq!(object_id, row_id);
|
||||
Ok(object)
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
@@ -452,23 +532,24 @@ impl SqliteCalendarStore {
|
||||
executor: E,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
object_id: &str,
|
||||
object: &CalendarObject,
|
||||
overwrite: bool,
|
||||
) -> Result<(), Error> {
|
||||
let (object_id, uid, ics) = (object.get_id(), object.get_uid(), object.get_ics());
|
||||
let (uid, ics) = (object.get_uid(), object.get_ics());
|
||||
|
||||
let first_occurence = object
|
||||
.get_inner()
|
||||
.get_inner()
|
||||
.get_first_occurence()
|
||||
.ok()
|
||||
.flatten()
|
||||
.as_ref()
|
||||
.map(CalDateTime::date);
|
||||
.map(CalDateTime::date_floor);
|
||||
let last_occurence = object
|
||||
.get_inner()
|
||||
.get_inner()
|
||||
.get_last_occurence()
|
||||
.ok()
|
||||
.flatten()
|
||||
.as_ref()
|
||||
.map(CalDateTime::date);
|
||||
.map(CalDateTime::date_ceil);
|
||||
let etag = object.get_etag();
|
||||
let object_type = object.get_object_type() as u8;
|
||||
|
||||
@@ -560,7 +641,7 @@ impl SqliteCalendarStore {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error> {
|
||||
) -> Result<(Vec<(String, CalendarObject)>, Vec<String>, i64), Error> {
|
||||
struct Row {
|
||||
object_id: String,
|
||||
synctoken: i64,
|
||||
@@ -587,7 +668,7 @@ impl SqliteCalendarStore {
|
||||
|
||||
for Row { object_id, .. } in changes {
|
||||
match Self::_get_object(&mut *conn, principal, cal_id, &object_id, false).await {
|
||||
Ok(object) => objects.push(object),
|
||||
Ok(object) => objects.push((object_id, object)),
|
||||
Err(rustical_store::Error::NotFound) => deleted_objects.push(object_id),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
@@ -627,8 +708,8 @@ impl CalendarStore for SqliteCalendarStore {
|
||||
#[instrument]
|
||||
async fn update_calendar(
|
||||
&self,
|
||||
principal: String,
|
||||
id: String,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
calendar: Calendar,
|
||||
) -> Result<(), Error> {
|
||||
Self::_update_calendar(&self.db, principal, id, calendar).await
|
||||
@@ -696,14 +777,23 @@ impl CalendarStore for SqliteCalendarStore {
|
||||
|
||||
let mut sync_token = None;
|
||||
for object in objects {
|
||||
Self::_put_object(&mut *tx, &calendar.principal, &calendar.id, &object, false).await?;
|
||||
let object_id = object.get_uid();
|
||||
Self::_put_object(
|
||||
&mut *tx,
|
||||
&calendar.principal,
|
||||
&calendar.id,
|
||||
object_id,
|
||||
&object,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
|
||||
sync_token = Some(
|
||||
Self::log_object_operation(
|
||||
&mut tx,
|
||||
&calendar.principal,
|
||||
&calendar.id,
|
||||
object.get_id(),
|
||||
object_id,
|
||||
ChangeOperation::Add,
|
||||
)
|
||||
.await?,
|
||||
@@ -729,7 +819,7 @@ impl CalendarStore for SqliteCalendarStore {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
query: CalendarQuery,
|
||||
) -> Result<Vec<CalendarObject>, Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error> {
|
||||
Self::_calendar_query(&self.db, principal, cal_id, query).await
|
||||
}
|
||||
|
||||
@@ -760,7 +850,7 @@ impl CalendarStore for SqliteCalendarStore {
|
||||
&self,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
) -> Result<Vec<CalendarObject>, Error> {
|
||||
) -> Result<Vec<(String, CalendarObject)>, Error> {
|
||||
Self::_get_objects(&self.db, principal, cal_id).await
|
||||
}
|
||||
|
||||
@@ -776,11 +866,11 @@ impl CalendarStore for SqliteCalendarStore {
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
async fn put_object(
|
||||
async fn put_objects(
|
||||
&self,
|
||||
principal: String,
|
||||
cal_id: String,
|
||||
object: CalendarObject,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
objects: Vec<(String, CalendarObject)>,
|
||||
overwrite: bool,
|
||||
) -> Result<(), Error> {
|
||||
let mut tx = self
|
||||
@@ -789,33 +879,35 @@ impl CalendarStore for SqliteCalendarStore {
|
||||
.await
|
||||
.map_err(crate::Error::from)?;
|
||||
|
||||
let object_id = object.get_id().to_owned();
|
||||
|
||||
let calendar = Self::_get_calendar(&mut *tx, &principal, &cal_id, true).await?;
|
||||
let calendar = Self::_get_calendar(&mut *tx, principal, cal_id, true).await?;
|
||||
if calendar.subscription_url.is_some() {
|
||||
// We cannot commit an object to a subscription calendar
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
|
||||
Self::_put_object(&mut *tx, &principal, &cal_id, &object, overwrite).await?;
|
||||
|
||||
let sync_token = Self::log_object_operation(
|
||||
&mut tx,
|
||||
&principal,
|
||||
&cal_id,
|
||||
&object_id,
|
||||
ChangeOperation::Add,
|
||||
)
|
||||
.await?;
|
||||
let mut sync_token = None;
|
||||
for (object_id, object) in objects {
|
||||
sync_token = Some(
|
||||
Self::log_object_operation(
|
||||
&mut tx,
|
||||
principal,
|
||||
cal_id,
|
||||
&object_id,
|
||||
ChangeOperation::Add,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
Self::_put_object(&mut *tx, principal, cal_id, &object_id, &object, overwrite).await?;
|
||||
}
|
||||
|
||||
tx.commit().await.map_err(crate::Error::from)?;
|
||||
|
||||
self.send_push_notification(
|
||||
CollectionOperationInfo::Content { sync_token },
|
||||
self.get_calendar(&principal, &cal_id, true)
|
||||
.await?
|
||||
.push_topic,
|
||||
);
|
||||
if let Some(sync_token) = sync_token {
|
||||
self.send_push_notification(
|
||||
CollectionOperationInfo::Content { sync_token },
|
||||
self.get_calendar(principal, cal_id, true).await?.push_topic,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -881,7 +973,7 @@ impl CalendarStore for SqliteCalendarStore {
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
synctoken: i64,
|
||||
) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error> {
|
||||
) -> Result<(Vec<(String, CalendarObject)>, Vec<String>, i64), Error> {
|
||||
Self::_sync_changes(&self.db, principal, cal_id, synctoken).await
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) enum ChangeOperation {
|
||||
Delete,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SqliteStore {
|
||||
db: SqlitePool,
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ impl TryFrom<PrincipalRow> for Principal {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Constructor)]
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct SqlitePrincipalStore {
|
||||
db: SqlitePool,
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{addressbook_store::SqliteAddressbookStore, tests::get_test_addressbook_store};
|
||||
use crate::tests::{TestStoreContext, test_store_context};
|
||||
use rstest::rstest;
|
||||
use rustical_store::{Addressbook, AddressbookStore};
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_addressbook_store(
|
||||
#[from(get_test_addressbook_store)]
|
||||
#[from(test_store_context)]
|
||||
#[future]
|
||||
addr_store: SqliteAddressbookStore,
|
||||
context: TestStoreContext,
|
||||
) {
|
||||
let addr_store = addr_store.await;
|
||||
let addr_store = context.await.addr_store;
|
||||
|
||||
let cal = Addressbook {
|
||||
id: "addr".to_string(),
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{calendar_store::SqliteCalendarStore, tests::get_test_calendar_store};
|
||||
use crate::tests::{TestStoreContext, test_store_context};
|
||||
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,
|
||||
#[from(test_store_context)]
|
||||
context: TestStoreContext,
|
||||
) {
|
||||
let cal_store = cal_store.await;
|
||||
let TestStoreContext { cal_store, .. } = context.await;
|
||||
|
||||
let cal_store = cal_store;
|
||||
|
||||
let cal = Calendar {
|
||||
principal: "fake-user".to_string(),
|
||||
|
||||
@@ -2,64 +2,59 @@ use crate::{
|
||||
SqliteStore, addressbook_store::SqliteAddressbookStore, calendar_store::SqliteCalendarStore,
|
||||
principal_store::SqlitePrincipalStore,
|
||||
};
|
||||
use rustical_store::{
|
||||
Secret,
|
||||
auth::{AuthenticationProvider, Principal, PrincipalType},
|
||||
};
|
||||
use rstest::fixture;
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal, PrincipalType};
|
||||
use sqlx::SqlitePool;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
static DB: OnceCell<SqlitePool> = OnceCell::const_new();
|
||||
|
||||
mod addressbook_store;
|
||||
mod calendar_store;
|
||||
|
||||
async fn get_test_db() -> SqlitePool {
|
||||
DB.get_or_init(async || {
|
||||
let db = SqlitePool::connect("sqlite::memory:").await.unwrap();
|
||||
sqlx::migrate!("./migrations").run(&db).await.unwrap();
|
||||
let db = SqlitePool::connect("sqlite::memory:").await.unwrap();
|
||||
sqlx::migrate!("./migrations").run(&db).await.unwrap();
|
||||
|
||||
// Populate with test data
|
||||
let principal_store = SqlitePrincipalStore::new(db.clone());
|
||||
principal_store
|
||||
.insert_principal(
|
||||
Principal {
|
||||
id: "user".to_owned(),
|
||||
displayname: None,
|
||||
memberships: vec![],
|
||||
password: None,
|
||||
principal_type: PrincipalType::Individual,
|
||||
},
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
principal_store
|
||||
.add_app_token("user", "test".to_string(), "pass".to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
// Populate with test data
|
||||
let principal_store = SqlitePrincipalStore::new(db.clone());
|
||||
principal_store
|
||||
.insert_principal(
|
||||
Principal {
|
||||
id: "user".to_owned(),
|
||||
displayname: None,
|
||||
memberships: vec![],
|
||||
password: None,
|
||||
principal_type: PrincipalType::Individual,
|
||||
},
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
principal_store
|
||||
.add_app_token("user", "test".to_string(), "pass".to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
db
|
||||
})
|
||||
.await
|
||||
.clone()
|
||||
db
|
||||
}
|
||||
|
||||
#[rstest::fixture]
|
||||
pub async fn get_test_addressbook_store() -> SqliteAddressbookStore {
|
||||
let (send, _recv) = tokio::sync::mpsc::channel(1000);
|
||||
SqliteAddressbookStore::new(get_test_db().await, send)
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TestStoreContext {
|
||||
pub db: SqlitePool,
|
||||
pub addr_store: SqliteAddressbookStore,
|
||||
pub cal_store: SqliteCalendarStore,
|
||||
pub principal_store: SqlitePrincipalStore,
|
||||
pub sub_store: SqliteStore,
|
||||
}
|
||||
#[rstest::fixture]
|
||||
pub async fn get_test_calendar_store() -> SqliteCalendarStore {
|
||||
let (send, _recv) = tokio::sync::mpsc::channel(1000);
|
||||
SqliteCalendarStore::new(get_test_db().await, send)
|
||||
}
|
||||
#[rstest::fixture]
|
||||
pub async fn get_test_subscription_store() -> SqliteStore {
|
||||
SqliteStore::new(get_test_db().await)
|
||||
}
|
||||
#[rstest::fixture]
|
||||
pub async fn get_test_principal_store() -> SqlitePrincipalStore {
|
||||
SqlitePrincipalStore::new(get_test_db().await)
|
||||
|
||||
#[fixture]
|
||||
pub async fn test_store_context() -> TestStoreContext {
|
||||
let (send_addr, _recv) = tokio::sync::mpsc::channel(1);
|
||||
let (send_cal, _recv) = tokio::sync::mpsc::channel(1);
|
||||
let db = get_test_db().await;
|
||||
TestStoreContext {
|
||||
db: db.clone(),
|
||||
addr_store: SqliteAddressbookStore::new(db.clone(), send_addr),
|
||||
cal_store: SqliteCalendarStore::new(db.clone(), send_cal),
|
||||
principal_store: SqlitePrincipalStore::new(db.clone()),
|
||||
sub_store: SqliteStore::new(db),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ impl NamedStruct {
|
||||
#(#builder_field_inits),*
|
||||
};
|
||||
|
||||
let (ns, name) = reader.resolve_element(start.name());
|
||||
let (ns, name) = reader.resolver().resolve_element(start.name());
|
||||
#(#tagname_field_branches);*
|
||||
#(#namespace_field_branches);*
|
||||
|
||||
@@ -161,7 +161,7 @@ impl NamedStruct {
|
||||
// start of a child element
|
||||
Event::Start(start) | Event::Empty(start) => {
|
||||
let empty = matches!(event, Event::Empty(_));
|
||||
let (ns, name) = reader.resolve_element(start.name());
|
||||
let (ns, name) = reader.resolver().resolve_element(start.name());
|
||||
match (ns, name.as_ref()) {
|
||||
#(#named_field_branches),*
|
||||
#(#untagged_field_branches),*
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user