mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-13 13:32:16 +00:00
Compare commits
1 Commits
v0.5.0
...
feature/ca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41039242ee |
@@ -2,5 +2,3 @@
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
|
||||
[docs/**/*.md]
|
||||
indent_size = 4
|
||||
|
||||
3
.gitattributes
vendored
3
.gitattributes
vendored
@@ -1,3 +0,0 @@
|
||||
# Otherwise GitHub thinks this is an HTML project
|
||||
crates/frontend/public/assets/licenses.html linguist-detectable=false
|
||||
crates/frontend/public/assets/js/* linguist-detectable=false
|
||||
8
.github/workflows/docker-publish.yml
vendored
8
.github/workflows/docker-publish.yml
vendored
@@ -3,9 +3,6 @@ name: Docker
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
release:
|
||||
types: ["published"]
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
@@ -41,10 +38,13 @@ jobs:
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
# As long as we don't have releases everything on the main branch shall be tagged as latest
|
||||
# TODO: Before first release correctly configure this
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -12,7 +12,3 @@ principals.toml
|
||||
.env
|
||||
|
||||
site
|
||||
|
||||
# Frontend
|
||||
**/node_modules
|
||||
**/.vite
|
||||
|
||||
12
.sqlx/query-2f043f62a7c0eae1023e319f0bc8f35dfdcf6a8247e03b1de3e2cabb2d3ab8ae.json
generated
Normal file
12
.sqlx/query-2f043f62a7c0eae1023e319f0bc8f35dfdcf6a8247e03b1de3e2cabb2d3ab8ae.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "\n REPLACE INTO principals\n (id, displayname, principal_type, password_hash)\n VALUES (?, ?, ?, ?)\n ",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 4
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "2f043f62a7c0eae1023e319f0bc8f35dfdcf6a8247e03b1de3e2cabb2d3ab8ae"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT id, vcf FROM addressobjects WHERE (principal, addressbook_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
|
||||
"query": "SELECT id, vcf FROM addressobjects WHERE (principal, addressbook_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) or ?)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -22,5 +22,5 @@
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "246ec675667992c1297c29348d46496a884c59adb8b64b569d36f4ce10f88f47"
|
||||
"hash": "395e40a7b3333b79bc2ad50a123d99f74bc2712a16257ee2119dd211fdb61f7e"
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT principal FROM memberships WHERE member_of = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "principal",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "3b00b59f047e534a7f7f654984dc880f4aa9281aae5974722d2f22ec6d15cb32"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO calendars (principal, id, displayname, description, \"order\", color, subscription_url, timezone, timezone_id, push_topic, comp_event, comp_todo, comp_journal)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 13
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "5132ee8198f155242aa332a10019c48ec334884bcf7841c8aa03fd5eb11351d9"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "\n INSERT INTO principals\n (id, displayname, principal_type, password_hash) VALUES (?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n (displayname, principal_type, password_hash)\n = (excluded.displayname, excluded.principal_type, excluded.password_hash)\n ",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 4
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "5c09c2a3c052188435409d4ff076575394e625dd19f00dea2d4c71a9f34a5952"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT length(vcf) AS 'length!: u64', deleted_at AS 'deleted!: bool' FROM addressobjects WHERE principal = ? AND addressbook_id = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "length!: u64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Null"
|
||||
},
|
||||
{
|
||||
"name": "deleted!: bool",
|
||||
"ordinal": 1,
|
||||
"type_info": "Datetime"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
null,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "660833e0505d3bbcd6dd736cce06b1bf14263d0e0e87b27d89d376d422e4e474"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT *\n FROM calendars\n WHERE (principal, id) = (?, ?)\n AND ((deleted_at IS NULL) OR ?) ",
|
||||
"query": "SELECT *\n FROM calendars\n WHERE (principal, id) = (?, ?)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -80,7 +80,7 @@
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
@@ -100,5 +100,5 @@
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "bb2fa030f2e7c7afdb38c5c54cb31de5293be332d86cf643977d479999542553"
|
||||
"hash": "9f930775043a6d4571a8ffd5a981cadf7c51f3f11a189f8461505abec31076e6"
|
||||
}
|
||||
12
.sqlx/query-c4134652b1efb1dda36fb59827bf9cfee6be5bddfd352f1da4e37c6b6aa0fa7a.json
generated
Normal file
12
.sqlx/query-c4134652b1efb1dda36fb59827bf9cfee6be5bddfd352f1da4e37c6b6aa0fa7a.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO calendars (principal, id, displayname, description, \"order\", color, timezone, timezone_id, push_topic, comp_event, comp_todo, comp_journal)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 12
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "c4134652b1efb1dda36fb59827bf9cfee6be5bddfd352f1da4e37c6b6aa0fa7a"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT id, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?) AND ((deleted_at IS NULL) OR ?)",
|
||||
"query": "SELECT id, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -15,12 +15,12 @@
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 4
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "543838c030550cb09d1af08adfeade8b7ce3575d92fddbc6e9582d141bc9e49d"
|
||||
"hash": "d2f7423e2e8f97607f6664200990dcadb927445880ec6edffba3b5aedf4e199b"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT length(ics) AS 'length!: u64', deleted_at AS 'deleted!: bool' FROM calendarobjects WHERE principal = ? AND cal_id = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "length!: u64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Null"
|
||||
},
|
||||
{
|
||||
"name": "deleted!: bool",
|
||||
"ordinal": 1,
|
||||
"type_info": "Datetime"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
null,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "d9f14260a46a7ccd137d462c35d350a7fe338a074131776596c5d803fcda1f48"
|
||||
}
|
||||
756
Cargo.lock
generated
756
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
13
Cargo.toml
13
Cargo.toml
@@ -2,11 +2,10 @@
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.4.13"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "A CalDAV server"
|
||||
repository = "https://github.com/lennart-k/rustical"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
[package]
|
||||
name = "rustical"
|
||||
@@ -14,13 +13,11 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
resolver = "2"
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
debug = ["opentelemetry"]
|
||||
frontend-dev = ["rustical_frontend/dev"]
|
||||
opentelemetry = [
|
||||
"dep:opentelemetry",
|
||||
"dep:opentelemetry-otlp",
|
||||
@@ -29,12 +26,10 @@ opentelemetry = [
|
||||
"dep:tracing-opentelemetry",
|
||||
]
|
||||
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
|
||||
[workspace.dependencies]
|
||||
matchit = "0.8"
|
||||
uuid = { version = "1.11", features = ["v4", "fast-rng"] }
|
||||
async-trait = "0.1"
|
||||
axum = "0.8"
|
||||
@@ -134,12 +129,6 @@ reqwest = { version = "0.12", features = [
|
||||
], default-features = false }
|
||||
openidconnect = "4.0"
|
||||
clap = { version = "4.5", features = ["derive", "env"] }
|
||||
matchit-serde = { git = "https://github.com/lennart-k/matchit-serde", rev = "f0591d13" }
|
||||
ece = { version = "2.3", default-features = false, features = [
|
||||
"backend-openssl",
|
||||
] }
|
||||
openssl = { version = "0.10", features = ["vendored"] }
|
||||
async-std = { version = "1.13", features = ["attributes"] }
|
||||
|
||||
[dependencies]
|
||||
rustical_store = { workspace = true }
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
FROM --platform=$BUILDPLATFORM rust:1.88-alpine AS chef
|
||||
FROM --platform=$BUILDPLATFORM rust:1.86-alpine AS chef
|
||||
|
||||
ARG TARGETPLATFORM
|
||||
ARG BUILDPLATFORM
|
||||
|
||||
# the compiler will otherwise ask for aarch64-linux-musl-gcc
|
||||
ENV CC_aarch64_unknown_linux_musl="clang"
|
||||
ENV AR_aarch64_unknown_linux_musl="llvm20-ar"
|
||||
ENV AR_aarch64_unknown_linux_musl="llvm-ar"
|
||||
ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS="-Clink-self-contained=yes -Clinker=rust-lld"
|
||||
|
||||
# Stupid workaound with tempfiles since environment variables
|
||||
@@ -16,7 +16,7 @@ RUN case $TARGETPLATFORM in \
|
||||
*) echo "Unsupported platform ${TARGETPLATFORM}"; exit 1;; \
|
||||
esac
|
||||
|
||||
RUN apk add --no-cache musl-dev llvm20 clang perl pkgconf make \
|
||||
RUN apk add --no-cache musl-dev llvm19 clang \
|
||||
&& rustup target add "$(cat /tmp/rust_target)" \
|
||||
&& cargo install cargo-chef --locked \
|
||||
&& rm -rf "$CARGO_HOME/registry"
|
||||
|
||||
12
Justfile
12
Justfile
@@ -1,14 +1,2 @@
|
||||
licenses:
|
||||
cargo about generate about.hbs > crates/frontend/public/assets/licenses.html
|
||||
|
||||
frontend-dev:
|
||||
cd crates/frontend/js-components && deno task dev
|
||||
|
||||
frontend-build:
|
||||
cd crates/frontend/js-components && deno task build
|
||||
|
||||
docs:
|
||||
mkdocs build
|
||||
|
||||
docs-dev:
|
||||
mkdocs serve
|
||||
|
||||
20
README.md
20
README.md
@@ -3,16 +3,15 @@
|
||||
a CalDAV/CardDAV server
|
||||
|
||||
> [!WARNING]
|
||||
RustiCal is under **active development**!
|
||||
While I've been successfully using RustiCal productively for a few weeks now,
|
||||
you'd still be one of the first testers so expect bugs and rough edges.
|
||||
If you still want to play around with it in its current state, absolutely feel free to do so and to open up an issue if something is not working. :)
|
||||
> RustiCal is **not production-ready!**
|
||||
> I'm just starting to use it myself so I cannot guarantee that everything will be working smoothly just yet.
|
||||
> I hope there won't be any manual migrations anymore but if you want to be an early adopter some SQL knowledge might be useful just in case.
|
||||
> If you still want to play around with it in its current state, absolutely feel free to do so and to open up an issue if something is not working. :)
|
||||
|
||||
## Features
|
||||
|
||||
- easy to backup, everything saved in one SQLite database
|
||||
- also export feature in the frontend
|
||||
- [WebDAV Push](https://github.com/bitfireAT/webdav-push/) support, so near-instant synchronisation to DAVx5
|
||||
- ~~[WebDAV Push](https://github.com/bitfireAT/webdav-push/) support, so near-instant synchronisation to DAVx5~~ (currently broken)
|
||||
- lightweight (the container image contains only one binary)
|
||||
- adequately fast (I'd love to say blazingly fast™ :fire: but I don't have any benchmarks)
|
||||
- deleted calendars are recoverable
|
||||
@@ -23,12 +22,3 @@ a CalDAV/CardDAV server
|
||||
## Getting Started
|
||||
|
||||
- Check out the [documentation](https://lennart-k.github.io/rustical/installation/)
|
||||
|
||||
## Tested Clients
|
||||
|
||||
- DAVx5,
|
||||
- GNOME Accounts, GNOME Calendar, GNOME Contacts
|
||||
- Evolution
|
||||
- Apple Calendar
|
||||
- Home Assistant integration
|
||||
- Thunderbird
|
||||
|
||||
@@ -7,6 +7,5 @@ accepted = [
|
||||
"CDLA-Permissive-2.0",
|
||||
"Zlib",
|
||||
"AGPL-3.0",
|
||||
"MPL-2.0",
|
||||
]
|
||||
workarounds = ["ring", "chrono", "rustls"]
|
||||
|
||||
@@ -4,14 +4,8 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dev-dependencies]
|
||||
rustical_store_sqlite = { workspace = true, features = ["test"] }
|
||||
rstest.workspace = true
|
||||
async-std.workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
axum-extra.workspace = true
|
||||
@@ -40,5 +34,3 @@ rustical_ical.workspace = true
|
||||
http.workspace = true
|
||||
headers.workspace = true
|
||||
tower-http.workspace = true
|
||||
strum.workspace = true
|
||||
strum_macros.workspace = true
|
||||
|
||||
@@ -4,12 +4,12 @@ use axum::body::Body;
|
||||
use axum::extract::State;
|
||||
use axum::{extract::Path, response::Response};
|
||||
use headers::{ContentType, HeaderMapExt};
|
||||
use http::{HeaderValue, Method, StatusCode, header};
|
||||
use http::{HeaderValue, StatusCode, header};
|
||||
use ical::generator::{Emitter, IcalCalendarBuilder};
|
||||
use ical::property::Property;
|
||||
use percent_encoding::{CONTROLS, utf8_percent_encode};
|
||||
use rustical_ical::{CalendarObjectComponent, EventObject, JournalObject, TodoObject};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::User};
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
@@ -18,23 +18,18 @@ use tracing::instrument;
|
||||
pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, calendar_id)): Path<(String, String)>,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
user: User,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let calendar = cal_store
|
||||
.get_calendar(&principal, &calendar_id, true)
|
||||
.await?;
|
||||
let calendar = cal_store.get_calendar(&principal, &calendar_id).await?;
|
||||
if !user.is_principal(&calendar.principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let calendar = cal_store
|
||||
.get_calendar(&principal, &calendar_id, true)
|
||||
.await?;
|
||||
let calendar = cal_store.get_calendar(&principal, &calendar_id).await?;
|
||||
|
||||
let mut timezones = HashMap::new();
|
||||
let objects = cal_store.get_objects(&principal, &calendar_id).await?;
|
||||
@@ -63,6 +58,13 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
params: None,
|
||||
});
|
||||
}
|
||||
if calendar.color.is_some() {
|
||||
ical_calendar_builder = ical_calendar_builder.set(Property {
|
||||
name: "X-RUSTICAL-COLOR".to_owned(),
|
||||
value: calendar.color,
|
||||
params: None,
|
||||
});
|
||||
}
|
||||
let mut ical_calendar = ical_calendar_builder.build();
|
||||
|
||||
for object in &objects {
|
||||
@@ -97,9 +99,5 @@ pub async fn route_get<C: CalendarStore, S: SubscriptionStore>(
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
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(ical_calendar.generate())).unwrap())
|
||||
}
|
||||
|
||||
@@ -4,9 +4,8 @@ use crate::calendar::prop::SupportedCalendarComponentSet;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use http::{Method, StatusCode};
|
||||
use rustical_dav::xml::HrefElement;
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::{Calendar, CalendarStore, SubscriptionStore};
|
||||
use rustical_xml::{Unparsed, XmlDeserialize, XmlDocument, XmlRootTag};
|
||||
use tracing::instrument;
|
||||
@@ -30,8 +29,6 @@ pub struct MkcolCalendarProp {
|
||||
resourcetype: Option<Unparsed>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
supported_calendar_component_set: Option<SupportedCalendarComponentSet>,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALENDARSERVER")]
|
||||
source: Option<HrefElement>,
|
||||
// Ignore that property, we don't support it but also don't want to throw an error
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
#[allow(dead_code)]
|
||||
@@ -63,7 +60,7 @@ struct MkcolRequest {
|
||||
#[instrument(skip(cal_store))]
|
||||
pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
method: Method,
|
||||
body: String,
|
||||
@@ -72,16 +69,12 @@ pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let mut request = match method.as_str() {
|
||||
let request = match method.as_str() {
|
||||
"MKCALENDAR" => MkcalendarRequest::parse_str(&body)?.set.prop,
|
||||
"MKCOL" => MkcolRequest::parse_str(&body)?.set.prop,
|
||||
_ => unreachable!("We never call with another method"),
|
||||
};
|
||||
|
||||
if let Some("") = request.displayname.as_deref() {
|
||||
request.displayname = None
|
||||
}
|
||||
|
||||
let calendar = Calendar {
|
||||
id: cal_id.to_owned(),
|
||||
principal: principal.to_owned(),
|
||||
@@ -93,7 +86,7 @@ pub async fn route_mkcalendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
description: request.calendar_description,
|
||||
deleted_at: None,
|
||||
synctoken: 0,
|
||||
subscription_url: request.source.map(|href| href.href),
|
||||
subscription_url: None,
|
||||
push_topic: uuid::Uuid::new_v4().to_string(),
|
||||
components: request
|
||||
.supported_calendar_component_set
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod get;
|
||||
pub mod mkcalendar;
|
||||
pub mod post;
|
||||
// pub mod post;
|
||||
pub mod get;
|
||||
pub mod put;
|
||||
pub mod report;
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
use crate::Error;
|
||||
use crate::calendar::CalendarResourceService;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use crate::calendar::resource::{CalendarResource, CalendarResourceService};
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use http::{HeaderMap, StatusCode, header};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
use rustical_dav::resource::Resource;
|
||||
use rustical_dav_push::register::PushRegister;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::{CalendarStore, Subscription, SubscriptionStore};
|
||||
use rustical_xml::XmlDocument;
|
||||
use tracing::instrument;
|
||||
@@ -15,7 +14,7 @@ use tracing::instrument;
|
||||
#[instrument(skip(resource_service))]
|
||||
pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
State(resource_service): State<CalendarResourceService<C, S>>,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
@@ -25,7 +24,7 @@ pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
||||
|
||||
let calendar = resource_service
|
||||
.cal_store
|
||||
.get_calendar(&principal, &cal_id, false)
|
||||
.get_calendar(&principal, &cal_id)
|
||||
.await?;
|
||||
let calendar_resource = CalendarResource {
|
||||
cal: calendar,
|
||||
@@ -74,17 +73,20 @@ pub async fn route_post<C: CalendarStore, S: SubscriptionStore>(
|
||||
.upsert_subscription(subscription)
|
||||
.await?;
|
||||
|
||||
// TODO: make nicer
|
||||
let location = format!("/push_subscription/{sub_id}");
|
||||
// let location = req
|
||||
// .resource_map()
|
||||
// .url_for(&req, "subscription", &[sub_id])
|
||||
// .unwrap();
|
||||
//
|
||||
let location = "asd";
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
HeaderMap::from_iter([
|
||||
(header::LOCATION, HeaderValue::from_str(&location).unwrap()),
|
||||
(
|
||||
header::EXPIRES,
|
||||
HeaderValue::from_str(&expires.to_rfc2822()).unwrap(),
|
||||
),
|
||||
]),
|
||||
HeaderMap::from_iter([(header::LOCATION, location)]),
|
||||
)
|
||||
.into_response())
|
||||
.into_response());
|
||||
|
||||
Ok(HttpResponse::Created()
|
||||
.append_header((header::LOCATION, location.to_string()))
|
||||
.append_header((header::EXPIRES, expires.to_rfc2822()))
|
||||
.finish())
|
||||
}
|
||||
|
||||
101
crates/caldav/src/calendar/methods/put.rs
Normal file
101
crates/caldav/src/calendar/methods/put.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::calendar::prop::SupportedCalendarComponent;
|
||||
use crate::calendar::{self, CalendarResourceService};
|
||||
use crate::{Error, calendar_set};
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use ical::generator::Emitter;
|
||||
use ical::parser::ical::component::IcalTimeZone;
|
||||
use ical::{IcalParser, parser::Component};
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_store::{Calendar, CalendarStore, SubscriptionStore, auth::User};
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(cal_store))]
|
||||
pub async fn route_put<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
user: User,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let mut parser = IcalParser::new(body.as_bytes());
|
||||
let cal = parser
|
||||
.next()
|
||||
.ok_or(rustical_ical::Error::MissingCalendar)?
|
||||
.map_err(rustical_ical::Error::from)?;
|
||||
if parser.next().is_some() {
|
||||
return Err(rustical_ical::Error::InvalidData(
|
||||
"multiple calendars, only one allowed".to_owned(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
if !cal.alarms.is_empty() || !cal.free_busys.is_empty() {
|
||||
return Err(rustical_ical::Error::InvalidData(
|
||||
"Importer does not support VALARM and VFREEBUSY components".to_owned(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
let mut objects = vec![];
|
||||
for event in cal.events {}
|
||||
for todo in cal.todos {}
|
||||
for journal in cal.journals {}
|
||||
|
||||
let timezones: HashMap<String, IcalTimeZone> = cal
|
||||
.timezones
|
||||
.clone()
|
||||
.into_iter()
|
||||
.filter_map(|timezone| {
|
||||
let timezone_prop = timezone.get_property("TZID")?.to_owned();
|
||||
let tzid = timezone_prop.value?;
|
||||
Some((tzid, timezone))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let displayname = cal.get_property("X-WR-CALNAME").and_then(|prop| prop.value);
|
||||
let description = cal.get_property("X-WR-CALDESC").and_then(|prop| prop.value);
|
||||
let color = cal
|
||||
.get_property("X-RUSTICAL-COLOR")
|
||||
.and_then(|prop| prop.value);
|
||||
let timezone_id = cal
|
||||
.get_property("X-WR-TIMEZONE")
|
||||
.and_then(|prop| prop.value);
|
||||
let timezone = timezone_id
|
||||
.and_then(|tzid| timezones.get(&tzid))
|
||||
.map(|timezone| timezone.generate());
|
||||
|
||||
let mut components = vec![CalendarObjectType::Event, CalendarObjectType::Todo];
|
||||
if !cal.journals.is_empty() {
|
||||
components.push(CalendarObjectType::Journal);
|
||||
}
|
||||
|
||||
let calendar = Calendar {
|
||||
principal: principal.clone(),
|
||||
id: cal_id,
|
||||
displayname,
|
||||
description,
|
||||
color,
|
||||
timezone_id,
|
||||
timezone,
|
||||
components,
|
||||
subscription_url: None,
|
||||
push_topic: uuid::Uuid::new_v4().to_string(),
|
||||
synctoken: 0,
|
||||
deleted_at: None,
|
||||
order: 0,
|
||||
};
|
||||
|
||||
cal_store
|
||||
.import_calendar(&principal, calendar, objects)
|
||||
.await?;
|
||||
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
|
||||
if let Some(filename) = href.strip_prefix(path) {
|
||||
let filename = filename.trim_start_matches("/");
|
||||
if let Some(object_id) = filename.strip_suffix(".ics") {
|
||||
match store.get_object(principal, cal_id, object_id, false).await {
|
||||
match store.get_object(principal, cal_id, object_id).await {
|
||||
Ok(object) => result.push(object),
|
||||
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
|
||||
Err(err) => return Err(err.into()),
|
||||
|
||||
@@ -21,7 +21,7 @@ use rustical_dav::{
|
||||
},
|
||||
};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore, auth::User};
|
||||
use rustical_xml::{XmlDeserialize, XmlDocument};
|
||||
use sync_collection::handle_sync_collection;
|
||||
use tracing::instrument;
|
||||
@@ -56,7 +56,7 @@ fn objects_response(
|
||||
path: &str,
|
||||
principal: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
prop: &PropfindType<CalendarObjectPropWrapperName>,
|
||||
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
|
||||
let mut responses = Vec::new();
|
||||
@@ -67,7 +67,7 @@ fn objects_response(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, prop, None, puri, user)?,
|
||||
.propfind(&path, prop, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ fn objects_response(
|
||||
#[instrument(skip(cal_store))]
|
||||
pub async fn route_report_calendar<C: CalendarStore, S: SubscriptionStore>(
|
||||
Path((principal, cal_id)): Path<(String, String)>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
Extension(puri): Extension<CalDavPrincipalUri>,
|
||||
State(CalendarResourceService { cal_store, .. }): State<CalendarResourceService<C, S>>,
|
||||
OriginalUri(uri): OriginalUri,
|
||||
@@ -149,7 +149,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::calendar_object::{CalendarData, CalendarObjectPropName, ExpandElement};
|
||||
use calendar_query::{CompFilterElement, FilterElement, TimeRangeElement};
|
||||
use rustical_dav::{extensions::CommonPropertiesPropName, xml::PropElement};
|
||||
use rustical_dav::xml::PropElement;
|
||||
use rustical_ical::UtcDateTime;
|
||||
use rustical_xml::{NamespaceOwned, ValueDeserialize};
|
||||
|
||||
@@ -160,6 +160,7 @@ mod tests {
|
||||
<calendar-multiget xmlns="urn:ietf:params:xml:ns:caldav" xmlns:D="DAV:">
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<D:displayname/>
|
||||
<calendar-data>
|
||||
<expand start="20250426T220000Z" end="20250503T220000Z"/>
|
||||
</calendar-data>
|
||||
@@ -179,7 +180,7 @@ mod tests {
|
||||
end: <UtcDateTime as ValueDeserialize>::deserialize("20250503T220000Z").unwrap(),
|
||||
}), limit_recurrence_set: None, limit_freebusy_set: None }
|
||||
)),
|
||||
], vec![])),
|
||||
], vec![(Some(NamespaceOwned(Vec::from("DAV:"))), "displayname".to_string())])),
|
||||
href: vec![
|
||||
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
||||
]
|
||||
@@ -252,7 +253,6 @@ mod tests {
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<D:displayname/>
|
||||
<D:invalid-prop/>
|
||||
</D:prop>
|
||||
<D:href>/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b</D:href>
|
||||
</calendar-multiget>
|
||||
@@ -263,8 +263,7 @@ mod tests {
|
||||
ReportRequest::CalendarMultiget(CalendarMultigetRequest {
|
||||
prop: rustical_dav::xml::PropfindType::Prop(PropElement(vec![
|
||||
CalendarObjectPropWrapperName::CalendarObject(CalendarObjectPropName::Getetag),
|
||||
CalendarObjectPropWrapperName::Common(CommonPropertiesPropName::Displayname),
|
||||
], vec![(Some(NamespaceOwned(Vec::from("DAV:"))), "invalid-prop".to_string())])),
|
||||
], vec![(Some(NamespaceOwned(Vec::from("DAV:"))), "displayname".to_string())])),
|
||||
href: vec![
|
||||
"/caldav/user/user/6f787542-5256-401a-8db97003260da/ae7a998fdfd1d84a20391168962c62b".to_owned()
|
||||
]
|
||||
|
||||
@@ -13,7 +13,7 @@ use rustical_dav::{
|
||||
};
|
||||
use rustical_store::{
|
||||
CalendarStore,
|
||||
auth::Principal,
|
||||
auth::User,
|
||||
synctoken::{format_synctoken, parse_synctoken},
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ pub async fn handle_sync_collection<C: CalendarStore>(
|
||||
sync_collection: &SyncCollectionRequest<CalendarObjectPropWrapperName>,
|
||||
path: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
cal_store: &C,
|
||||
@@ -39,7 +39,7 @@ pub async fn handle_sync_collection<C: CalendarStore>(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||
.propfind(&path, &sync_collection.prop, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use derive_more::derive::{From, Into};
|
||||
use rustical_ical::CalendarObjectType;
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use strum_macros::VariantArray;
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, PartialEq, From, Into)]
|
||||
pub struct SupportedCalendarComponent {
|
||||
@@ -59,12 +58,39 @@ pub struct SupportedCalendarData {
|
||||
calendar_data: CalendarData,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub enum ReportMethod {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
CalendarQuery,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
CalendarMultiget,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
SyncCollection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct ReportWrapper {
|
||||
report: ReportMethod,
|
||||
}
|
||||
|
||||
// RFC 3253 section-3.1.5
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportSet {
|
||||
#[xml(flatten)]
|
||||
supported_report: Vec<ReportWrapper>,
|
||||
}
|
||||
|
||||
impl Default for SupportedReportSet {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
supported_report: vec![
|
||||
ReportWrapper {
|
||||
report: ReportMethod::CalendarQuery,
|
||||
},
|
||||
ReportWrapper {
|
||||
report: ReportMethod::CalendarMultiget,
|
||||
},
|
||||
ReportWrapper {
|
||||
report: ReportMethod::SyncCollection,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData};
|
||||
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData, SupportedReportSet};
|
||||
use crate::Error;
|
||||
use crate::calendar::prop::ReportMethod;
|
||||
use chrono::{DateTime, Utc};
|
||||
use derive_more::derive::{From, Into};
|
||||
use rustical_dav::extensions::{
|
||||
@@ -8,11 +7,11 @@ use rustical_dav::extensions::{
|
||||
};
|
||||
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_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
||||
use rustical_dav_push::DavPushExtension;
|
||||
use rustical_ical::CalDateTime;
|
||||
use rustical_store::Calendar;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_xml::{EnumVariants, PropName};
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use std::str::FromStr;
|
||||
@@ -20,6 +19,10 @@ use std::str::FromStr;
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "CalendarPropName")]
|
||||
pub enum CalendarProp {
|
||||
// WebDAV (RFC 2518)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(Option<String>),
|
||||
|
||||
// CalDAV (RFC 4791)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_ICAL")]
|
||||
CalendarColor(Option<String>),
|
||||
@@ -41,8 +44,8 @@ pub enum CalendarProp {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
MaxResourceSize(i64),
|
||||
#[xml(skip_deserializing)]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
SupportedReportSet(SupportedReportSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALENDARSERVER")]
|
||||
Source(Option<HrefElement>),
|
||||
#[xml(skip_deserializing)]
|
||||
@@ -58,7 +61,7 @@ pub enum CalendarProp {
|
||||
pub enum CalendarPropWrapper {
|
||||
Calendar(CalendarProp),
|
||||
SyncToken(SyncTokenExtensionProp),
|
||||
DavPush(DavPushExtensionProp),
|
||||
// DavPush(DavPushExtensionProp),
|
||||
Common(CommonPropertiesProp),
|
||||
}
|
||||
|
||||
@@ -95,11 +98,9 @@ impl DavPushExtension for CalendarResource {
|
||||
impl Resource for CalendarResource {
|
||||
type Prop = CalendarPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
const IS_COLLECTION: bool = true;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
if self.cal.subscription_url.is_none() {
|
||||
@@ -121,11 +122,14 @@ impl Resource for CalendarResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
prop: &CalendarPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
CalendarPropWrapperName::Calendar(prop) => CalendarPropWrapper::Calendar(match prop {
|
||||
CalendarPropName::Displayname => {
|
||||
CalendarProp::Displayname(self.cal.displayname.clone())
|
||||
}
|
||||
CalendarPropName::CalendarColor => {
|
||||
CalendarProp::CalendarColor(self.cal.color.clone())
|
||||
}
|
||||
@@ -153,7 +157,7 @@ impl Resource for CalendarResource {
|
||||
}
|
||||
CalendarPropName::MaxResourceSize => CalendarProp::MaxResourceSize(10000000),
|
||||
CalendarPropName::SupportedReportSet => {
|
||||
CalendarProp::SupportedReportSet(SupportedReportSet::all())
|
||||
CalendarProp::SupportedReportSet(SupportedReportSet::default())
|
||||
}
|
||||
CalendarPropName::Source => CalendarProp::Source(
|
||||
self.cal.subscription_url.to_owned().map(HrefElement::from),
|
||||
@@ -168,9 +172,9 @@ impl Resource for CalendarResource {
|
||||
CalendarPropWrapperName::SyncToken(prop) => {
|
||||
CalendarPropWrapper::SyncToken(SyncTokenExtension::get_prop(self, prop)?)
|
||||
}
|
||||
CalendarPropWrapperName::DavPush(prop) => {
|
||||
CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?)
|
||||
}
|
||||
// CalendarPropWrapperName::DavPush(prop) => {
|
||||
// CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?)
|
||||
// }
|
||||
CalendarPropWrapperName::Common(prop) => CalendarPropWrapper::Common(
|
||||
CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
|
||||
),
|
||||
@@ -183,6 +187,10 @@ impl Resource for CalendarResource {
|
||||
}
|
||||
match prop {
|
||||
CalendarPropWrapper::Calendar(prop) => match prop {
|
||||
CalendarProp::Displayname(displayname) => {
|
||||
self.cal.displayname = displayname;
|
||||
Ok(())
|
||||
}
|
||||
CalendarProp::CalendarColor(color) => {
|
||||
self.cal.color = color;
|
||||
Ok(())
|
||||
@@ -201,7 +209,10 @@ impl Resource for CalendarResource {
|
||||
if let Some(tzid) = &timezone_id {
|
||||
// Validate timezone id
|
||||
chrono_tz::Tz::from_str(tzid).map_err(|_| {
|
||||
rustical_dav::Error::BadRequest(format!("Invalid timezone-id: {tzid}"))
|
||||
rustical_dav::Error::BadRequest(format!(
|
||||
"Invalid timezone-id: {}",
|
||||
tzid
|
||||
))
|
||||
})?;
|
||||
// TODO: Ensure that timezone is also updated (For now hope that clients play nice)
|
||||
}
|
||||
@@ -225,7 +236,7 @@ impl Resource for CalendarResource {
|
||||
CalendarProp::MaxDateTime(_) => Err(rustical_dav::Error::PropReadOnly),
|
||||
},
|
||||
CalendarPropWrapper::SyncToken(prop) => SyncTokenExtension::set_prop(self, prop),
|
||||
CalendarPropWrapper::DavPush(prop) => DavPushExtension::set_prop(self, prop),
|
||||
// CalendarPropWrapper::DavPush(prop) => DavPushExtension::set_prop(self, prop),
|
||||
CalendarPropWrapper::Common(prop) => CommonPropertiesExtension::set_prop(self, prop),
|
||||
}
|
||||
}
|
||||
@@ -236,6 +247,10 @@ impl Resource for CalendarResource {
|
||||
}
|
||||
match prop {
|
||||
CalendarPropWrapperName::Calendar(prop) => match prop {
|
||||
CalendarPropName::Displayname => {
|
||||
self.cal.displayname = None;
|
||||
Ok(())
|
||||
}
|
||||
CalendarPropName::CalendarColor => {
|
||||
self.cal.color = None;
|
||||
Ok(())
|
||||
@@ -269,32 +284,19 @@ impl Resource for CalendarResource {
|
||||
CalendarPropName::MaxDateTime => Err(rustical_dav::Error::PropReadOnly),
|
||||
},
|
||||
CalendarPropWrapperName::SyncToken(prop) => SyncTokenExtension::remove_prop(self, prop),
|
||||
CalendarPropWrapperName::DavPush(prop) => DavPushExtension::remove_prop(self, prop),
|
||||
// CalendarPropWrapperName::DavPush(prop) => DavPushExtension::remove_prop(self, prop),
|
||||
CalendarPropWrapperName::Common(prop) => {
|
||||
CommonPropertiesExtension::remove_prop(self, prop)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
self.cal.displayname.as_deref()
|
||||
}
|
||||
fn set_displayname(&mut self, name: Option<String>) -> Result<(), rustical_dav::Error> {
|
||||
self.cal.displayname = name;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.cal.principal)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
if self.cal.subscription_url.is_some() {
|
||||
return Ok(UserPrivilegeSet::owner_write_properties(
|
||||
user.is_principal(&self.cal.principal),
|
||||
));
|
||||
}
|
||||
if self.read_only {
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
if self.cal.subscription_url.is_some() || self.read_only {
|
||||
return Ok(UserPrivilegeSet::owner_read(
|
||||
user.is_principal(&self.cal.principal),
|
||||
));
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::calendar::methods::get::route_get;
|
||||
use crate::calendar::methods::mkcalendar::route_mkcalendar;
|
||||
use crate::calendar::methods::post::route_post;
|
||||
use crate::calendar::methods::report::route_report_calendar;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use crate::calendar_object::CalendarObjectResourceService;
|
||||
@@ -13,7 +12,7 @@ use axum::handler::Handler;
|
||||
use axum::response::Response;
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
@@ -48,23 +47,19 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
|
||||
type PathComponents = (String, String); // principal, calendar_id
|
||||
type Resource = CalendarResource;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access, calendar-proxy, webdav-push";
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal, cal_id): &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Error> {
|
||||
let calendar = self
|
||||
.cal_store
|
||||
.get_calendar(principal, cal_id, show_deleted)
|
||||
.await?;
|
||||
let calendar = self.cal_store.get_calendar(principal, cal_id).await?;
|
||||
Ok(CalendarResource {
|
||||
cal: calendar,
|
||||
read_only: self.cal_store.is_read_only(cal_id),
|
||||
read_only: self.cal_store.is_read_only(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -131,13 +126,6 @@ impl<C: CalendarStore, S: SubscriptionStore> AxumMethods for CalendarResourceSer
|
||||
})
|
||||
}
|
||||
|
||||
fn post() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||
Some(|state, req| {
|
||||
let mut service = Handler::with_state(route_post::<C, S>, state);
|
||||
Box::pin(Service::call(&mut service, req))
|
||||
})
|
||||
}
|
||||
|
||||
fn mkcalendar() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>>
|
||||
{
|
||||
Some(|state, req| {
|
||||
|
||||
@@ -6,10 +6,10 @@ use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::TypedHeader;
|
||||
use headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||
use http::{HeaderMap, Method, StatusCode};
|
||||
use http::{HeaderMap, StatusCode};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::CalendarStore;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
|
||||
@@ -21,33 +21,26 @@ pub async fn get_event<C: CalendarStore>(
|
||||
object_id,
|
||||
}): Path<CalendarObjectPathComponents>,
|
||||
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
user: User,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let calendar = cal_store
|
||||
.get_calendar(&principal, &calendar_id, false)
|
||||
.await?;
|
||||
let calendar = cal_store.get_calendar(&principal, &calendar_id).await?;
|
||||
if !user.is_principal(&calendar.principal) {
|
||||
return Err(crate::Error::Unauthorized);
|
||||
}
|
||||
|
||||
let event = cal_store
|
||||
.get_object(&principal, &calendar_id, &object_id, false)
|
||||
.get_object(&principal, &calendar_id, &object_id)
|
||||
.await?;
|
||||
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ETag::from_str(&event.get_etag()).unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/calendar").unwrap());
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(event.get_ics().to_owned())).unwrap())
|
||||
}
|
||||
Ok(resp.body(Body::new(event.get_ics().to_owned())).unwrap())
|
||||
}
|
||||
|
||||
#[instrument(skip(cal_store))]
|
||||
@@ -58,7 +51,7 @@ pub async fn put_event<C: CalendarStore>(
|
||||
object_id,
|
||||
}): Path<CalendarObjectPathComponents>,
|
||||
State(CalendarObjectResourceService { cal_store }): State<CalendarObjectResourceService<C>>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
|
||||
header_map: HeaderMap,
|
||||
body: String,
|
||||
|
||||
@@ -8,7 +8,7 @@ use rustical_dav::{
|
||||
xml::Resourcetype,
|
||||
};
|
||||
use rustical_ical::CalendarObject;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
|
||||
#[derive(Clone, From, Into)]
|
||||
pub struct CalendarObjectResource {
|
||||
@@ -25,11 +25,9 @@ impl ResourceName for CalendarObjectResource {
|
||||
impl Resource for CalendarObjectResource {
|
||||
type Prop = CalendarObjectPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
|
||||
fn is_collection(&self) -> bool {
|
||||
false
|
||||
}
|
||||
const IS_COLLECTION: bool = false;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[])
|
||||
@@ -38,7 +36,7 @@ impl Resource for CalendarObjectResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
prop: &CalendarObjectPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
@@ -68,10 +66,6 @@ impl Resource for CalendarObjectResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal)
|
||||
}
|
||||
@@ -80,7 +74,7 @@ impl Resource for CalendarObjectResource {
|
||||
Some(self.object.get_etag())
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.principal),
|
||||
))
|
||||
|
||||
@@ -9,7 +9,7 @@ use async_trait::async_trait;
|
||||
use axum::{extract::Request, handler::Handler, response::Response};
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::{CalendarStore, auth::Principal};
|
||||
use rustical_store::{CalendarStore, auth::User};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::{convert::Infallible, sync::Arc};
|
||||
use tower::Service;
|
||||
@@ -46,7 +46,7 @@ impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
|
||||
type Resource = CalendarObjectResource;
|
||||
type MemberType = CalendarObjectResource;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||
@@ -58,11 +58,10 @@ impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
|
||||
calendar_id,
|
||||
object_id,
|
||||
}: &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let object = self
|
||||
.cal_store
|
||||
.get_object(principal, calendar_id, object_id, show_deleted)
|
||||
.get_object(principal, calendar_id, object_id)
|
||||
.await?;
|
||||
Ok(CalendarObjectResource {
|
||||
object,
|
||||
|
||||
64
crates/caldav/src/calendar_set/mod.rs
Normal file
64
crates/caldav/src/calendar_set/mod.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
use crate::Error;
|
||||
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{Resourcetype, ResourcetypeInner};
|
||||
use rustical_store::auth::User;
|
||||
|
||||
mod service;
|
||||
pub use service::*;
|
||||
mod prop;
|
||||
pub use prop::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CalendarSetResource {
|
||||
pub(crate) principal: String,
|
||||
pub(crate) read_only: bool,
|
||||
pub(crate) name: &'static str,
|
||||
}
|
||||
|
||||
impl ResourceName for CalendarSetResource {
|
||||
fn get_name(&self) -> String {
|
||||
self.name.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Resource for CalendarSetResource {
|
||||
type Prop = PrincipalPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
|
||||
const IS_COLLECTION: bool = true;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[ResourcetypeInner(
|
||||
Some(rustical_dav::namespace::NS_DAV),
|
||||
"collection",
|
||||
)])
|
||||
}
|
||||
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &User,
|
||||
prop: &PrincipalPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
||||
<Self as CommonPropertiesExtension>::get_prop(self, puri, user, prop)?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(if self.read_only {
|
||||
UserPrivilegeSet::owner_read(user.is_principal(&self.principal))
|
||||
} else {
|
||||
UserPrivilegeSet::owner_only(user.is_principal(&self.principal))
|
||||
})
|
||||
}
|
||||
}
|
||||
8
crates/caldav/src/calendar_set/prop.rs
Normal file
8
crates/caldav/src/calendar_set/prop.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use rustical_dav::extensions::CommonPropertiesProp;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
||||
pub enum PrincipalPropWrapper {
|
||||
Common(CommonPropertiesProp),
|
||||
}
|
||||
84
crates/caldav/src/calendar_set/service.rs
Normal file
84
crates/caldav/src/calendar_set/service.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use crate::calendar::CalendarResourceService;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use crate::calendar_set::CalendarSetResource;
|
||||
use crate::{CalDavPrincipalUri, Error};
|
||||
use async_trait::async_trait;
|
||||
use axum::Router;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct CalendarSetResourceService<C: CalendarStore, S: SubscriptionStore> {
|
||||
name: &'static str,
|
||||
cal_store: Arc<C>,
|
||||
sub_store: Arc<S>,
|
||||
}
|
||||
|
||||
impl<C: CalendarStore, S: SubscriptionStore> Clone for CalendarSetResourceService<C, S> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
name: self.name,
|
||||
cal_store: self.cal_store.clone(),
|
||||
sub_store: self.sub_store.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: CalendarStore, S: SubscriptionStore> CalendarSetResourceService<C, S> {
|
||||
pub fn new(name: &'static str, cal_store: Arc<C>, sub_store: Arc<S>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
cal_store,
|
||||
sub_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarSetResourceService<C, S> {
|
||||
type PathComponents = (String,);
|
||||
type MemberType = CalendarResource;
|
||||
type Resource = CalendarSetResource;
|
||||
type Error = Error;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, extended-mkcol, calendar-access";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
Ok(CalendarSetResource {
|
||||
principal: principal.to_owned(),
|
||||
read_only: self.cal_store.is_read_only(),
|
||||
name: self.name,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_members(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||
let calendars = self.cal_store.get_calendars(principal).await?;
|
||||
Ok(calendars
|
||||
.into_iter()
|
||||
.map(|cal| CalendarResource {
|
||||
cal,
|
||||
read_only: self.cal_store.is_read_only(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn axum_router<State: Send + Sync + Clone + 'static>(self) -> axum::Router<State> {
|
||||
Router::new()
|
||||
.nest(
|
||||
"/{calendar_id}",
|
||||
CalendarResourceService::new(self.cal_store.clone(), self.sub_store.clone())
|
||||
.axum_router(),
|
||||
)
|
||||
.route_service("/", self.axum_service())
|
||||
}
|
||||
}
|
||||
impl<C: CalendarStore, S: SubscriptionStore> AxumMethods for CalendarSetResourceService<C, S> {}
|
||||
@@ -1,48 +1,63 @@
|
||||
use axum::response::Redirect;
|
||||
use axum::routing::any;
|
||||
use axum::{Extension, Router};
|
||||
use derive_more::Constructor;
|
||||
use principal::PrincipalResourceService;
|
||||
use rustical_dav::resource::{PrincipalUri, ResourceService};
|
||||
use rustical_dav::resources::RootResourceService;
|
||||
use rustical_store::auth::middleware::AuthenticationLayer;
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use rustical_store::auth::{AuthenticationProvider, User};
|
||||
use rustical_store::{AddressbookStore, CalendarStore, ContactBirthdayStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub mod calendar;
|
||||
pub mod calendar_object;
|
||||
pub mod calendar_set;
|
||||
pub mod error;
|
||||
pub mod principal;
|
||||
// mod subscription;
|
||||
|
||||
pub use error::Error;
|
||||
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct CalDavPrincipalUri(&'static str);
|
||||
|
||||
impl PrincipalUri for CalDavPrincipalUri {
|
||||
fn principal_collection(&self) -> String {
|
||||
format!("{}/principal/", self.0)
|
||||
}
|
||||
fn principal_uri(&self, principal: &str) -> String {
|
||||
format!("{}{}/", self.principal_collection(), principal)
|
||||
format!("{}/principal/{}/", self.0, principal)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn caldav_router<AP: AuthenticationProvider, C: CalendarStore, S: SubscriptionStore>(
|
||||
pub fn caldav_router<
|
||||
AP: AuthenticationProvider,
|
||||
AS: AddressbookStore,
|
||||
C: CalendarStore,
|
||||
S: SubscriptionStore,
|
||||
>(
|
||||
prefix: &'static str,
|
||||
auth_provider: Arc<AP>,
|
||||
store: Arc<C>,
|
||||
addr_store: Arc<AS>,
|
||||
subscription_store: Arc<S>,
|
||||
simplified_home_set: bool,
|
||||
) -> Router {
|
||||
Router::new().nest(
|
||||
prefix,
|
||||
RootResourceService::<_, Principal, CalDavPrincipalUri>::new(PrincipalResourceService {
|
||||
auth_provider: auth_provider.clone(),
|
||||
sub_store: subscription_store.clone(),
|
||||
cal_store: store.clone(),
|
||||
simplified_home_set,
|
||||
})
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CalDavPrincipalUri(prefix))),
|
||||
)
|
||||
let birthday_store = Arc::new(ContactBirthdayStore::new(addr_store));
|
||||
let principal_service = PrincipalResourceService {
|
||||
auth_provider: auth_provider.clone(),
|
||||
sub_store: subscription_store.clone(),
|
||||
birthday_store: birthday_store.clone(),
|
||||
cal_store: store.clone(),
|
||||
};
|
||||
|
||||
Router::new()
|
||||
.nest(
|
||||
prefix,
|
||||
RootResourceService::<_, User, CalDavPrincipalUri>::new(principal_service.clone())
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CalDavPrincipalUri(prefix))),
|
||||
)
|
||||
.route(
|
||||
"/.well-known/caldav",
|
||||
any(async || Redirect::permanent(prefix)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,24 +2,18 @@ use crate::Error;
|
||||
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{
|
||||
GroupMemberSet, GroupMembership, Resourcetype, ResourcetypeInner, SupportedReportSet,
|
||||
};
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
||||
use rustical_store::auth::User;
|
||||
|
||||
mod service;
|
||||
pub use service::*;
|
||||
mod prop;
|
||||
pub use prop::*;
|
||||
#[cfg(test)]
|
||||
pub mod tests;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Clone)]
|
||||
pub struct PrincipalResource {
|
||||
principal: Principal,
|
||||
members: Vec<String>,
|
||||
// If true only return the principal as the calendar home set, otherwise also groups
|
||||
simplified_home_set: bool,
|
||||
principal: User,
|
||||
home_set: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl ResourceName for PrincipalResource {
|
||||
@@ -31,79 +25,56 @@ impl ResourceName for PrincipalResource {
|
||||
impl Resource for PrincipalResource {
|
||||
type Prop = PrincipalPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
const IS_COLLECTION: bool = true;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[
|
||||
ResourcetypeInner(Some(rustical_dav::namespace::NS_DAV), "collection"),
|
||||
ResourcetypeInner(Some(rustical_dav::namespace::NS_DAV), "principal"),
|
||||
// https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/doc/Extensions/caldav-proxy.txt
|
||||
// ResourcetypeInner(
|
||||
// Some(rustical_dav::namespace::NS_CALENDARSERVER),
|
||||
// "calendar-proxy-write",
|
||||
// ),
|
||||
])
|
||||
}
|
||||
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
prop: &PrincipalPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
let principal_url = puri.principal_uri(&self.principal.id);
|
||||
|
||||
let home_set = CalendarHomeSet(
|
||||
user.memberships()
|
||||
.into_iter()
|
||||
.map(|principal| puri.principal_uri(principal))
|
||||
.flat_map(|principal_url| {
|
||||
self.home_set.iter().map(move |&home_name| {
|
||||
HrefElement::new(format!("{}{}/", &principal_url, home_name))
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
|
||||
Ok(match prop {
|
||||
PrincipalPropWrapperName::Principal(prop) => {
|
||||
PrincipalPropWrapper::Principal(match prop {
|
||||
PrincipalPropName::CalendarUserType => {
|
||||
PrincipalProp::CalendarUserType(self.principal.principal_type.to_owned())
|
||||
}
|
||||
PrincipalPropName::Displayname => PrincipalProp::Displayname(
|
||||
self.principal
|
||||
.displayname
|
||||
.to_owned()
|
||||
.unwrap_or(self.principal.id.to_owned()),
|
||||
),
|
||||
PrincipalPropName::PrincipalUrl => {
|
||||
PrincipalProp::PrincipalUrl(principal_url.into())
|
||||
}
|
||||
PrincipalPropName::CalendarHomeSet => PrincipalProp::CalendarHomeSet(
|
||||
CalendarHomeSet(if self.simplified_home_set {
|
||||
vec![principal_url.into()]
|
||||
} else {
|
||||
self.principal
|
||||
.memberships()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect()
|
||||
}),
|
||||
),
|
||||
PrincipalPropName::CalendarHomeSet => PrincipalProp::CalendarHomeSet(home_set),
|
||||
PrincipalPropName::CalendarUserAddressSet => {
|
||||
PrincipalProp::CalendarUserAddressSet(principal_url.into())
|
||||
}
|
||||
PrincipalPropName::GroupMemberSet => {
|
||||
PrincipalProp::GroupMemberSet(GroupMemberSet(
|
||||
self.members
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::GroupMembership => {
|
||||
PrincipalProp::GroupMembership(GroupMembership(
|
||||
self.principal
|
||||
.memberships_without_self()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::AlternateUriSet => PrincipalProp::AlternateUriSet,
|
||||
// PrincipalPropName::PrincipalCollectionSet => {
|
||||
// PrincipalProp::PrincipalCollectionSet(puri.principal_collection().into())
|
||||
// }
|
||||
PrincipalPropName::SupportedReportSet => {
|
||||
PrincipalProp::SupportedReportSet(SupportedReportSet::all())
|
||||
}
|
||||
})
|
||||
}
|
||||
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
|
||||
@@ -112,20 +83,11 @@ impl Resource for PrincipalResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
Some(
|
||||
self.principal
|
||||
.displayname
|
||||
.as_ref()
|
||||
.unwrap_or(&self.principal.id),
|
||||
)
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal.id)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_read(
|
||||
user.is_principal(&self.principal.id),
|
||||
))
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
use rustical_dav::{
|
||||
extensions::CommonPropertiesProp,
|
||||
xml::{GroupMemberSet, GroupMembership, HrefElement, SupportedReportSet},
|
||||
};
|
||||
use rustical_store::auth::PrincipalType;
|
||||
use rustical_dav::{extensions::CommonPropertiesProp, xml::HrefElement};
|
||||
use rustical_store::auth::user::PrincipalType;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
use strum_macros::VariantArray;
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropName")]
|
||||
pub enum PrincipalProp {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(String),
|
||||
|
||||
// Scheduling Extensions to CalDAV (RFC 6638)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV", skip_deserializing)]
|
||||
CalendarUserType(PrincipalType),
|
||||
@@ -18,25 +17,12 @@ pub enum PrincipalProp {
|
||||
// WebDAV Access Control (RFC 3744)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", rename = b"principal-URL")]
|
||||
PrincipalUrl(HrefElement),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMembership(GroupMembership),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMemberSet(GroupMemberSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", rename = b"alternate-URI-set")]
|
||||
AlternateUriSet,
|
||||
// #[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
// PrincipalCollectionSet(HrefElement),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
||||
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||
|
||||
// CalDAV (RFC 4791)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
|
||||
CalendarHomeSet(CalendarHomeSet),
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct CalendarHomeSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
||||
pub enum PrincipalPropWrapper {
|
||||
@@ -44,9 +30,5 @@ pub enum PrincipalPropWrapper {
|
||||
Common(CommonPropertiesProp),
|
||||
}
|
||||
|
||||
#[derive(XmlSerialize, PartialEq, Clone, VariantArray)]
|
||||
pub enum ReportMethod {
|
||||
// We don't actually support principal-match
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
PrincipalMatch,
|
||||
}
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct CalendarHomeSet(#[xml(ty = "untagged", flatten)] pub(super) Vec<HrefElement>);
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use crate::calendar::CalendarResourceService;
|
||||
use crate::calendar::resource::CalendarResource;
|
||||
use crate::calendar_set::{CalendarSetResource, CalendarSetResourceService};
|
||||
use crate::principal::PrincipalResource;
|
||||
use crate::{CalDavPrincipalUri, Error};
|
||||
use async_trait::async_trait;
|
||||
use axum::Router;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||
use rustical_store::auth::{AuthenticationProvider, User};
|
||||
use rustical_store::{CalendarStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -14,44 +13,43 @@ pub struct PrincipalResourceService<
|
||||
AP: AuthenticationProvider,
|
||||
S: SubscriptionStore,
|
||||
CS: CalendarStore,
|
||||
BS: CalendarStore,
|
||||
> {
|
||||
pub(crate) auth_provider: Arc<AP>,
|
||||
pub(crate) sub_store: Arc<S>,
|
||||
pub(crate) cal_store: Arc<CS>,
|
||||
// If true only return the principal as the calendar home set, otherwise also groups
|
||||
pub(crate) simplified_home_set: bool,
|
||||
pub(crate) birthday_store: Arc<BS>,
|
||||
}
|
||||
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> Clone
|
||||
for PrincipalResourceService<AP, S, CS>
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: CalendarStore> Clone
|
||||
for PrincipalResourceService<AP, S, CS, BS>
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
auth_provider: self.auth_provider.clone(),
|
||||
sub_store: self.sub_store.clone(),
|
||||
cal_store: self.cal_store.clone(),
|
||||
simplified_home_set: self.simplified_home_set,
|
||||
birthday_store: self.birthday_store.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> ResourceService
|
||||
for PrincipalResourceService<AP, S, CS>
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: CalendarStore>
|
||||
ResourceService for PrincipalResourceService<AP, S, CS, BS>
|
||||
{
|
||||
type PathComponents = (String,);
|
||||
type MemberType = CalendarResource;
|
||||
type MemberType = CalendarSetResource;
|
||||
type Resource = PrincipalResource;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CalDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access, calendar-proxy";
|
||||
const DAV_HEADER: &str = "1, 3, access-control, calendar-access";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
_show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let user = self
|
||||
.auth_provider
|
||||
@@ -59,9 +57,8 @@ impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> Resour
|
||||
.await?
|
||||
.ok_or(crate::Error::NotFound)?;
|
||||
Ok(PrincipalResource {
|
||||
members: self.auth_provider.list_members(&user.id).await?,
|
||||
principal: user,
|
||||
simplified_home_set: self.simplified_home_set,
|
||||
home_set: &["calendar", "birthdays"],
|
||||
})
|
||||
}
|
||||
|
||||
@@ -69,29 +66,45 @@ impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> Resour
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
) -> Result<Vec<Self::MemberType>, Self::Error> {
|
||||
let calendars = self.cal_store.get_calendars(principal).await?;
|
||||
|
||||
Ok(calendars
|
||||
.into_iter()
|
||||
.map(|cal| CalendarResource {
|
||||
read_only: self.cal_store.is_read_only(&cal.id),
|
||||
cal,
|
||||
})
|
||||
.collect())
|
||||
Ok(vec![
|
||||
CalendarSetResource {
|
||||
name: "calendar",
|
||||
principal: principal.to_owned(),
|
||||
read_only: false,
|
||||
},
|
||||
CalendarSetResource {
|
||||
name: "birthdays",
|
||||
principal: principal.to_owned(),
|
||||
read_only: true,
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
fn axum_router<State: Send + Sync + Clone + 'static>(self) -> axum::Router<State> {
|
||||
Router::new()
|
||||
.nest(
|
||||
"/{calendar_id}",
|
||||
CalendarResourceService::new(self.cal_store.clone(), self.sub_store.clone())
|
||||
.axum_router(),
|
||||
"/calendar",
|
||||
CalendarSetResourceService::new(
|
||||
"calendar",
|
||||
self.cal_store.clone(),
|
||||
self.sub_store.clone(),
|
||||
)
|
||||
.axum_router(),
|
||||
)
|
||||
.nest(
|
||||
"/birthdays",
|
||||
CalendarSetResourceService::new(
|
||||
"birthdays",
|
||||
self.birthday_store.clone(),
|
||||
self.sub_store.clone(),
|
||||
)
|
||||
.axum_router(),
|
||||
)
|
||||
.route_service("/", self.axum_service())
|
||||
}
|
||||
}
|
||||
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore> AxumMethods
|
||||
for PrincipalResourceService<AP, S, CS>
|
||||
impl<AP: AuthenticationProvider, S: SubscriptionStore, CS: CalendarStore, BS: CalendarStore>
|
||||
AxumMethods for PrincipalResourceService<AP, S, CS, BS>
|
||||
{
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::principal::PrincipalResourceService;
|
||||
use rstest::rstest;
|
||||
use rustical_dav::resource::ResourceService;
|
||||
use rustical_store_sqlite::{
|
||||
SqliteStore,
|
||||
calendar_store::SqliteCalendarStore,
|
||||
principal_store::SqlitePrincipalStore,
|
||||
tests::{get_test_calendar_store, get_test_principal_store, get_test_subscription_store},
|
||||
};
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_principal_resource(
|
||||
#[from(get_test_calendar_store)]
|
||||
#[future]
|
||||
cal_store: SqliteCalendarStore,
|
||||
#[from(get_test_principal_store)]
|
||||
#[future]
|
||||
auth_provider: SqlitePrincipalStore,
|
||||
#[from(get_test_subscription_store)]
|
||||
#[future]
|
||||
sub_store: SqliteStore,
|
||||
) {
|
||||
let service = PrincipalResourceService {
|
||||
cal_store: Arc::new(cal_store.await),
|
||||
sub_store: Arc::new(sub_store.await),
|
||||
auth_provider: Arc::new(auth_provider.await),
|
||||
simplified_home_set: false,
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
service
|
||||
.get_resource(&("invalid-user".to_owned(),), true)
|
||||
.await,
|
||||
Err(crate::Error::NotFound)
|
||||
));
|
||||
|
||||
let _principal_resource = service
|
||||
.get_resource(&("user".to_owned(),), true)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_propfind() {}
|
||||
33
crates/caldav/src/subscription.rs
Normal file
33
crates/caldav/src/subscription.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::{
|
||||
HttpResponse,
|
||||
web::{self, Data, Path},
|
||||
};
|
||||
use rustical_dav::xml::multistatus::PropstatElement;
|
||||
use rustical_store::SubscriptionStore;
|
||||
use rustical_xml::{XmlRootTag, XmlSerialize};
|
||||
|
||||
use crate::calendar::resource::CalendarProp;
|
||||
|
||||
async fn handle_delete<S: SubscriptionStore>(
|
||||
store: Data<S>,
|
||||
path: Path<String>,
|
||||
) -> Result<HttpResponse, rustical_store::Error> {
|
||||
let id = path.into_inner();
|
||||
store.delete_subscription(&id).await?;
|
||||
Ok(HttpResponse::NoContent().body("Unregistered"))
|
||||
}
|
||||
|
||||
pub fn subscription_resource<S: SubscriptionStore>(sub_store: Arc<S>) -> actix_web::Resource {
|
||||
web::resource("/subscription/{id}")
|
||||
.app_data(Data::from(sub_store))
|
||||
.name("subscription")
|
||||
.delete(handle_delete::<S>)
|
||||
}
|
||||
|
||||
#[derive(XmlSerialize, XmlRootTag)]
|
||||
#[xml(root = b"push-message", ns = "rustical_dav::namespace::NS_DAVPUSH")]
|
||||
pub struct PushMessage {
|
||||
propstat: PropstatElement<CalendarProp>,
|
||||
}
|
||||
@@ -4,7 +4,6 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
@@ -32,5 +31,3 @@ http.workspace = true
|
||||
tower-http.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
ical.workspace = true
|
||||
strum.workspace = true
|
||||
strum_macros.workspace = true
|
||||
|
||||
@@ -7,13 +7,12 @@ use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::TypedHeader;
|
||||
use axum_extra::headers::{ContentType, ETag, HeaderMapExt, IfNoneMatch};
|
||||
use http::Method;
|
||||
use http::{HeaderMap, StatusCode};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
use rustical_dav::resource::Resource;
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::AddressbookStore;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
|
||||
@@ -25,8 +24,7 @@ pub async fn get_object<AS: AddressbookStore>(
|
||||
object_id,
|
||||
}): Path<AddressObjectPathComponents>,
|
||||
State(AddressObjectResourceService { addr_store }): State<AddressObjectResourceService<AS>>,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
user: User,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(Error::Unauthorized);
|
||||
@@ -51,11 +49,7 @@ pub async fn get_object<AS: AddressbookStore>(
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ETag::from_str(&object.get_etag()).unwrap());
|
||||
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(object.get_vcf().to_owned())).unwrap())
|
||||
}
|
||||
Ok(resp.body(Body::new(object.get_vcf().to_owned())).unwrap())
|
||||
}
|
||||
|
||||
#[instrument(skip(addr_store, body))]
|
||||
@@ -66,7 +60,7 @@ pub async fn put_object<AS: AddressbookStore>(
|
||||
object_id,
|
||||
}): Path<AddressObjectPathComponents>,
|
||||
State(AddressObjectResourceService { addr_store }): State<AddressObjectResourceService<AS>>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
mut if_none_match: Option<TypedHeader<IfNoneMatch>>,
|
||||
header_map: HeaderMap,
|
||||
body: String,
|
||||
|
||||
@@ -13,7 +13,7 @@ use rustical_dav::{
|
||||
xml::Resourcetype,
|
||||
};
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
|
||||
#[derive(Clone, From, Into)]
|
||||
pub struct AddressObjectResource {
|
||||
@@ -30,11 +30,9 @@ impl ResourceName for AddressObjectResource {
|
||||
impl Resource for AddressObjectResource {
|
||||
type Prop = AddressObjectPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
|
||||
fn is_collection(&self) -> bool {
|
||||
false
|
||||
}
|
||||
const IS_COLLECTION: bool = false;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[])
|
||||
@@ -43,7 +41,7 @@ impl Resource for AddressObjectResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
prop: &AddressObjectPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
@@ -66,10 +64,6 @@ impl Resource for AddressObjectResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
self.object.get_full_name()
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal)
|
||||
}
|
||||
@@ -78,7 +72,7 @@ impl Resource for AddressObjectResource {
|
||||
Some(self.object.get_etag())
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.principal),
|
||||
))
|
||||
|
||||
@@ -5,7 +5,7 @@ use axum::{extract::Request, handler::Handler, response::Response};
|
||||
use derive_more::derive::Constructor;
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::{AddressbookStore, auth::Principal};
|
||||
use rustical_store::{AddressbookStore, auth::User};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::{convert::Infallible, sync::Arc};
|
||||
use tower::Service;
|
||||
@@ -37,7 +37,7 @@ impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS>
|
||||
type Resource = AddressObjectResource;
|
||||
type MemberType = AddressObjectResource;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CardDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||
@@ -49,11 +49,10 @@ impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS>
|
||||
addressbook_id,
|
||||
object_id,
|
||||
}: &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let object = self
|
||||
.addr_store
|
||||
.get_object(principal, addressbook_id, object_id, show_deleted)
|
||||
.get_object(principal, addressbook_id, object_id, false)
|
||||
.await?;
|
||||
Ok(AddressObjectResource {
|
||||
object,
|
||||
|
||||
@@ -5,12 +5,12 @@ use axum::body::Body;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::Response;
|
||||
use axum_extra::headers::{ContentType, HeaderMapExt};
|
||||
use http::{HeaderValue, Method, StatusCode, header};
|
||||
use http::{HeaderValue, 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::auth::User;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||
use std::str::FromStr;
|
||||
use tracing::instrument;
|
||||
@@ -19,8 +19,7 @@ use tracing::instrument;
|
||||
pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
user: Principal,
|
||||
method: Method,
|
||||
user: User,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(Error::Unauthorized);
|
||||
@@ -47,7 +46,7 @@ pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ContentType::from_str("text/vcard").unwrap());
|
||||
let filename = format!("{principal}_{addressbook_id}.vcf");
|
||||
let filename = format!("{}_{}.vcf", principal, addressbook_id);
|
||||
let filename = utf8_percent_encode(&filename, CONTROLS);
|
||||
hdrs.insert(
|
||||
header::CONTENT_DISPOSITION,
|
||||
@@ -56,9 +55,5 @@ pub async fn route_get<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
if matches!(method, Method::HEAD) {
|
||||
Ok(resp.body(Body::empty()).unwrap())
|
||||
} else {
|
||||
Ok(resp.body(Body::new(vcf)).unwrap())
|
||||
}
|
||||
Ok(resp.body(Body::new(vcf)).unwrap())
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_store::{Addressbook, AddressbookStore, SubscriptionStore, auth::User};
|
||||
use rustical_xml::{XmlDeserialize, XmlDocument, XmlRootTag};
|
||||
use tracing::instrument;
|
||||
|
||||
@@ -44,7 +44,7 @@ struct MkcolRequest {
|
||||
#[instrument(skip(addr_store))]
|
||||
pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
@@ -52,10 +52,8 @@ pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let mut request = MkcolRequest::parse_str(&body)?.set.prop;
|
||||
if let Some("") = request.displayname.as_deref() {
|
||||
request.displayname = None
|
||||
}
|
||||
let request = MkcolRequest::parse_str(&body)?;
|
||||
let request = request.set.prop;
|
||||
|
||||
let addressbook = Addressbook {
|
||||
id: addressbook_id.to_owned(),
|
||||
@@ -88,8 +86,15 @@ pub async fn route_mkcol<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
}
|
||||
}
|
||||
|
||||
addr_store.insert_addressbook(addressbook).await?;
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
match addr_store.insert_addressbook(addressbook).await {
|
||||
// TODO: The spec says we should return a mkcol-response.
|
||||
// However, it works without one but breaks on iPadOS when using an empty one :)
|
||||
Ok(()) => Ok(StatusCode::CREATED.into_response()),
|
||||
Err(err) => {
|
||||
dbg!(err.to_string());
|
||||
Err(err.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
pub mod get;
|
||||
pub mod mkcol;
|
||||
pub mod post;
|
||||
// pub mod post;
|
||||
pub mod get;
|
||||
pub mod put;
|
||||
pub mod report;
|
||||
|
||||
@@ -1,40 +1,33 @@
|
||||
use crate::Error;
|
||||
use crate::addressbook::AddressbookResourceService;
|
||||
use crate::addressbook::resource::AddressbookResource;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use rustical_dav::privileges::UserPrivilege;
|
||||
use rustical_dav::resource::Resource;
|
||||
use crate::addressbook::resource::AddressbookResourceService;
|
||||
use actix_web::http::header;
|
||||
use actix_web::web::{Data, Path};
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use rustical_dav_push::register::PushRegister;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::{AddressbookStore, Subscription, SubscriptionStore};
|
||||
use rustical_xml::XmlDocument;
|
||||
use tracing::instrument;
|
||||
use tracing_actix_web::RootSpan;
|
||||
|
||||
#[instrument(skip(resource_service))]
|
||||
pub async fn route_post<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addr_id)): Path<(String, String)>,
|
||||
user: Principal,
|
||||
State(resource_service): State<AddressbookResourceService<AS, S>>,
|
||||
#[instrument(parent = root_span.id(), skip(resource_service, root_span, req))]
|
||||
pub async fn route_post<A: AddressbookStore, S: SubscriptionStore>(
|
||||
path: Path<(String, String)>,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
user: User,
|
||||
resource_service: Data<AddressbookResourceService<A, S>>,
|
||||
root_span: RootSpan,
|
||||
req: HttpRequest,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let (principal, addressbook_id) = path.into_inner();
|
||||
if !user.is_principal(&principal) {
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let addressbook = resource_service
|
||||
.addr_store
|
||||
.get_addressbook(&principal, &addr_id, false)
|
||||
.get_addressbook(&principal, &addressbook_id, false)
|
||||
.await?;
|
||||
let addressbook_resource = AddressbookResource(addressbook);
|
||||
if !addressbook_resource
|
||||
.get_user_privileges(&user)?
|
||||
.has(&UserPrivilege::Read)
|
||||
{
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let request = PushRegister::parse_str(&body)?;
|
||||
let sub_id = uuid::Uuid::new_v4().to_string();
|
||||
|
||||
@@ -51,7 +44,7 @@ pub async fn route_post<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
.web_push_subscription
|
||||
.push_resource
|
||||
.to_owned(),
|
||||
topic: addressbook_resource.0.push_topic,
|
||||
topic: addressbook.push_topic,
|
||||
expiration: expires.naive_local(),
|
||||
public_key: request
|
||||
.subscription
|
||||
@@ -70,17 +63,13 @@ pub async fn route_post<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
.upsert_subscription(subscription)
|
||||
.await?;
|
||||
|
||||
// TODO: make nicer
|
||||
let location = format!("/push_subscription/{sub_id}");
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
HeaderMap::from_iter([
|
||||
(header::LOCATION, HeaderValue::from_str(&location).unwrap()),
|
||||
(
|
||||
header::EXPIRES,
|
||||
HeaderValue::from_str(&expires.to_rfc2822()).unwrap(),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.into_response())
|
||||
let location = req
|
||||
.resource_map()
|
||||
.url_for(&req, "subscription", &[sub_id])
|
||||
.unwrap();
|
||||
|
||||
Ok(HttpResponse::Created()
|
||||
.append_header((header::LOCATION, location.to_string()))
|
||||
.append_header((header::EXPIRES, expires.to_rfc2822()))
|
||||
.finish())
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ use http::StatusCode;
|
||||
use ical::VcardParser;
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::Addressbook;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::User};
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(addr_store))]
|
||||
pub async fn route_put<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
body: String,
|
||||
) -> Result<Response, Error> {
|
||||
if !user.is_principal(&principal) {
|
||||
|
||||
@@ -10,7 +10,7 @@ use rustical_dav::{
|
||||
xml::{MultistatusElement, PropfindType, multistatus::ResponseElement},
|
||||
};
|
||||
use rustical_ical::AddressObject;
|
||||
use rustical_store::{AddressbookStore, auth::Principal};
|
||||
use rustical_store::{AddressbookStore, auth::User};
|
||||
use rustical_xml::XmlDeserialize;
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
@@ -58,13 +58,12 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
|
||||
Ok((result, not_found))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
|
||||
addr_multiget: &AddressbookMultigetRequest,
|
||||
prop: &PropfindType<AddressObjectPropWrapperName>,
|
||||
path: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
addr_store: &AS,
|
||||
@@ -81,7 +80,7 @@ pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, prop, None, puri, user)?,
|
||||
.propfind(&path, prop, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use axum::{
|
||||
response::IntoResponse,
|
||||
};
|
||||
use rustical_dav::xml::{PropfindType, sync_collection::SyncCollectionRequest};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::Principal};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore, auth::User};
|
||||
use rustical_xml::{XmlDeserialize, XmlDocument};
|
||||
use sync_collection::handle_sync_collection;
|
||||
use tracing::instrument;
|
||||
@@ -37,7 +37,7 @@ impl ReportRequest {
|
||||
#[instrument(skip(addr_store))]
|
||||
pub async fn route_report_addressbook<AS: AddressbookStore, S: SubscriptionStore>(
|
||||
Path((principal, addressbook_id)): Path<(String, String)>,
|
||||
user: Principal,
|
||||
user: User,
|
||||
OriginalUri(uri): OriginalUri,
|
||||
Extension(puri): Extension<CardDavPrincipalUri>,
|
||||
State(AddressbookResourceService { addr_store, .. }): State<AddressbookResourceService<AS, S>>,
|
||||
|
||||
@@ -13,7 +13,7 @@ use rustical_dav::{
|
||||
};
|
||||
use rustical_store::{
|
||||
AddressbookStore,
|
||||
auth::Principal,
|
||||
auth::User,
|
||||
synctoken::{format_synctoken, parse_synctoken},
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
|
||||
sync_collection: &SyncCollectionRequest<AddressObjectPropWrapperName>,
|
||||
path: &str,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
addr_store: &AS,
|
||||
@@ -39,7 +39,7 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
|
||||
object,
|
||||
principal: principal.to_owned(),
|
||||
}
|
||||
.propfind(&path, &sync_collection.prop, None, puri, user)?,
|
||||
.propfind(&path, &sync_collection.prop, puri, user)?,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
use rustical_dav::{
|
||||
extensions::{CommonPropertiesProp, SyncTokenExtensionProp},
|
||||
xml::SupportedReportSet,
|
||||
};
|
||||
use rustical_dav::extensions::{CommonPropertiesProp, SyncTokenExtensionProp};
|
||||
use rustical_dav_push::DavPushExtensionProp;
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
use strum_macros::VariantArray;
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "AddressbookPropName")]
|
||||
pub enum AddressbookProp {
|
||||
// WebDAV (RFC 2518)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(Option<String>),
|
||||
|
||||
// CardDAV (RFC 6352)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
AddressbookDescription(Option<String>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
|
||||
SupportedAddressData(SupportedAddressData),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", skip_deserializing)]
|
||||
SupportedReportSet(SupportedReportSet<ReportMethod>),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", skip_deserializing)]
|
||||
SupportedReportSet(SupportedReportSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
MaxResourceSize(i64),
|
||||
}
|
||||
@@ -60,10 +60,37 @@ impl Default for SupportedAddressData {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq, VariantArray)]
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub enum ReportMethod {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
AddressbookMultiget,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
SyncCollection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportWrapper {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
report: ReportMethod,
|
||||
}
|
||||
|
||||
// RFC 3253 section-3.1.5
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportSet {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV", flatten)]
|
||||
supported_report: &'static [SupportedReportWrapper],
|
||||
}
|
||||
|
||||
impl Default for SupportedReportSet {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
supported_report: &[
|
||||
SupportedReportWrapper {
|
||||
report: ReportMethod::AddressbookMultiget,
|
||||
},
|
||||
SupportedReportWrapper {
|
||||
report: ReportMethod::SyncCollection,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::prop::SupportedAddressData;
|
||||
use super::prop::{SupportedAddressData, SupportedReportSet};
|
||||
use crate::Error;
|
||||
use crate::addressbook::prop::{
|
||||
AddressbookProp, AddressbookPropName, AddressbookPropWrapper, AddressbookPropWrapperName,
|
||||
@@ -7,10 +7,10 @@ use derive_more::derive::{From, Into};
|
||||
use rustical_dav::extensions::{CommonPropertiesExtension, SyncTokenExtension};
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{Resourcetype, ResourcetypeInner, SupportedReportSet};
|
||||
use rustical_dav::xml::{Resourcetype, ResourcetypeInner};
|
||||
use rustical_dav_push::DavPushExtension;
|
||||
use rustical_store::Addressbook;
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
|
||||
#[derive(Clone, Debug, From, Into)]
|
||||
pub struct AddressbookResource(pub(crate) Addressbook);
|
||||
@@ -36,11 +36,9 @@ impl DavPushExtension for AddressbookResource {
|
||||
impl Resource for AddressbookResource {
|
||||
type Prop = AddressbookPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
const IS_COLLECTION: bool = true;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[
|
||||
@@ -52,17 +50,20 @@ impl Resource for AddressbookResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
prop: &AddressbookPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
Ok(match prop {
|
||||
AddressbookPropWrapperName::Addressbook(prop) => {
|
||||
AddressbookPropWrapper::Addressbook(match prop {
|
||||
AddressbookPropName::Displayname => {
|
||||
AddressbookProp::Displayname(self.0.displayname.clone())
|
||||
}
|
||||
AddressbookPropName::MaxResourceSize => {
|
||||
AddressbookProp::MaxResourceSize(10000000)
|
||||
}
|
||||
AddressbookPropName::SupportedReportSet => {
|
||||
AddressbookProp::SupportedReportSet(SupportedReportSet::all())
|
||||
AddressbookProp::SupportedReportSet(SupportedReportSet::default())
|
||||
}
|
||||
AddressbookPropName::AddressbookDescription => {
|
||||
AddressbookProp::AddressbookDescription(self.0.description.to_owned())
|
||||
@@ -88,6 +89,10 @@ impl Resource for AddressbookResource {
|
||||
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
|
||||
match prop {
|
||||
AddressbookPropWrapper::Addressbook(prop) => match prop {
|
||||
AddressbookProp::Displayname(displayname) => {
|
||||
self.0.displayname = displayname;
|
||||
Ok(())
|
||||
}
|
||||
AddressbookProp::AddressbookDescription(description) => {
|
||||
self.0.description = description;
|
||||
Ok(())
|
||||
@@ -108,6 +113,10 @@ impl Resource for AddressbookResource {
|
||||
) -> Result<(), rustical_dav::Error> {
|
||||
match prop {
|
||||
AddressbookPropWrapperName::Addressbook(prop) => match prop {
|
||||
AddressbookPropName::Displayname => {
|
||||
self.0.displayname = None;
|
||||
Ok(())
|
||||
}
|
||||
AddressbookPropName::AddressbookDescription => {
|
||||
self.0.description = None;
|
||||
Ok(())
|
||||
@@ -126,19 +135,11 @@ impl Resource for AddressbookResource {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
self.0.displayname.as_deref()
|
||||
}
|
||||
fn set_displayname(&mut self, name: Option<String>) -> Result<(), rustical_dav::Error> {
|
||||
self.0.displayname = name;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.0.principal)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.0.principal),
|
||||
))
|
||||
|
||||
@@ -3,7 +3,6 @@ use super::methods::report::route_report_addressbook;
|
||||
use crate::address_object::AddressObjectResourceService;
|
||||
use crate::address_object::resource::AddressObjectResource;
|
||||
use crate::addressbook::methods::get::route_get;
|
||||
use crate::addressbook::methods::post::route_post;
|
||||
use crate::addressbook::methods::put::route_put;
|
||||
use crate::addressbook::resource::AddressbookResource;
|
||||
use crate::{CardDavPrincipalUri, Error};
|
||||
@@ -14,7 +13,7 @@ use axum::handler::Handler;
|
||||
use axum::response::Response;
|
||||
use futures_util::future::BoxFuture;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_store::auth::User;
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||
use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
@@ -51,19 +50,18 @@ impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
|
||||
type PathComponents = (String, String); // principal, addressbook_id
|
||||
type Resource = AddressbookResource;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CardDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook, webdav-push";
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal, addressbook_id): &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
) -> Result<Self::Resource, Error> {
|
||||
let addressbook = self
|
||||
.addr_store
|
||||
.get_addressbook(principal, addressbook_id, show_deleted)
|
||||
.get_addressbook(principal, addressbook_id, false)
|
||||
.await
|
||||
.map_err(|_e| Error::NotFound)?;
|
||||
Ok(addressbook.into())
|
||||
@@ -132,13 +130,6 @@ impl<AS: AddressbookStore, S: SubscriptionStore> AxumMethods for AddressbookReso
|
||||
})
|
||||
}
|
||||
|
||||
fn post() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||
Some(|state, req| {
|
||||
let mut service = Handler::with_state(route_post::<AS, S>, state);
|
||||
Box::pin(Service::call(&mut service, req))
|
||||
})
|
||||
}
|
||||
|
||||
fn put() -> Option<fn(Self, Request) -> BoxFuture<'static, Result<Response, Infallible>>> {
|
||||
Some(|state, req| {
|
||||
let mut service = Handler::with_state(route_put::<AS, S>, state);
|
||||
|
||||
@@ -9,7 +9,7 @@ use rustical_dav::resources::RootResourceService;
|
||||
use rustical_store::auth::middleware::AuthenticationLayer;
|
||||
use rustical_store::{
|
||||
AddressbookStore, SubscriptionStore,
|
||||
auth::{AuthenticationProvider, Principal},
|
||||
auth::{AuthenticationProvider, User},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -22,11 +22,8 @@ pub mod principal;
|
||||
pub struct CardDavPrincipalUri(&'static str);
|
||||
|
||||
impl PrincipalUri for CardDavPrincipalUri {
|
||||
fn principal_collection(&self) -> String {
|
||||
format!("{}/principal/", self.0)
|
||||
}
|
||||
fn principal_uri(&self, principal: &str) -> String {
|
||||
format!("{}{}/", self.principal_collection(), principal)
|
||||
format!("{}/principal/{}/", self.0, principal)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,12 +41,10 @@ pub fn carddav_router<AP: AuthenticationProvider, A: AddressbookStore, S: Subscr
|
||||
Router::new()
|
||||
.nest(
|
||||
prefix,
|
||||
RootResourceService::<_, Principal, CardDavPrincipalUri>::new(
|
||||
principal_service.clone(),
|
||||
)
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CardDavPrincipalUri(prefix))),
|
||||
RootResourceService::<_, User, CardDavPrincipalUri>::new(principal_service.clone())
|
||||
.axum_router()
|
||||
.layer(AuthenticationLayer::new(auth_provider))
|
||||
.layer(Extension(CardDavPrincipalUri(prefix))),
|
||||
)
|
||||
.route(
|
||||
"/.well-known/carddav",
|
||||
|
||||
@@ -2,10 +2,8 @@ use crate::Error;
|
||||
use rustical_dav::extensions::CommonPropertiesExtension;
|
||||
use rustical_dav::privileges::UserPrivilegeSet;
|
||||
use rustical_dav::resource::{PrincipalUri, Resource, ResourceName};
|
||||
use rustical_dav::xml::{
|
||||
GroupMemberSet, GroupMembership, HrefElement, Resourcetype, ResourcetypeInner,
|
||||
};
|
||||
use rustical_store::auth::Principal;
|
||||
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
|
||||
use rustical_store::auth::User;
|
||||
|
||||
mod service;
|
||||
pub use service::*;
|
||||
@@ -14,8 +12,7 @@ pub use prop::*;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PrincipalResource {
|
||||
principal: Principal,
|
||||
members: Vec<String>,
|
||||
principal: User,
|
||||
}
|
||||
|
||||
impl ResourceName for PrincipalResource {
|
||||
@@ -27,11 +24,9 @@ impl ResourceName for PrincipalResource {
|
||||
impl Resource for PrincipalResource {
|
||||
type Prop = PrincipalPropWrapper;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
const IS_COLLECTION: bool = true;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[
|
||||
@@ -43,46 +38,33 @@ impl Resource for PrincipalResource {
|
||||
fn get_prop(
|
||||
&self,
|
||||
puri: &impl PrincipalUri,
|
||||
user: &Principal,
|
||||
user: &User,
|
||||
prop: &PrincipalPropWrapperName,
|
||||
) -> Result<Self::Prop, Self::Error> {
|
||||
let principal_href = HrefElement::new(puri.principal_uri(&self.principal.id));
|
||||
let principal_href = HrefElement::new(puri.principal_uri(&user.id));
|
||||
|
||||
let home_set = AddressbookHomeSet(
|
||||
user.memberships()
|
||||
.into_iter()
|
||||
.map(|principal| puri.principal_uri(principal))
|
||||
.map(HrefElement::new)
|
||||
.collect(),
|
||||
);
|
||||
|
||||
Ok(match prop {
|
||||
PrincipalPropWrapperName::Principal(prop) => {
|
||||
PrincipalPropWrapper::Principal(match prop {
|
||||
PrincipalPropName::Displayname => PrincipalProp::Displayname(
|
||||
self.principal
|
||||
.displayname
|
||||
.to_owned()
|
||||
.unwrap_or(self.principal.id.to_owned()),
|
||||
),
|
||||
PrincipalPropName::PrincipalUrl => PrincipalProp::PrincipalUrl(principal_href),
|
||||
PrincipalPropName::AddressbookHomeSet => {
|
||||
PrincipalProp::AddressbookHomeSet(AddressbookHomeSet(
|
||||
self.principal
|
||||
.memberships()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
PrincipalProp::AddressbookHomeSet(home_set)
|
||||
}
|
||||
PrincipalPropName::PrincipalAddress => PrincipalProp::PrincipalAddress(None),
|
||||
PrincipalPropName::GroupMembership => {
|
||||
PrincipalProp::GroupMembership(GroupMembership(
|
||||
self.principal
|
||||
.memberships_without_self()
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::GroupMemberSet => {
|
||||
PrincipalProp::GroupMemberSet(GroupMemberSet(
|
||||
self.members
|
||||
.iter()
|
||||
.map(|principal| puri.principal_uri(principal).into())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
PrincipalPropName::AlternateUriSet => PrincipalProp::AlternateUriSet,
|
||||
PrincipalPropName::PrincipalCollectionSet => {
|
||||
PrincipalProp::PrincipalCollectionSet(puri.principal_collection().into())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -92,20 +74,11 @@ impl Resource for PrincipalResource {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
Some(
|
||||
self.principal
|
||||
.displayname
|
||||
.as_ref()
|
||||
.unwrap_or(&self.principal.id),
|
||||
)
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
Some(&self.principal.id)
|
||||
}
|
||||
|
||||
fn get_user_privileges(&self, user: &Principal) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
fn get_user_privileges(&self, user: &User) -> Result<UserPrivilegeSet, Self::Error> {
|
||||
Ok(UserPrivilegeSet::owner_only(
|
||||
user.is_principal(&self.principal.id),
|
||||
))
|
||||
|
||||
@@ -1,24 +1,19 @@
|
||||
use rustical_dav::{
|
||||
extensions::CommonPropertiesProp,
|
||||
xml::{GroupMemberSet, GroupMembership, HrefElement},
|
||||
};
|
||||
use rustical_dav::{extensions::CommonPropertiesProp, xml::HrefElement};
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlSerialize};
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct AddressbookHomeSet(#[xml(ty = "untagged", flatten)] pub(super) Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropName")]
|
||||
pub enum PrincipalProp {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
Displayname(String),
|
||||
|
||||
// WebDAV Access Control (RFC 3744)
|
||||
#[xml(rename = b"principal-URL")]
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
PrincipalUrl(HrefElement),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMembership(GroupMembership),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
GroupMemberSet(GroupMemberSet),
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV", rename = b"alternate-URI-set")]
|
||||
AlternateUriSet,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
PrincipalCollectionSet(HrefElement),
|
||||
|
||||
// CardDAV (RFC 6352)
|
||||
#[xml(ns = "rustical_dav::namespace::NS_CARDDAV")]
|
||||
@@ -27,9 +22,6 @@ pub enum PrincipalProp {
|
||||
PrincipalAddress(Option<HrefElement>),
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct AddressbookHomeSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumVariants, PropName)]
|
||||
#[xml(unit_variants_ident = "PrincipalPropWrapperName", untagged)]
|
||||
pub enum PrincipalPropWrapper {
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{CardDavPrincipalUri, Error};
|
||||
use async_trait::async_trait;
|
||||
use axum::Router;
|
||||
use rustical_dav::resource::{AxumMethods, ResourceService};
|
||||
use rustical_store::auth::{AuthenticationProvider, Principal};
|
||||
use rustical_store::auth::{AuthenticationProvider, User};
|
||||
use rustical_store::{AddressbookStore, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -51,7 +51,7 @@ impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> Reso
|
||||
type MemberType = AddressbookResource;
|
||||
type Resource = PrincipalResource;
|
||||
type Error = Error;
|
||||
type Principal = Principal;
|
||||
type Principal = User;
|
||||
type PrincipalUri = CardDavPrincipalUri;
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control, addressbook";
|
||||
@@ -59,17 +59,13 @@ impl<A: AddressbookStore, AP: AuthenticationProvider, S: SubscriptionStore> Reso
|
||||
async fn get_resource(
|
||||
&self,
|
||||
(principal,): &Self::PathComponents,
|
||||
_show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
let user = self
|
||||
.auth_provider
|
||||
.get_principal(principal)
|
||||
.await?
|
||||
.ok_or(crate::Error::NotFound)?;
|
||||
Ok(PrincipalResource {
|
||||
members: self.auth_provider.list_members(&user.id).await?,
|
||||
principal: user,
|
||||
})
|
||||
Ok(PrincipalResource { principal: user })
|
||||
}
|
||||
|
||||
async fn get_members(
|
||||
|
||||
@@ -4,7 +4,6 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
@@ -25,6 +24,3 @@ tracing.workspace = true
|
||||
tokio.workspace = true
|
||||
http.workspace = true
|
||||
headers.workspace = true
|
||||
strum.workspace = true
|
||||
matchit.workspace = true
|
||||
matchit-serde.workspace = true
|
||||
|
||||
@@ -28,9 +28,6 @@ pub enum Error {
|
||||
|
||||
#[error("Precondition Failed")]
|
||||
PreconditionFailed,
|
||||
|
||||
#[error("Forbidden")]
|
||||
Forbidden,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
@@ -52,7 +49,6 @@ impl Error {
|
||||
Error::PropReadOnly => StatusCode::CONFLICT,
|
||||
Error::PreconditionFailed => StatusCode::PRECONDITION_FAILED,
|
||||
Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::Forbidden => StatusCode::FORBIDDEN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,6 @@ pub enum CommonPropertiesProp {
|
||||
#[xml(skip_deserializing)]
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
Resourcetype(Resourcetype),
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
Displayname(Option<String>),
|
||||
|
||||
// WebDAV Current Principal Extension (RFC 5397)
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
@@ -39,9 +37,6 @@ pub trait CommonPropertiesExtension: Resource {
|
||||
CommonPropertiesPropName::Resourcetype => {
|
||||
CommonPropertiesProp::Resourcetype(self.get_resourcetype())
|
||||
}
|
||||
CommonPropertiesPropName::Displayname => {
|
||||
CommonPropertiesProp::Displayname(self.get_displayname().map(|s| s.to_string()))
|
||||
}
|
||||
CommonPropertiesPropName::CurrentUserPrincipal => {
|
||||
CommonPropertiesProp::CurrentUserPrincipal(
|
||||
principal_uri.principal_uri(principal.get_id()).into(),
|
||||
@@ -57,18 +52,12 @@ pub trait CommonPropertiesExtension: Resource {
|
||||
})
|
||||
}
|
||||
|
||||
fn set_prop(&mut self, prop: CommonPropertiesProp) -> Result<(), crate::Error> {
|
||||
match prop {
|
||||
CommonPropertiesProp::Displayname(name) => self.set_displayname(name),
|
||||
_ => Err(crate::Error::PropReadOnly),
|
||||
}
|
||||
fn set_prop(&self, _prop: CommonPropertiesProp) -> Result<(), crate::Error> {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
}
|
||||
|
||||
fn remove_prop(&mut self, prop: &CommonPropertiesPropName) -> Result<(), crate::Error> {
|
||||
match prop {
|
||||
CommonPropertiesPropName::Displayname => self.set_displayname(None),
|
||||
_ => Err(crate::Error::PropReadOnly),
|
||||
}
|
||||
fn remove_prop(&self, _prop: &CommonPropertiesPropName) -> Result<(), crate::Error> {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ use quick_xml::name::Namespace;
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/rfc3744
|
||||
#[derive(Debug, Clone, XmlSerialize, XmlDeserialize, Eq, Hash, PartialEq)]
|
||||
pub enum UserPrivilege {
|
||||
Read,
|
||||
@@ -16,12 +15,12 @@ pub enum UserPrivilege {
|
||||
}
|
||||
|
||||
impl XmlSerialize for UserPrivilegeSet {
|
||||
fn serialize(
|
||||
fn serialize<W: std::io::Write>(
|
||||
&self,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
#[derive(XmlSerialize)]
|
||||
pub struct FakeUserPrivilegeSet {
|
||||
@@ -35,6 +34,7 @@ impl XmlSerialize for UserPrivilegeSet {
|
||||
.serialize(ns, tag, namespaces, writer)
|
||||
}
|
||||
|
||||
#[allow(refining_impl_trait)]
|
||||
fn attributes<'a>(&self) -> Option<Vec<quick_xml::events::attributes::Attribute<'a>>> {
|
||||
None
|
||||
}
|
||||
@@ -47,12 +47,6 @@ pub struct UserPrivilegeSet {
|
||||
|
||||
impl UserPrivilegeSet {
|
||||
pub fn has(&self, privilege: &UserPrivilege) -> bool {
|
||||
if (privilege == &UserPrivilege::WriteProperties
|
||||
|| privilege == &UserPrivilege::WriteContent)
|
||||
&& self.privileges.contains(&UserPrivilege::Write)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
self.privileges.contains(privilege) || self.privileges.contains(&UserPrivilege::All)
|
||||
}
|
||||
|
||||
@@ -78,15 +72,6 @@ impl UserPrivilegeSet {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn owner_write_properties(is_owner: bool) -> Self {
|
||||
// Content is read-only but we can write properties
|
||||
if is_owner {
|
||||
Self::write_properties()
|
||||
} else {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_only() -> Self {
|
||||
Self {
|
||||
privileges: HashSet::from([
|
||||
@@ -96,17 +81,6 @@ impl UserPrivilegeSet {
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_properties() -> Self {
|
||||
Self {
|
||||
privileges: HashSet::from([
|
||||
UserPrivilege::Read,
|
||||
UserPrivilege::WriteProperties,
|
||||
UserPrivilege::ReadAcl,
|
||||
UserPrivilege::ReadCurrentUserPrivilegeSet,
|
||||
]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> From<[UserPrivilege; N]> for UserPrivilegeSet {
|
||||
|
||||
@@ -18,6 +18,11 @@ pub trait AxumMethods: Sized + Send + Sync + 'static {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn head() -> Option<MethodFunction<Self>> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn post() -> Option<MethodFunction<Self>> {
|
||||
None
|
||||
@@ -53,6 +58,8 @@ pub trait AxumMethods: Sized + Send + Sync + 'static {
|
||||
}
|
||||
if Self::get().is_some() {
|
||||
allow.push(Method::GET);
|
||||
}
|
||||
if Self::head().is_some() {
|
||||
allow.push(Method::HEAD);
|
||||
}
|
||||
if Self::post().is_some() {
|
||||
|
||||
@@ -72,11 +72,16 @@ where
|
||||
return svc(self.resource_service.clone(), req);
|
||||
}
|
||||
}
|
||||
"GET" | "HEAD" => {
|
||||
"GET" => {
|
||||
if let Some(svc) = RS::get() {
|
||||
return svc(self.resource_service.clone(), req);
|
||||
}
|
||||
}
|
||||
"HEAD" => {
|
||||
if let Some(svc) = RS::head() {
|
||||
return svc(self.resource_service.clone(), req);
|
||||
}
|
||||
}
|
||||
"POST" => {
|
||||
if let Some(svc) = RS::post() {
|
||||
return svc(self.resource_service.clone(), req);
|
||||
@@ -109,9 +114,6 @@ where
|
||||
}
|
||||
|
||||
async fn route_options<RS: ResourceService + AxumMethods>() -> Response<Body> {
|
||||
// Semantically NO_CONTENT would also make sense,
|
||||
// but GNOME Accounts only works when returning OK
|
||||
// https://gitlab.gnome.org/GNOME/gnome-online-accounts/-/blob/master/src/goabackend/goadavclient.c#L289
|
||||
let mut resp = Response::builder().status(StatusCode::OK);
|
||||
let headers = resp.headers_mut().unwrap();
|
||||
headers.insert("DAV", HeaderValue::from_static(RS::DAV_HEADER));
|
||||
|
||||
@@ -1,54 +1,25 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::{
|
||||
header::{Depth, Overwrite},
|
||||
resource::ResourceService,
|
||||
};
|
||||
use axum::{
|
||||
extract::{MatchedPath, Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::{HeaderMap, StatusCode, Uri};
|
||||
use matchit_serde::ParamsDeserializer;
|
||||
use serde::Deserialize;
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(path, resource_service,))]
|
||||
#[instrument(skip(_path, _resource_service,))]
|
||||
pub(crate) async fn axum_route_copy<R: ResourceService>(
|
||||
Path(path): Path<R::PathComponents>,
|
||||
State(resource_service): State<R>,
|
||||
Path(_path): Path<R::PathComponents>,
|
||||
State(_resource_service): State<R>,
|
||||
depth: Option<Depth>,
|
||||
principal: R::Principal,
|
||||
overwrite: Overwrite,
|
||||
matched_path: MatchedPath,
|
||||
header_map: HeaderMap,
|
||||
) -> Result<Response, R::Error> {
|
||||
let destination = header_map
|
||||
.get("Destination")
|
||||
.ok_or(crate::Error::Forbidden)?
|
||||
.to_str()
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
let destination_uri: Uri = destination.parse().map_err(|_| crate::Error::Forbidden)?;
|
||||
// TODO: Check that host also matches
|
||||
let destination = destination_uri.path();
|
||||
|
||||
let mut router = matchit::Router::new();
|
||||
router.insert(matched_path.as_str(), ()).unwrap();
|
||||
if let Ok(matchit::Match { params, .. }) = router.at(destination) {
|
||||
let params =
|
||||
matchit_serde::Params::try_from(¶ms).map_err(|_| crate::Error::Forbidden)?;
|
||||
let dest_path = R::PathComponents::deserialize(&ParamsDeserializer::new(params))
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
|
||||
if resource_service
|
||||
.copy_resource(&path, &dest_path, &principal, overwrite.is_true())
|
||||
.await?
|
||||
{
|
||||
// Overwritten
|
||||
Ok(StatusCode::NO_CONTENT.into_response())
|
||||
} else {
|
||||
// Not overwritten
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
}
|
||||
} else {
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
}
|
||||
// TODO: Actually implement, but to be WebDAV-compliant we must at least support this route but
|
||||
// can return a 403 error
|
||||
let _depth = depth.unwrap_or(Depth::Infinity);
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
}
|
||||
|
||||
@@ -45,11 +45,10 @@ pub async fn route_delete<R: ResourceService>(
|
||||
if_match: Option<IfMatch>,
|
||||
if_none_match: Option<IfNoneMatch>,
|
||||
) -> Result<(), R::Error> {
|
||||
let resource = resource_service.get_resource(path_components, true).await?;
|
||||
let resource = resource_service.get_resource(path_components).await?;
|
||||
|
||||
// Kind of a bodge since we don't get unbind from the parent
|
||||
let privileges = resource.get_user_privileges(principal)?;
|
||||
if !privileges.has(&UserPrivilege::WriteProperties) {
|
||||
if !privileges.has(&UserPrivilege::Write) {
|
||||
return Err(Error::Unauthorized.into());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,54 +1,25 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::StatusCode;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::{
|
||||
header::{Depth, Overwrite},
|
||||
resource::ResourceService,
|
||||
};
|
||||
use axum::{
|
||||
extract::{MatchedPath, Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::{HeaderMap, StatusCode, Uri};
|
||||
use matchit_serde::ParamsDeserializer;
|
||||
use serde::Deserialize;
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(skip(path, resource_service,))]
|
||||
#[instrument(skip(_path, _resource_service,))]
|
||||
pub(crate) async fn axum_route_move<R: ResourceService>(
|
||||
Path(path): Path<R::PathComponents>,
|
||||
State(resource_service): State<R>,
|
||||
Path(_path): Path<R::PathComponents>,
|
||||
State(_resource_service): State<R>,
|
||||
depth: Option<Depth>,
|
||||
principal: R::Principal,
|
||||
overwrite: Overwrite,
|
||||
matched_path: MatchedPath,
|
||||
header_map: HeaderMap,
|
||||
) -> Result<Response, R::Error> {
|
||||
let destination = header_map
|
||||
.get("Destination")
|
||||
.ok_or(crate::Error::Forbidden)?
|
||||
.to_str()
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
let destination_uri: Uri = destination.parse().map_err(|_| crate::Error::Forbidden)?;
|
||||
// TODO: Check that host also matches
|
||||
let destination = destination_uri.path();
|
||||
|
||||
let mut router = matchit::Router::new();
|
||||
router.insert(matched_path.as_str(), ()).unwrap();
|
||||
if let Ok(matchit::Match { params, .. }) = router.at(destination) {
|
||||
let params =
|
||||
matchit_serde::Params::try_from(¶ms).map_err(|_| crate::Error::Forbidden)?;
|
||||
let dest_path = R::PathComponents::deserialize(&ParamsDeserializer::new(params))
|
||||
.map_err(|_| crate::Error::Forbidden)?;
|
||||
|
||||
if resource_service
|
||||
.copy_resource(&path, &dest_path, &principal, overwrite.is_true())
|
||||
.await?
|
||||
{
|
||||
// Overwritten
|
||||
Ok(StatusCode::NO_CONTENT.into_response())
|
||||
} else {
|
||||
// Not overwritten
|
||||
Ok(StatusCode::CREATED.into_response())
|
||||
}
|
||||
} else {
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
}
|
||||
// TODO: Actually implement, but to be WebDAV-compliant we must at least support this route but
|
||||
// can return a 403 error
|
||||
let _depth = depth.unwrap_or(Depth::Infinity);
|
||||
Ok(StatusCode::FORBIDDEN.into_response())
|
||||
}
|
||||
|
||||
@@ -49,9 +49,7 @@ pub(crate) async fn route_propfind<R: ResourceService>(
|
||||
resource_service: &R,
|
||||
puri: &impl PrincipalUri,
|
||||
) -> Result<RSMultistatus<R>, R::Error> {
|
||||
let resource = resource_service
|
||||
.get_resource(path_components, false)
|
||||
.await?;
|
||||
let resource = resource_service.get_resource(path_components).await?;
|
||||
let privileges = resource.get_user_privileges(principal)?;
|
||||
if !privileges.has(&UserPrivilege::Read) {
|
||||
return Err(Error::Unauthorized.into());
|
||||
@@ -64,7 +62,6 @@ pub(crate) async fn route_propfind<R: ResourceService>(
|
||||
} else {
|
||||
PropfindElement {
|
||||
prop: PropfindType::Allprop,
|
||||
include: None,
|
||||
}
|
||||
};
|
||||
let propfind_member: PropfindElement<<<R::MemberType as Resource>::Prop as PropName>::Names> =
|
||||
@@ -73,31 +70,22 @@ pub(crate) async fn route_propfind<R: ResourceService>(
|
||||
} else {
|
||||
PropfindElement {
|
||||
prop: PropfindType::Allprop,
|
||||
include: None,
|
||||
}
|
||||
};
|
||||
|
||||
let mut member_responses = Vec::new();
|
||||
if depth != &Depth::Zero {
|
||||
// TODO: authorization check for member resources
|
||||
for member in resource_service.get_members(path_components).await? {
|
||||
member_responses.push(member.propfind(
|
||||
&format!("{}/{}", path.trim_end_matches('/'), member.get_name()),
|
||||
&propfind_member.prop,
|
||||
propfind_member.include.as_ref(),
|
||||
puri,
|
||||
principal,
|
||||
)?);
|
||||
}
|
||||
}
|
||||
|
||||
let response = resource.propfind(
|
||||
path,
|
||||
&propfind_self.prop,
|
||||
propfind_self.include.as_ref(),
|
||||
puri,
|
||||
principal,
|
||||
)?;
|
||||
let response = resource.propfind(path, &propfind_self.prop, puri, principal)?;
|
||||
|
||||
Ok(MultistatusElement {
|
||||
responses: vec![response],
|
||||
|
||||
@@ -85,9 +85,7 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
|
||||
operations,
|
||||
) = XmlDocument::parse_str(body).map_err(Error::XmlError)?;
|
||||
|
||||
let mut resource = resource_service
|
||||
.get_resource(path_components, false)
|
||||
.await?;
|
||||
let mut resource = resource_service.get_resource(path_components).await?;
|
||||
let privileges = resource.get_user_privileges(principal)?;
|
||||
if !privileges.has(&UserPrivilege::Write) {
|
||||
return Err(Error::Unauthorized.into());
|
||||
|
||||
@@ -18,7 +18,7 @@ mod methods;
|
||||
mod principal_uri;
|
||||
mod resource_service;
|
||||
|
||||
pub use axum_methods::{AxumMethods, MethodFunction};
|
||||
pub use axum_methods::AxumMethods;
|
||||
pub use axum_service::AxumService;
|
||||
pub use principal_uri::PrincipalUri;
|
||||
|
||||
@@ -37,7 +37,7 @@ pub trait Resource: Clone + Send + 'static {
|
||||
type Error: From<crate::Error>;
|
||||
type Principal: Principal;
|
||||
|
||||
fn is_collection(&self) -> bool;
|
||||
const IS_COLLECTION: bool;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype;
|
||||
|
||||
@@ -60,11 +60,6 @@ pub trait Resource: Clone + Send + 'static {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str>;
|
||||
fn set_displayname(&mut self, _name: Option<String>) -> Result<(), crate::Error> {
|
||||
Err(crate::Error::PropReadOnly)
|
||||
}
|
||||
|
||||
fn get_owner(&self) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
@@ -106,50 +101,45 @@ pub trait Resource: Clone + Send + 'static {
|
||||
&self,
|
||||
path: &str,
|
||||
prop: &PropfindType<<Self::Prop as PropName>::Names>,
|
||||
include: Option<&PropElement<<Self::Prop as PropName>::Names>>,
|
||||
principal_uri: &impl PrincipalUri,
|
||||
principal: &Self::Principal,
|
||||
) -> Result<ResponseElement<Self::Prop>, Self::Error> {
|
||||
// Collections have a trailing slash
|
||||
let mut path = path.to_string();
|
||||
if self.is_collection() && !path.ends_with('/') {
|
||||
if Self::IS_COLLECTION && !path.ends_with('/') {
|
||||
path.push('/');
|
||||
}
|
||||
|
||||
let (mut props, mut invalid_props): (HashSet<<Self::Prop as PropName>::Names>, Vec<_>) =
|
||||
match prop {
|
||||
PropfindType::Propname => {
|
||||
let props = Self::list_props()
|
||||
.into_iter()
|
||||
.map(|(ns, tag)| (ns.map(NamespaceOwned::from), tag.to_string()))
|
||||
.collect_vec();
|
||||
// TODO: Support include element
|
||||
let (props, invalid_props): (HashSet<<Self::Prop as PropName>::Names>, Vec<_>) = match prop
|
||||
{
|
||||
PropfindType::Propname => {
|
||||
let props = Self::list_props()
|
||||
.into_iter()
|
||||
.map(|(ns, tag)| (ns.map(NamespaceOwned::from), tag.to_string()))
|
||||
.collect_vec();
|
||||
|
||||
return Ok(ResponseElement {
|
||||
href: path.to_owned(),
|
||||
propstat: vec![PropstatWrapper::TagList(PropstatElement {
|
||||
prop: TagList::from(props),
|
||||
status: StatusCode::OK,
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
PropfindType::Allprop => (
|
||||
Self::list_props()
|
||||
.iter()
|
||||
.map(|(_ns, name)| <Self::Prop as PropName>::Names::from_str(name).unwrap())
|
||||
.collect(),
|
||||
vec![],
|
||||
),
|
||||
PropfindType::Prop(PropElement(valid_tags, invalid_tags)) => (
|
||||
valid_tags.iter().cloned().collect(),
|
||||
invalid_tags.to_owned(),
|
||||
),
|
||||
};
|
||||
|
||||
if let Some(PropElement(valid_tags, invalid_tags)) = include {
|
||||
props.extend(valid_tags.clone());
|
||||
invalid_props.extend(invalid_tags.to_owned());
|
||||
}
|
||||
return Ok(ResponseElement {
|
||||
href: path.to_owned(),
|
||||
propstat: vec![PropstatWrapper::TagList(PropstatElement {
|
||||
prop: TagList::from(props),
|
||||
status: StatusCode::OK,
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
PropfindType::Allprop => (
|
||||
Self::list_props()
|
||||
.iter()
|
||||
.map(|(_ns, name)| <Self::Prop as PropName>::Names::from_str(name).unwrap())
|
||||
.collect(),
|
||||
vec![],
|
||||
),
|
||||
PropfindType::Prop(PropElement(valid_tags, invalid_tags)) => (
|
||||
valid_tags.iter().cloned().collect(),
|
||||
invalid_tags.to_owned(),
|
||||
),
|
||||
};
|
||||
|
||||
let prop_responses = props
|
||||
.into_iter()
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
pub trait PrincipalUri: 'static + Clone + Send + Sync {
|
||||
fn principal_collection(&self) -> String;
|
||||
fn principal_uri(&self, principal: &str) -> String;
|
||||
}
|
||||
|
||||
@@ -9,13 +9,7 @@ use serde::Deserialize;
|
||||
|
||||
#[async_trait]
|
||||
pub trait ResourceService: Clone + Sized + Send + Sync + AxumMethods + 'static {
|
||||
type PathComponents: std::fmt::Debug
|
||||
+ for<'de> Deserialize<'de>
|
||||
+ Sized
|
||||
+ Send
|
||||
+ Sync
|
||||
+ Clone
|
||||
+ 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
||||
type PathComponents: for<'de> Deserialize<'de> + Sized + Send + Sync + Clone + 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
||||
type MemberType: Resource<Error = Self::Error, Principal = Self::Principal>
|
||||
+ super::ResourceName;
|
||||
type Resource: Resource<Error = Self::Error, Principal = Self::Principal>;
|
||||
@@ -34,8 +28,7 @@ pub trait ResourceService: Clone + Sized + Send + Sync + AxumMethods + 'static {
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
path: &Self::PathComponents,
|
||||
show_deleted: bool,
|
||||
_path: &Self::PathComponents,
|
||||
) -> Result<Self::Resource, Self::Error>;
|
||||
|
||||
async fn save_resource(
|
||||
@@ -54,28 +47,6 @@ pub trait ResourceService: Clone + Sized + Send + Sync + AxumMethods + 'static {
|
||||
Err(crate::Error::Unauthorized.into())
|
||||
}
|
||||
|
||||
// Returns whether an existing resource was overwritten
|
||||
async fn copy_resource(
|
||||
&self,
|
||||
_path: &Self::PathComponents,
|
||||
_destination: &Self::PathComponents,
|
||||
_user: &Self::Principal,
|
||||
_overwrite: bool,
|
||||
) -> Result<bool, Self::Error> {
|
||||
Err(crate::Error::Forbidden.into())
|
||||
}
|
||||
|
||||
// Returns whether an existing resource was overwritten
|
||||
async fn move_resource(
|
||||
&self,
|
||||
_path: &Self::PathComponents,
|
||||
_destination: &Self::PathComponents,
|
||||
_user: &Self::Principal,
|
||||
_overwrite: bool,
|
||||
) -> Result<bool, Self::Error> {
|
||||
Err(crate::Error::Forbidden.into())
|
||||
}
|
||||
|
||||
fn axum_service(self) -> AxumService<Self>
|
||||
where
|
||||
Self: AxumMethods,
|
||||
|
||||
@@ -24,9 +24,7 @@ impl<PR: Resource, P: Principal> Resource for RootResource<PR, P> {
|
||||
type Error = PR::Error;
|
||||
type Principal = P;
|
||||
|
||||
fn is_collection(&self) -> bool {
|
||||
true
|
||||
}
|
||||
const IS_COLLECTION: bool = true;
|
||||
|
||||
fn get_resourcetype(&self) -> Resourcetype {
|
||||
Resourcetype(&[ResourcetypeInner(
|
||||
@@ -35,10 +33,6 @@ impl<PR: Resource, P: Principal> Resource for RootResource<PR, P> {
|
||||
)])
|
||||
}
|
||||
|
||||
fn get_displayname(&self) -> Option<&str> {
|
||||
Some("RustiCal DAV root")
|
||||
}
|
||||
|
||||
fn get_prop(
|
||||
&self,
|
||||
principal_uri: &impl PrincipalUri,
|
||||
@@ -86,11 +80,7 @@ where
|
||||
|
||||
const DAV_HEADER: &str = "1, 3, access-control";
|
||||
|
||||
async fn get_resource(
|
||||
&self,
|
||||
_: &(),
|
||||
_show_deleted: bool,
|
||||
) -> Result<Self::Resource, Self::Error> {
|
||||
async fn get_resource(&self, _: &()) -> Result<Self::Resource, Self::Error> {
|
||||
Ok(RootResource::<PRS::Resource, P>::default())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
use crate::xml::HrefElement;
|
||||
use rustical_xml::{XmlDeserialize, XmlSerialize};
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct GroupMembership(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
|
||||
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone)]
|
||||
pub struct GroupMemberSet(#[xml(ty = "untagged", flatten)] pub Vec<HrefElement>);
|
||||
@@ -11,7 +11,3 @@ pub use tag_list::TagList;
|
||||
mod error;
|
||||
pub mod sync_collection;
|
||||
pub use error::ErrorElement;
|
||||
mod report_set;
|
||||
pub use report_set::SupportedReportSet;
|
||||
mod group;
|
||||
pub use group::*;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::xml::TagList;
|
||||
use headers::{CacheControl, ContentType, HeaderMapExt};
|
||||
use http::StatusCode;
|
||||
use quick_xml::name::Namespace;
|
||||
use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot};
|
||||
@@ -19,12 +18,12 @@ pub struct PropstatElement<PropType: XmlSerialize> {
|
||||
pub status: StatusCode,
|
||||
}
|
||||
|
||||
fn xml_serialize_status(
|
||||
fn xml_serialize_status<W: ::std::io::Write>(
|
||||
status: &StatusCode,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
XmlSerialize::serialize(&format!("HTTP/1.1 {}", status), ns, tag, namespaces, writer)
|
||||
}
|
||||
@@ -49,12 +48,12 @@ pub struct ResponseElement<PropstatType: XmlSerialize> {
|
||||
pub propstat: Vec<PropstatWrapper<PropstatType>>,
|
||||
}
|
||||
|
||||
fn xml_serialize_optional_status(
|
||||
fn xml_serialize_optional_status<W: ::std::io::Write>(
|
||||
val: &Option<StatusCode>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
XmlSerialize::serialize(
|
||||
&val.map(|status| format!("HTTP/1.1 {}", status)),
|
||||
@@ -110,16 +109,18 @@ impl<T1: XmlSerialize, T2: XmlSerialize> axum::response::IntoResponse
|
||||
{
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
use axum::body::Body;
|
||||
use http::header;
|
||||
|
||||
let output = match self.serialize_to_string() {
|
||||
Ok(out) => out,
|
||||
Err(err) => return crate::Error::from(err).into_response(),
|
||||
};
|
||||
let mut output: Vec<_> = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".into();
|
||||
let mut writer = quick_xml::Writer::new_with_indent(&mut output, b' ', 4);
|
||||
if let Err(err) = self.serialize_root(&mut writer) {
|
||||
return crate::Error::from(err).into_response();
|
||||
}
|
||||
|
||||
let mut resp = axum::response::Response::builder().status(StatusCode::MULTI_STATUS);
|
||||
let hdrs = resp.headers_mut().unwrap();
|
||||
hdrs.typed_insert(ContentType::xml());
|
||||
hdrs.typed_insert(CacheControl::new().with_no_cache());
|
||||
resp.headers_mut()
|
||||
.unwrap()
|
||||
.insert(header::CONTENT_TYPE, "application/xml".try_into().unwrap());
|
||||
resp.body(Body::from(output)).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,10 @@ use rustical_xml::XmlRootTag;
|
||||
pub struct PropfindElement<PN: XmlDeserialize> {
|
||||
#[xml(ty = "untagged")]
|
||||
pub prop: PropfindType<PN>,
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub include: Option<PropElement<PN>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
// pub struct PropElement<PN: XmlDeserialize = Propname>(#[xml(ty = "untagged", flatten)] pub Vec<PN>);
|
||||
pub struct PropElement<PN: XmlDeserialize>(
|
||||
// valid
|
||||
pub Vec<PN>,
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
use rustical_xml::XmlSerialize;
|
||||
use strum::VariantArray;
|
||||
|
||||
// RFC 3253 section-3.1.5
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct SupportedReportSet<T: XmlSerialize + 'static> {
|
||||
#[xml(flatten)]
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
supported_report: Vec<ReportWrapper<T>>,
|
||||
}
|
||||
|
||||
impl<T: XmlSerialize + Clone + 'static> SupportedReportSet<T> {
|
||||
pub fn new(methods: Vec<T>) -> Self {
|
||||
Self {
|
||||
supported_report: methods
|
||||
.into_iter()
|
||||
.map(|method| ReportWrapper { report: method })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all() -> Self
|
||||
where
|
||||
T: VariantArray,
|
||||
{
|
||||
Self::new(T::VARIANTS.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, XmlSerialize, PartialEq)]
|
||||
pub struct ReportWrapper<T: XmlSerialize> {
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
report: T,
|
||||
}
|
||||
@@ -23,23 +23,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_serialize_resourcetype() {
|
||||
let out = Document {
|
||||
let mut buf = Vec::new();
|
||||
let mut writer = quick_xml::Writer::new(&mut buf);
|
||||
Document {
|
||||
resourcetype: Resourcetype(&[
|
||||
ResourcetypeInner(Some(crate::namespace::NS_DAV), "displayname"),
|
||||
ResourcetypeInner(Some(crate::namespace::NS_CALENDARSERVER), "calendar-color"),
|
||||
]),
|
||||
}
|
||||
.serialize_to_string()
|
||||
.serialize_root(&mut writer)
|
||||
.unwrap();
|
||||
let out = String::from_utf8(buf).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<document>
|
||||
<resourcetype>
|
||||
<displayname xmlns="DAV:"/>
|
||||
<calendar-color xmlns="http://calendarserver.org/ns/"/>
|
||||
</resourcetype>
|
||||
</document>"#
|
||||
"<document><resourcetype><displayname xmlns=\"DAV:\"/><calendar-color xmlns=\"http://calendarserver.org/ns/\"/></resourcetype></document>"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlDeserialize, XmlRootTag};
|
||||
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlDeserialize};
|
||||
|
||||
use super::PropfindType;
|
||||
|
||||
@@ -32,35 +32,11 @@ impl ValueSerialize for SyncLevel {
|
||||
}
|
||||
}
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/rfc5323#section-5.17
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
pub struct LimitElement {
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub nresults: NresultsElement,
|
||||
}
|
||||
|
||||
impl From<u64> for LimitElement {
|
||||
fn from(value: u64) -> Self {
|
||||
Self {
|
||||
nresults: NresultsElement(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LimitElement> for u64 {
|
||||
fn from(value: LimitElement) -> Self {
|
||||
value.nresults.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq)]
|
||||
pub struct NresultsElement(#[xml(ty = "text")] u64);
|
||||
|
||||
#[derive(XmlDeserialize, Clone, Debug, PartialEq, XmlRootTag)]
|
||||
// <!ELEMENT sync-collection (sync-token, sync-level, limit?, prop)>
|
||||
// <!-- DAV:limit defined in RFC 5323, Section 5.17 -->
|
||||
// <!-- DAV:prop defined in RFC 4918, Section 14.18 -->
|
||||
#[xml(ns = "crate::namespace::NS_DAV", root = b"sync-collection")]
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub struct SyncCollectionRequest<PN: XmlDeserialize> {
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub sync_token: String,
|
||||
@@ -69,48 +45,5 @@ pub struct SyncCollectionRequest<PN: XmlDeserialize> {
|
||||
#[xml(ns = "crate::namespace::NS_DAV", ty = "untagged")]
|
||||
pub prop: PropfindType<PN>,
|
||||
#[xml(ns = "crate::namespace::NS_DAV")]
|
||||
pub limit: Option<LimitElement>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::xml::{
|
||||
PropElement, PropfindType,
|
||||
sync_collection::{SyncCollectionRequest, SyncLevel},
|
||||
};
|
||||
use rustical_xml::{EnumVariants, PropName, XmlDeserialize, XmlDocument};
|
||||
|
||||
const SYNC_COLLECTION_REQUEST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<sync-collection xmlns="DAV:">
|
||||
<sync-token />
|
||||
<sync-level>1</sync-level>
|
||||
<limit>
|
||||
<nresults>100</nresults>
|
||||
</limit>
|
||||
<prop>
|
||||
<getetag />
|
||||
</prop>
|
||||
</sync-collection>
|
||||
"#;
|
||||
|
||||
#[derive(XmlDeserialize, PropName, EnumVariants, PartialEq)]
|
||||
#[xml(unit_variants_ident = "TestPropName")]
|
||||
enum TestProp {
|
||||
Getetag(String),
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_sync_collection_request() {
|
||||
let request =
|
||||
SyncCollectionRequest::<TestPropName>::parse_str(SYNC_COLLECTION_REQUEST).unwrap();
|
||||
assert_eq!(
|
||||
request,
|
||||
SyncCollectionRequest {
|
||||
sync_token: "".to_owned(),
|
||||
sync_level: SyncLevel::One,
|
||||
prop: PropfindType::Prop(PropElement(vec![TestPropName::Getetag], vec![])),
|
||||
limit: Some(100.into())
|
||||
}
|
||||
)
|
||||
}
|
||||
pub limit: Option<u64>,
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use derive_more::derive::From;
|
||||
use quick_xml::{
|
||||
events::{BytesEnd, BytesStart, Event},
|
||||
name::Namespace,
|
||||
};
|
||||
use quick_xml::name::Namespace;
|
||||
use rustical_xml::{NamespaceOwned, XmlSerialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -10,39 +7,13 @@ use std::collections::HashMap;
|
||||
pub struct TagList(Vec<(Option<NamespaceOwned>, String)>);
|
||||
|
||||
impl XmlSerialize for TagList {
|
||||
fn serialize(
|
||||
fn serialize<W: std::io::Write>(
|
||||
&self,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<&mut Vec<u8>>,
|
||||
_ns: Option<Namespace>,
|
||||
_tag: Option<&[u8]>,
|
||||
_namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
let prefix = ns
|
||||
.map(|ns| namespaces.get(&ns))
|
||||
.unwrap_or(None)
|
||||
.map(|prefix| {
|
||||
if !prefix.is_empty() {
|
||||
[*prefix, b":"].concat()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
});
|
||||
let has_prefix = prefix.is_some();
|
||||
let tagname = tag.map(|tag| [&prefix.unwrap_or_default(), tag].concat());
|
||||
let qname = tagname
|
||||
.as_ref()
|
||||
.map(|tagname| ::quick_xml::name::QName(tagname));
|
||||
|
||||
if let Some(qname) = &qname {
|
||||
let mut bytes_start = BytesStart::from(qname.to_owned());
|
||||
if !has_prefix {
|
||||
if let Some(ns) = &ns {
|
||||
bytes_start.push_attribute((b"xmlns".as_ref(), ns.as_ref()));
|
||||
}
|
||||
}
|
||||
writer.write_event(Event::Start(bytes_start))?;
|
||||
}
|
||||
|
||||
for (ns, tag) in &self.0 {
|
||||
let mut el = writer.create_element(tag);
|
||||
if let Some(ns) = ns {
|
||||
@@ -50,13 +21,10 @@ impl XmlSerialize for TagList {
|
||||
}
|
||||
el.write_empty()?;
|
||||
}
|
||||
|
||||
if let Some(qname) = &qname {
|
||||
writer.write_event(Event::End(BytesEnd::from(qname.to_owned())))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(refining_impl_trait)]
|
||||
fn attributes<'a>(&self) -> Option<Vec<quick_xml::events::attributes::Attribute<'a>>> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
@@ -23,8 +22,3 @@ tokio.workspace = true
|
||||
rustical_dav.workspace = true
|
||||
rustical_store.workspace = true
|
||||
http.workspace = true
|
||||
base64.workspace = true
|
||||
rand.workspace = true
|
||||
ece.workspace = true
|
||||
axum.workspace = true
|
||||
openssl.workspace = true
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
routing::delete,
|
||||
};
|
||||
use http::StatusCode;
|
||||
use rustical_store::SubscriptionStore;
|
||||
use std::sync::Arc;
|
||||
|
||||
async fn handle_delete<S: SubscriptionStore>(
|
||||
State(store): State<Arc<S>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Response, rustical_store::Error> {
|
||||
store.delete_subscription(&id).await?;
|
||||
Ok((StatusCode::NO_CONTENT, "Unregistered").into_response())
|
||||
}
|
||||
|
||||
pub fn subscription_service<S: SubscriptionStore>(sub_store: Arc<S>) -> Router {
|
||||
Router::new()
|
||||
.route("/push_subscription/{id}", delete(handle_delete::<S>))
|
||||
.with_state(sub_store)
|
||||
}
|
||||
@@ -1,41 +1,14 @@
|
||||
mod extension;
|
||||
pub mod notifier;
|
||||
mod prop;
|
||||
pub mod register;
|
||||
use base64::Engine;
|
||||
use derive_more::Constructor;
|
||||
pub use extension::*;
|
||||
use http::{HeaderValue, Method, header};
|
||||
pub use prop::*;
|
||||
use reqwest::{Body, Url};
|
||||
use rustical_store::{
|
||||
CollectionOperation, CollectionOperationInfo, Subscription, SubscriptionStore,
|
||||
};
|
||||
use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot};
|
||||
use std::{collections::HashMap, sync::Arc, time::Duration};
|
||||
use rustical_store::{CollectionOperation, SubscriptionStore};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tracing::{error, warn};
|
||||
|
||||
mod endpoints;
|
||||
pub use endpoints::subscription_service;
|
||||
|
||||
#[derive(XmlSerialize, Debug)]
|
||||
pub struct ContentUpdate {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
sync_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(XmlSerialize, XmlRootTag, Debug)]
|
||||
#[xml(root = b"push-message", ns = "rustical_dav::namespace::NS_DAVPUSH")]
|
||||
#[xml(ns_prefix(
|
||||
rustical_dav::namespace::NS_DAVPUSH = b"",
|
||||
rustical_dav::namespace::NS_DAV = b"D",
|
||||
))]
|
||||
struct PushMessage {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAVPUSH")]
|
||||
topic: String,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAVPUSH")]
|
||||
content_update: Option<ContentUpdate>,
|
||||
}
|
||||
use tracing::error;
|
||||
|
||||
#[derive(Debug, Constructor)]
|
||||
pub struct DavPushController<S: SubscriptionStore> {
|
||||
@@ -45,176 +18,14 @@ pub struct DavPushController<S: SubscriptionStore> {
|
||||
|
||||
impl<S: SubscriptionStore> DavPushController<S> {
|
||||
pub async fn notifier(&self, mut recv: Receiver<CollectionOperation>) {
|
||||
loop {
|
||||
// Make sure we don't flood the subscribers
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
let mut messages = vec![];
|
||||
recv.recv_many(&mut messages, 100).await;
|
||||
|
||||
// Right now we just have to show the latest content update by topic
|
||||
// This might become more complicated in the future depending on what kind of updates
|
||||
// we add
|
||||
let mut latest_messages = HashMap::new();
|
||||
for message in messages {
|
||||
if matches!(message.data, CollectionOperationInfo::Content { .. }) {
|
||||
latest_messages.insert(message.topic.to_string(), message);
|
||||
while let Some(message) = recv.recv().await {
|
||||
let subscribers = match self.sub_store.get_subscriptions(&message.topic).await {
|
||||
Ok(subs) => subs,
|
||||
Err(err) => {
|
||||
error!("{err}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let messages = latest_messages.into_values();
|
||||
|
||||
for message in messages {
|
||||
self.send_message(message).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_message(&self, message: CollectionOperation) {
|
||||
let subscriptions = match self.sub_store.get_subscriptions(&message.topic).await {
|
||||
Ok(subs) => subs,
|
||||
Err(err) => {
|
||||
error!("{err}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if subscriptions.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
if matches!(message.data, CollectionOperationInfo::Delete) {
|
||||
// Collection has been deleted, but we cannot handle that
|
||||
return;
|
||||
}
|
||||
|
||||
let content_update = if let CollectionOperationInfo::Content { sync_token } = message.data {
|
||||
Some(ContentUpdate {
|
||||
sync_token: Some(sync_token),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let push_message = PushMessage {
|
||||
topic: message.topic,
|
||||
content_update,
|
||||
};
|
||||
|
||||
let payload = match push_message.serialize_to_string() {
|
||||
Ok(payload) => payload,
|
||||
Err(err) => {
|
||||
error!("Could not serialize push message: {}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for subsciption in subscriptions {
|
||||
if let Some(allowed_push_servers) = &self.allowed_push_servers {
|
||||
if let Ok(url) = Url::parse(&subsciption.push_resource) {
|
||||
let origin = url.origin().unicode_serialization();
|
||||
if !allowed_push_servers.contains(&origin) {
|
||||
warn!(
|
||||
"Deleting subscription {} on topic {} because the endpoint is not in the list of allowed push servers",
|
||||
subsciption.id, subsciption.topic
|
||||
);
|
||||
self.try_delete_subscription(&subsciption.id).await;
|
||||
}
|
||||
} else {
|
||||
warn!(
|
||||
"Deleting subscription {} on topic {} because of invalid URL",
|
||||
subsciption.id, subsciption.topic
|
||||
);
|
||||
self.try_delete_subscription(&subsciption.id).await;
|
||||
};
|
||||
}
|
||||
|
||||
if let Err(err) = self.send_payload(&payload, &subsciption).await {
|
||||
error!("An error occured sending out a push notification: {err}");
|
||||
if err.is_permament_error() {
|
||||
warn!(
|
||||
"Deleting subscription {} on topic {}",
|
||||
subsciption.id, subsciption.topic
|
||||
);
|
||||
self.try_delete_subscription(&subsciption.id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn try_delete_subscription(&self, sub_id: &str) {
|
||||
if let Err(err) = self.sub_store.delete_subscription(sub_id).await {
|
||||
error!("Error deleting subsciption: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_payload(
|
||||
&self,
|
||||
payload: &str,
|
||||
subsciption: &Subscription,
|
||||
) -> Result<(), NotifierError> {
|
||||
if subsciption.public_key_type != "p256dh" {
|
||||
return Err(NotifierError::InvalidPublicKeyType(
|
||||
subsciption.public_key_type.to_string(),
|
||||
));
|
||||
}
|
||||
let endpoint = subsciption.push_resource.parse().map_err(|_| {
|
||||
NotifierError::InvalidEndpointUrl(subsciption.push_resource.to_string())
|
||||
})?;
|
||||
let ua_public = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(&subsciption.public_key)
|
||||
.map_err(|_| NotifierError::InvalidKeyEncoding)?;
|
||||
let auth_secret = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(&subsciption.auth_secret)
|
||||
.map_err(|_| NotifierError::InvalidKeyEncoding)?;
|
||||
|
||||
let client = reqwest::ClientBuilder::new()
|
||||
.build()
|
||||
.map_err(NotifierError::from)?;
|
||||
|
||||
let payload = ece::encrypt(&ua_public, &auth_secret, payload.as_bytes())?;
|
||||
|
||||
let mut request = reqwest::Request::new(Method::POST, endpoint);
|
||||
*request.body_mut() = Some(Body::from(payload));
|
||||
let hdrs = request.headers_mut();
|
||||
hdrs.insert(
|
||||
header::CONTENT_ENCODING,
|
||||
HeaderValue::from_static("aes128gcm"),
|
||||
);
|
||||
hdrs.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/octet-stream"),
|
||||
);
|
||||
client.execute(request).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum NotifierError {
|
||||
#[error("Invalid public key type: {0}")]
|
||||
InvalidPublicKeyType(String),
|
||||
#[error("Invalid endpoint URL: {0}")]
|
||||
InvalidEndpointUrl(String),
|
||||
#[error("Invalid key encoding")]
|
||||
InvalidKeyEncoding,
|
||||
#[error(transparent)]
|
||||
EceError(#[from] ece::Error),
|
||||
#[error(transparent)]
|
||||
ReqwestError(#[from] reqwest::Error),
|
||||
}
|
||||
|
||||
impl NotifierError {
|
||||
// Decide whether the error should cause the subscription to be removed
|
||||
pub fn is_permament_error(&self) -> bool {
|
||||
match self {
|
||||
Self::InvalidPublicKeyType(_)
|
||||
| Self::InvalidEndpointUrl(_)
|
||||
| Self::InvalidKeyEncoding => true,
|
||||
Self::EceError(err) => matches!(
|
||||
err,
|
||||
ece::Error::InvalidAuthSecret | ece::Error::InvalidKeyLength
|
||||
),
|
||||
Self::ReqwestError(_) => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
147
crates/dav_push/src/notifier.rs
Normal file
147
crates/dav_push/src/notifier.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
use http::StatusCode;
|
||||
use reqwest::{
|
||||
Method, Request,
|
||||
header::{self, HeaderName, HeaderValue},
|
||||
};
|
||||
use rustical_dav::xml::multistatus::PropstatElement;
|
||||
use rustical_store::{CollectionOperation, CollectionOperationType, SubscriptionStore};
|
||||
use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot};
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tracing::{error, info, warn};
|
||||
// use web_push::{SubscriptionInfo, WebPushMessage, WebPushMessageBuilder};
|
||||
|
||||
#[derive(XmlSerialize, Debug)]
|
||||
struct PushMessageProp {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
topic: String,
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
sync_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(XmlSerialize, XmlRootTag, Debug)]
|
||||
#[xml(root = b"push-message", ns = "rustical_dav::namespace::NS_DAVPUSH")]
|
||||
#[xml(ns_prefix(
|
||||
rustical_dav::namespace::NS_DAVPUSH = b"",
|
||||
rustical_dav::namespace::NS_DAV = b"D",
|
||||
))]
|
||||
struct PushMessage {
|
||||
#[xml(ns = "rustical_dav::namespace::NS_DAV")]
|
||||
propstat: PropstatElement<PushMessageProp>,
|
||||
}
|
||||
|
||||
// pub fn build_request(message: WebPushMessage) -> Request {
|
||||
// // A little janky :)
|
||||
// let url = reqwest::Url::from_str(&message.endpoint.to_string()).unwrap();
|
||||
// let mut builder = Request::new(Method::POST, url);
|
||||
//
|
||||
// if let Some(topic) = message.topic {
|
||||
// builder
|
||||
// .headers_mut()
|
||||
// .insert("Topic", HeaderValue::from_str(topic.as_str()).unwrap());
|
||||
// }
|
||||
//
|
||||
// if let Some(payload) = message.payload {
|
||||
// builder.headers_mut().insert(
|
||||
// header::CONTENT_ENCODING,
|
||||
// HeaderValue::from_static(payload.content_encoding.to_str()),
|
||||
// );
|
||||
// builder.headers_mut().insert(
|
||||
// header::CONTENT_TYPE,
|
||||
// HeaderValue::from_static("application/octet-stream"),
|
||||
// );
|
||||
//
|
||||
// for (k, v) in payload.crypto_headers.into_iter() {
|
||||
// let v: &str = v.as_ref();
|
||||
// builder.headers_mut().insert(
|
||||
// HeaderName::from_static(k),
|
||||
// HeaderValue::from_str(&v).unwrap(),
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// *builder.body_mut() = Some(reqwest::Body::from(payload.content));
|
||||
// }
|
||||
// builder
|
||||
// }
|
||||
|
||||
pub async fn push_notifier(
|
||||
allowed_push_servers: Option<Vec<String>>,
|
||||
mut recv: Receiver<CollectionOperation>,
|
||||
sub_store: Arc<impl SubscriptionStore>,
|
||||
) {
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
while let Some(message) = recv.recv().await {
|
||||
let subscribers = match sub_store.get_subscriptions(&message.topic).await {
|
||||
Ok(subs) => subs,
|
||||
Err(err) => {
|
||||
error!("{err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let status = match message.r#type {
|
||||
CollectionOperationType::Object => StatusCode::OK,
|
||||
CollectionOperationType::Delete => StatusCode::NOT_FOUND,
|
||||
};
|
||||
|
||||
let push_message = PushMessage {
|
||||
propstat: PropstatElement {
|
||||
prop: PushMessageProp {
|
||||
topic: message.topic,
|
||||
sync_token: message.sync_token,
|
||||
},
|
||||
status,
|
||||
},
|
||||
};
|
||||
|
||||
let mut output: Vec<_> = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".into();
|
||||
let mut writer = quick_xml::Writer::new_with_indent(&mut output, b' ', 4);
|
||||
if let Err(err) = push_message.serialize_root(&mut writer) {
|
||||
error!("Could not serialize push message: {}", err);
|
||||
continue;
|
||||
}
|
||||
let payload = String::from_utf8(output).unwrap();
|
||||
// for subscriber in subscribers {
|
||||
// let push_resource = subscriber.push_resource;
|
||||
//
|
||||
// let sub_info = SubscriptionInfo {
|
||||
// endpoint: push_resource.to_owned(),
|
||||
// keys: web_push::SubscriptionKeys {
|
||||
// p256dh: subscriber.public_key,
|
||||
// auth: subscriber.auth_secret,
|
||||
// },
|
||||
// };
|
||||
// let mut builder = WebPushMessageBuilder::new(&sub_info);
|
||||
// builder.set_payload(web_push::ContentEncoding::Aes128Gcm, payload.as_bytes());
|
||||
// let push_message = builder.build().unwrap();
|
||||
// let request = build_request(push_message);
|
||||
//
|
||||
// let allowed = if let Some(allowed_push_servers) = &allowed_push_servers {
|
||||
// if let Ok(resource_url) = reqwest::Url::parse(&push_resource) {
|
||||
// let origin = resource_url.origin().ascii_serialization();
|
||||
// allowed_push_servers
|
||||
// .iter()
|
||||
// .any(|allowed_push_server| allowed_push_server == &origin)
|
||||
// } else {
|
||||
// warn!("Invalid push url: {push_resource}");
|
||||
// false
|
||||
// }
|
||||
// } else {
|
||||
// true
|
||||
// };
|
||||
//
|
||||
// if allowed {
|
||||
// info!("Sending a push message to {}: {}", push_resource, payload);
|
||||
// if let Err(err) = client.execute(request).await {
|
||||
// error!("{err}");
|
||||
// }
|
||||
// } else {
|
||||
// warn!(
|
||||
// "Not sending a push notification to {} since it's not allowed in dav_push::allowed_push_servers",
|
||||
// push_resource
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,8 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
description.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
default = []
|
||||
dev = ["tower-http/fs"]
|
||||
|
||||
[dependencies]
|
||||
tower.workspace = true
|
||||
http.workspace = true
|
||||
@@ -38,4 +33,3 @@ axum-extra.workspace = true
|
||||
headers.workspace = true
|
||||
tower-sessions.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
tower-http = { workspace = true, optional = true }
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"tasks": {
|
||||
"dev": "deno run -A --node-modules-dir npm:vite build --emptyOutDir --watch",
|
||||
"build": "deno run -A --node-modules-dir npm:vite build --emptyOutDir"
|
||||
},
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"ES2024",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
]
|
||||
},
|
||||
"imports": {
|
||||
"@deno/vite-plugin": "npm:@deno/vite-plugin@^1.0.4",
|
||||
"lit": "npm:lit@^3.2.1",
|
||||
"vite": "npm:vite@^6.1.1",
|
||||
"webdav": "npm:webdav@^5.8.0"
|
||||
}
|
||||
}
|
||||
436
crates/frontend/js-components/deno.lock
generated
436
crates/frontend/js-components/deno.lock
generated
@@ -1,436 +0,0 @@
|
||||
{
|
||||
"version": "4",
|
||||
"specifiers": {
|
||||
"npm:@deno/vite-plugin@^1.0.4": "1.0.4_vite@6.3.5__picomatch@4.0.2",
|
||||
"npm:lit@^3.2.1": "3.3.0",
|
||||
"npm:vite@*": "6.3.5_picomatch@4.0.2",
|
||||
"npm:vite@^6.1.1": "6.3.5_picomatch@4.0.2",
|
||||
"npm:webdav@^5.8.0": "5.8.0"
|
||||
},
|
||||
"npm": {
|
||||
"@buttercup/fetch@0.2.1": {
|
||||
"integrity": "sha512-sCgECOx8wiqY8NN1xN22BqqKzXYIG2AicNLlakOAI4f0WgyLVUbAigMf8CZhBtJxdudTcB1gD5lciqi44jwJvg==",
|
||||
"dependencies": [
|
||||
"node-fetch"
|
||||
]
|
||||
},
|
||||
"@deno/vite-plugin@1.0.4_vite@6.3.5__picomatch@4.0.2": {
|
||||
"integrity": "sha512-xg8YT8Wn2sGXSnJgiGTpBGX1Dov0c6fd1rAp8VsfrCUtyBRRWzwVMAnd3fQ4yq8h7LSVvJUxEFN4U421k/DQLA==",
|
||||
"dependencies": [
|
||||
"vite"
|
||||
]
|
||||
},
|
||||
"@esbuild/aix-ppc64@0.25.5": {
|
||||
"integrity": "sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA=="
|
||||
},
|
||||
"@esbuild/android-arm64@0.25.5": {
|
||||
"integrity": "sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg=="
|
||||
},
|
||||
"@esbuild/android-arm@0.25.5": {
|
||||
"integrity": "sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA=="
|
||||
},
|
||||
"@esbuild/android-x64@0.25.5": {
|
||||
"integrity": "sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw=="
|
||||
},
|
||||
"@esbuild/darwin-arm64@0.25.5": {
|
||||
"integrity": "sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ=="
|
||||
},
|
||||
"@esbuild/darwin-x64@0.25.5": {
|
||||
"integrity": "sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ=="
|
||||
},
|
||||
"@esbuild/freebsd-arm64@0.25.5": {
|
||||
"integrity": "sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw=="
|
||||
},
|
||||
"@esbuild/freebsd-x64@0.25.5": {
|
||||
"integrity": "sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw=="
|
||||
},
|
||||
"@esbuild/linux-arm64@0.25.5": {
|
||||
"integrity": "sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg=="
|
||||
},
|
||||
"@esbuild/linux-arm@0.25.5": {
|
||||
"integrity": "sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw=="
|
||||
},
|
||||
"@esbuild/linux-ia32@0.25.5": {
|
||||
"integrity": "sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA=="
|
||||
},
|
||||
"@esbuild/linux-loong64@0.25.5": {
|
||||
"integrity": "sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg=="
|
||||
},
|
||||
"@esbuild/linux-mips64el@0.25.5": {
|
||||
"integrity": "sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg=="
|
||||
},
|
||||
"@esbuild/linux-ppc64@0.25.5": {
|
||||
"integrity": "sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ=="
|
||||
},
|
||||
"@esbuild/linux-riscv64@0.25.5": {
|
||||
"integrity": "sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA=="
|
||||
},
|
||||
"@esbuild/linux-s390x@0.25.5": {
|
||||
"integrity": "sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ=="
|
||||
},
|
||||
"@esbuild/linux-x64@0.25.5": {
|
||||
"integrity": "sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw=="
|
||||
},
|
||||
"@esbuild/netbsd-arm64@0.25.5": {
|
||||
"integrity": "sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw=="
|
||||
},
|
||||
"@esbuild/netbsd-x64@0.25.5": {
|
||||
"integrity": "sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ=="
|
||||
},
|
||||
"@esbuild/openbsd-arm64@0.25.5": {
|
||||
"integrity": "sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw=="
|
||||
},
|
||||
"@esbuild/openbsd-x64@0.25.5": {
|
||||
"integrity": "sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg=="
|
||||
},
|
||||
"@esbuild/sunos-x64@0.25.5": {
|
||||
"integrity": "sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA=="
|
||||
},
|
||||
"@esbuild/win32-arm64@0.25.5": {
|
||||
"integrity": "sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw=="
|
||||
},
|
||||
"@esbuild/win32-ia32@0.25.5": {
|
||||
"integrity": "sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ=="
|
||||
},
|
||||
"@esbuild/win32-x64@0.25.5": {
|
||||
"integrity": "sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g=="
|
||||
},
|
||||
"@lit-labs/ssr-dom-shim@1.3.0": {
|
||||
"integrity": "sha512-nQIWonJ6eFAvUUrSlwyHDm/aE8PBDu5kRpL0vHMg6K8fK3Diq1xdPjTnsJSwxABhaZ+5eBi1btQB5ShUTKo4nQ=="
|
||||
},
|
||||
"@lit/reactive-element@2.1.0": {
|
||||
"integrity": "sha512-L2qyoZSQClcBmq0qajBVbhYEcG6iK0XfLn66ifLe/RfC0/ihpc+pl0Wdn8bJ8o+hj38cG0fGXRgSS20MuXn7qA==",
|
||||
"dependencies": [
|
||||
"@lit-labs/ssr-dom-shim"
|
||||
]
|
||||
},
|
||||
"@rollup/rollup-android-arm-eabi@4.43.0": {
|
||||
"integrity": "sha512-Krjy9awJl6rKbruhQDgivNbD1WuLb8xAclM4IR4cN5pHGAs2oIMMQJEiC3IC/9TZJ+QZkmZhlMO/6MBGxPidpw=="
|
||||
},
|
||||
"@rollup/rollup-android-arm64@4.43.0": {
|
||||
"integrity": "sha512-ss4YJwRt5I63454Rpj+mXCXicakdFmKnUNxr1dLK+5rv5FJgAxnN7s31a5VchRYxCFWdmnDWKd0wbAdTr0J5EA=="
|
||||
},
|
||||
"@rollup/rollup-darwin-arm64@4.43.0": {
|
||||
"integrity": "sha512-eKoL8ykZ7zz8MjgBenEF2OoTNFAPFz1/lyJ5UmmFSz5jW+7XbH1+MAgCVHy72aG59rbuQLcJeiMrP8qP5d/N0A=="
|
||||
},
|
||||
"@rollup/rollup-darwin-x64@4.43.0": {
|
||||
"integrity": "sha512-SYwXJgaBYW33Wi/q4ubN+ldWC4DzQY62S4Ll2dgfr/dbPoF50dlQwEaEHSKrQdSjC6oIe1WgzosoaNoHCdNuMg=="
|
||||
},
|
||||
"@rollup/rollup-freebsd-arm64@4.43.0": {
|
||||
"integrity": "sha512-SV+U5sSo0yujrjzBF7/YidieK2iF6E7MdF6EbYxNz94lA+R0wKl3SiixGyG/9Klab6uNBIqsN7j4Y/Fya7wAjQ=="
|
||||
},
|
||||
"@rollup/rollup-freebsd-x64@4.43.0": {
|
||||
"integrity": "sha512-J7uCsiV13L/VOeHJBo5SjasKiGxJ0g+nQTrBkAsmQBIdil3KhPnSE9GnRon4ejX1XDdsmK/l30IYLiAaQEO0Cg=="
|
||||
},
|
||||
"@rollup/rollup-linux-arm-gnueabihf@4.43.0": {
|
||||
"integrity": "sha512-gTJ/JnnjCMc15uwB10TTATBEhK9meBIY+gXP4s0sHD1zHOaIh4Dmy1X9wup18IiY9tTNk5gJc4yx9ctj/fjrIw=="
|
||||
},
|
||||
"@rollup/rollup-linux-arm-musleabihf@4.43.0": {
|
||||
"integrity": "sha512-ZJ3gZynL1LDSIvRfz0qXtTNs56n5DI2Mq+WACWZ7yGHFUEirHBRt7fyIk0NsCKhmRhn7WAcjgSkSVVxKlPNFFw=="
|
||||
},
|
||||
"@rollup/rollup-linux-arm64-gnu@4.43.0": {
|
||||
"integrity": "sha512-8FnkipasmOOSSlfucGYEu58U8cxEdhziKjPD2FIa0ONVMxvl/hmONtX/7y4vGjdUhjcTHlKlDhw3H9t98fPvyA=="
|
||||
},
|
||||
"@rollup/rollup-linux-arm64-musl@4.43.0": {
|
||||
"integrity": "sha512-KPPyAdlcIZ6S9C3S2cndXDkV0Bb1OSMsX0Eelr2Bay4EsF9yi9u9uzc9RniK3mcUGCLhWY9oLr6er80P5DE6XA=="
|
||||
},
|
||||
"@rollup/rollup-linux-loongarch64-gnu@4.43.0": {
|
||||
"integrity": "sha512-HPGDIH0/ZzAZjvtlXj6g+KDQ9ZMHfSP553za7o2Odegb/BEfwJcR0Sw0RLNpQ9nC6Gy8s+3mSS9xjZ0n3rhcYg=="
|
||||
},
|
||||
"@rollup/rollup-linux-powerpc64le-gnu@4.43.0": {
|
||||
"integrity": "sha512-gEmwbOws4U4GLAJDhhtSPWPXUzDfMRedT3hFMyRAvM9Mrnj+dJIFIeL7otsv2WF3D7GrV0GIewW0y28dOYWkmw=="
|
||||
},
|
||||
"@rollup/rollup-linux-riscv64-gnu@4.43.0": {
|
||||
"integrity": "sha512-XXKvo2e+wFtXZF/9xoWohHg+MuRnvO29TI5Hqe9xwN5uN8NKUYy7tXUG3EZAlfchufNCTHNGjEx7uN78KsBo0g=="
|
||||
},
|
||||
"@rollup/rollup-linux-riscv64-musl@4.43.0": {
|
||||
"integrity": "sha512-ruf3hPWhjw6uDFsOAzmbNIvlXFXlBQ4nk57Sec8E8rUxs/AI4HD6xmiiasOOx/3QxS2f5eQMKTAwk7KHwpzr/Q=="
|
||||
},
|
||||
"@rollup/rollup-linux-s390x-gnu@4.43.0": {
|
||||
"integrity": "sha512-QmNIAqDiEMEvFV15rsSnjoSmO0+eJLoKRD9EAa9rrYNwO/XRCtOGM3A5A0X+wmG+XRrw9Fxdsw+LnyYiZWWcVw=="
|
||||
},
|
||||
"@rollup/rollup-linux-x64-gnu@4.43.0": {
|
||||
"integrity": "sha512-jAHr/S0iiBtFyzjhOkAics/2SrXE092qyqEg96e90L3t9Op8OTzS6+IX0Fy5wCt2+KqeHAkti+eitV0wvblEoQ=="
|
||||
},
|
||||
"@rollup/rollup-linux-x64-musl@4.43.0": {
|
||||
"integrity": "sha512-3yATWgdeXyuHtBhrLt98w+5fKurdqvs8B53LaoKD7P7H7FKOONLsBVMNl9ghPQZQuYcceV5CDyPfyfGpMWD9mQ=="
|
||||
},
|
||||
"@rollup/rollup-win32-arm64-msvc@4.43.0": {
|
||||
"integrity": "sha512-wVzXp2qDSCOpcBCT5WRWLmpJRIzv23valvcTwMHEobkjippNf+C3ys/+wf07poPkeNix0paTNemB2XrHr2TnGw=="
|
||||
},
|
||||
"@rollup/rollup-win32-ia32-msvc@4.43.0": {
|
||||
"integrity": "sha512-fYCTEyzf8d+7diCw8b+asvWDCLMjsCEA8alvtAutqJOJp/wL5hs1rWSqJ1vkjgW0L2NB4bsYJrpKkiIPRR9dvw=="
|
||||
},
|
||||
"@rollup/rollup-win32-x64-msvc@4.43.0": {
|
||||
"integrity": "sha512-SnGhLiE5rlK0ofq8kzuDkM0g7FN1s5VYY+YSMTibP7CqShxCQvqtNxTARS4xX4PFJfHjG0ZQYX9iGzI3FQh5Aw=="
|
||||
},
|
||||
"@types/estree@1.0.7": {
|
||||
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ=="
|
||||
},
|
||||
"@types/trusted-types@2.0.7": {
|
||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="
|
||||
},
|
||||
"balanced-match@1.0.2": {
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
|
||||
},
|
||||
"base-64@1.0.0": {
|
||||
"integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg=="
|
||||
},
|
||||
"brace-expansion@2.0.2": {
|
||||
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
||||
"dependencies": [
|
||||
"balanced-match"
|
||||
]
|
||||
},
|
||||
"byte-length@1.0.2": {
|
||||
"integrity": "sha512-ovBpjmsgd/teRmgcPh23d4gJvxDoXtAzEL9xTfMU8Yc2kqCDb7L9jAG0XHl1nzuGl+h3ebCIF1i62UFyA9V/2Q=="
|
||||
},
|
||||
"charenc@0.0.2": {
|
||||
"integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA=="
|
||||
},
|
||||
"crypt@0.0.2": {
|
||||
"integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow=="
|
||||
},
|
||||
"data-uri-to-buffer@4.0.1": {
|
||||
"integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="
|
||||
},
|
||||
"entities@6.0.1": {
|
||||
"integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="
|
||||
},
|
||||
"esbuild@0.25.5": {
|
||||
"integrity": "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ==",
|
||||
"dependencies": [
|
||||
"@esbuild/aix-ppc64",
|
||||
"@esbuild/android-arm",
|
||||
"@esbuild/android-arm64",
|
||||
"@esbuild/android-x64",
|
||||
"@esbuild/darwin-arm64",
|
||||
"@esbuild/darwin-x64",
|
||||
"@esbuild/freebsd-arm64",
|
||||
"@esbuild/freebsd-x64",
|
||||
"@esbuild/linux-arm",
|
||||
"@esbuild/linux-arm64",
|
||||
"@esbuild/linux-ia32",
|
||||
"@esbuild/linux-loong64",
|
||||
"@esbuild/linux-mips64el",
|
||||
"@esbuild/linux-ppc64",
|
||||
"@esbuild/linux-riscv64",
|
||||
"@esbuild/linux-s390x",
|
||||
"@esbuild/linux-x64",
|
||||
"@esbuild/netbsd-arm64",
|
||||
"@esbuild/netbsd-x64",
|
||||
"@esbuild/openbsd-arm64",
|
||||
"@esbuild/openbsd-x64",
|
||||
"@esbuild/sunos-x64",
|
||||
"@esbuild/win32-arm64",
|
||||
"@esbuild/win32-ia32",
|
||||
"@esbuild/win32-x64"
|
||||
]
|
||||
},
|
||||
"fast-xml-parser@4.5.3": {
|
||||
"integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==",
|
||||
"dependencies": [
|
||||
"strnum"
|
||||
]
|
||||
},
|
||||
"fdir@6.4.6_picomatch@4.0.2": {
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"dependencies": [
|
||||
"picomatch"
|
||||
]
|
||||
},
|
||||
"fetch-blob@3.2.0": {
|
||||
"integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
|
||||
"dependencies": [
|
||||
"node-domexception",
|
||||
"web-streams-polyfill"
|
||||
]
|
||||
},
|
||||
"formdata-polyfill@4.0.10": {
|
||||
"integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
|
||||
"dependencies": [
|
||||
"fetch-blob"
|
||||
]
|
||||
},
|
||||
"fsevents@2.3.3": {
|
||||
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="
|
||||
},
|
||||
"hot-patcher@2.0.1": {
|
||||
"integrity": "sha512-ECg1JFG0YzehicQaogenlcs2qg6WsXQsxtnbr1i696u5tLUjtJdQAh0u2g0Q5YV45f263Ta1GnUJsc8WIfJf4Q=="
|
||||
},
|
||||
"is-buffer@1.1.6": {
|
||||
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="
|
||||
},
|
||||
"layerr@3.0.0": {
|
||||
"integrity": "sha512-tv754Ki2dXpPVApOrjTyRo4/QegVb9eVFq4mjqp4+NM5NaX7syQvN5BBNfV/ZpAHCEHV24XdUVrBAoka4jt3pA=="
|
||||
},
|
||||
"lit-element@4.2.0": {
|
||||
"integrity": "sha512-MGrXJVAI5x+Bfth/pU9Kst1iWID6GHDLEzFEnyULB/sFiRLgkd8NPK/PeeXxktA3T6EIIaq8U3KcbTU5XFcP2Q==",
|
||||
"dependencies": [
|
||||
"@lit-labs/ssr-dom-shim",
|
||||
"@lit/reactive-element",
|
||||
"lit-html"
|
||||
]
|
||||
},
|
||||
"lit-html@3.3.0": {
|
||||
"integrity": "sha512-RHoswrFAxY2d8Cf2mm4OZ1DgzCoBKUKSPvA1fhtSELxUERq2aQQ2h05pO9j81gS1o7RIRJ+CePLogfyahwmynw==",
|
||||
"dependencies": [
|
||||
"@types/trusted-types"
|
||||
]
|
||||
},
|
||||
"lit@3.3.0": {
|
||||
"integrity": "sha512-DGVsqsOIHBww2DqnuZzW7QsuCdahp50ojuDaBPC7jUDRpYoH0z7kHBBYZewRzer75FwtrkmkKk7iOAwSaWdBmw==",
|
||||
"dependencies": [
|
||||
"@lit/reactive-element",
|
||||
"lit-element",
|
||||
"lit-html"
|
||||
]
|
||||
},
|
||||
"md5@2.3.0": {
|
||||
"integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==",
|
||||
"dependencies": [
|
||||
"charenc",
|
||||
"crypt",
|
||||
"is-buffer"
|
||||
]
|
||||
},
|
||||
"minimatch@9.0.5": {
|
||||
"integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
|
||||
"dependencies": [
|
||||
"brace-expansion"
|
||||
]
|
||||
},
|
||||
"nanoid@3.3.11": {
|
||||
"integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="
|
||||
},
|
||||
"nested-property@4.0.0": {
|
||||
"integrity": "sha512-yFehXNWRs4cM0+dz7QxCd06hTbWbSkV0ISsqBfkntU6TOY4Qm3Q88fRRLOddkGh2Qq6dZvnKVAahfhjcUvLnyA=="
|
||||
},
|
||||
"node-domexception@1.0.0": {
|
||||
"integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="
|
||||
},
|
||||
"node-fetch@3.3.2": {
|
||||
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
|
||||
"dependencies": [
|
||||
"data-uri-to-buffer",
|
||||
"fetch-blob",
|
||||
"formdata-polyfill"
|
||||
]
|
||||
},
|
||||
"path-posix@1.0.0": {
|
||||
"integrity": "sha512-1gJ0WpNIiYcQydgg3Ed8KzvIqTsDpNwq+cjBCssvBtuTWjEqY1AW+i+OepiEMqDCzyro9B2sLAe4RBPajMYFiA=="
|
||||
},
|
||||
"picocolors@1.1.1": {
|
||||
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="
|
||||
},
|
||||
"picomatch@4.0.2": {
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg=="
|
||||
},
|
||||
"postcss@8.5.5": {
|
||||
"integrity": "sha512-d/jtm+rdNT8tpXuHY5MMtcbJFBkhXE6593XVR9UoGCH8jSFGci7jGvMGH5RYd5PBJW+00NZQt6gf7CbagJCrhg==",
|
||||
"dependencies": [
|
||||
"nanoid",
|
||||
"picocolors",
|
||||
"source-map-js"
|
||||
]
|
||||
},
|
||||
"querystringify@2.2.0": {
|
||||
"integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ=="
|
||||
},
|
||||
"requires-port@1.0.0": {
|
||||
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ=="
|
||||
},
|
||||
"rollup@4.43.0": {
|
||||
"integrity": "sha512-wdN2Kd3Twh8MAEOEJZsuxuLKCsBEo4PVNLK6tQWAn10VhsVewQLzcucMgLolRlhFybGxfclbPeEYBaP6RvUFGg==",
|
||||
"dependencies": [
|
||||
"@rollup/rollup-android-arm-eabi",
|
||||
"@rollup/rollup-android-arm64",
|
||||
"@rollup/rollup-darwin-arm64",
|
||||
"@rollup/rollup-darwin-x64",
|
||||
"@rollup/rollup-freebsd-arm64",
|
||||
"@rollup/rollup-freebsd-x64",
|
||||
"@rollup/rollup-linux-arm-gnueabihf",
|
||||
"@rollup/rollup-linux-arm-musleabihf",
|
||||
"@rollup/rollup-linux-arm64-gnu",
|
||||
"@rollup/rollup-linux-arm64-musl",
|
||||
"@rollup/rollup-linux-loongarch64-gnu",
|
||||
"@rollup/rollup-linux-powerpc64le-gnu",
|
||||
"@rollup/rollup-linux-riscv64-gnu",
|
||||
"@rollup/rollup-linux-riscv64-musl",
|
||||
"@rollup/rollup-linux-s390x-gnu",
|
||||
"@rollup/rollup-linux-x64-gnu",
|
||||
"@rollup/rollup-linux-x64-musl",
|
||||
"@rollup/rollup-win32-arm64-msvc",
|
||||
"@rollup/rollup-win32-ia32-msvc",
|
||||
"@rollup/rollup-win32-x64-msvc",
|
||||
"@types/estree",
|
||||
"fsevents"
|
||||
]
|
||||
},
|
||||
"source-map-js@1.2.1": {
|
||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="
|
||||
},
|
||||
"strnum@1.1.2": {
|
||||
"integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA=="
|
||||
},
|
||||
"tinyglobby@0.2.14_picomatch@4.0.2": {
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"dependencies": [
|
||||
"fdir",
|
||||
"picomatch"
|
||||
]
|
||||
},
|
||||
"url-join@5.0.0": {
|
||||
"integrity": "sha512-n2huDr9h9yzd6exQVnH/jU5mr+Pfx08LRXXZhkLLetAMESRj+anQsTAh940iMrIetKAmry9coFuZQ2jY8/p3WA=="
|
||||
},
|
||||
"url-parse@1.5.10": {
|
||||
"integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
|
||||
"dependencies": [
|
||||
"querystringify",
|
||||
"requires-port"
|
||||
]
|
||||
},
|
||||
"vite@6.3.5_picomatch@4.0.2": {
|
||||
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
|
||||
"dependencies": [
|
||||
"esbuild",
|
||||
"fdir",
|
||||
"fsevents",
|
||||
"picomatch",
|
||||
"postcss",
|
||||
"rollup",
|
||||
"tinyglobby"
|
||||
]
|
||||
},
|
||||
"web-streams-polyfill@3.3.3": {
|
||||
"integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="
|
||||
},
|
||||
"webdav@5.8.0": {
|
||||
"integrity": "sha512-iuFG7NamJ41Oshg4930iQgfIpRrUiatPWIekeznYgEf2EOraTRcDPTjy7gIOMtkdpKTaqPk1E68NO5PAGtJahA==",
|
||||
"dependencies": [
|
||||
"@buttercup/fetch",
|
||||
"base-64",
|
||||
"byte-length",
|
||||
"entities",
|
||||
"fast-xml-parser",
|
||||
"hot-patcher",
|
||||
"layerr",
|
||||
"md5",
|
||||
"minimatch",
|
||||
"nested-property",
|
||||
"node-fetch",
|
||||
"path-posix",
|
||||
"url-join",
|
||||
"url-parse"
|
||||
]
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dependencies": [
|
||||
"npm:@deno/vite-plugin@^1.0.4",
|
||||
"npm:lit@^3.2.1",
|
||||
"npm:vite@^6.1.1",
|
||||
"npm:webdav@^5.8.0"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite + Lit</title>
|
||||
<link rel="stylesheet" href="./src/index.css" />
|
||||
<script type="module" src="/src/my-element.ts"></script>
|
||||
</head>
|
||||
<body>
|
||||
<my-element>
|
||||
<h1>Vite + Lit</h1>
|
||||
</my-element>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,104 +0,0 @@
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators.js";
|
||||
import { Ref, createRef, ref } from 'lit/directives/ref.js';
|
||||
import { createClient } from "webdav";
|
||||
import { escapeXml } from ".";
|
||||
|
||||
@customElement("create-addressbook-form")
|
||||
export class CreateAddressbookForm extends LitElement {
|
||||
constructor() {
|
||||
super()
|
||||
|
||||
}
|
||||
|
||||
protected override createRenderRoot() {
|
||||
return this
|
||||
}
|
||||
|
||||
client = createClient("/carddav")
|
||||
|
||||
@property()
|
||||
user: string = ''
|
||||
@property()
|
||||
principal: string = ''
|
||||
@property()
|
||||
addr_id: string = ''
|
||||
@property()
|
||||
displayname: string = ''
|
||||
@property()
|
||||
description: string = ''
|
||||
|
||||
dialog: Ref<HTMLDialogElement> = createRef()
|
||||
form: Ref<HTMLFormElement> = createRef()
|
||||
|
||||
override render() {
|
||||
return html`
|
||||
<button @click=${() => this.dialog.value.showModal()}>Create addressbook</button>
|
||||
<dialog ${ref(this.dialog)}>
|
||||
<h3>Create addressbook</h3>
|
||||
<form @submit=${this.submit} ${ref(this.form)}>
|
||||
<label>
|
||||
principal (for group addressbooks)
|
||||
<select name="principal" value=${this.user} @change=${e => this.principal = e.target.value}>
|
||||
<option value=${this.user}>${this.user}</option>
|
||||
${window.rusticalUser.memberships.map(membership => html`
|
||||
<option value=${membership}>${membership}</option>
|
||||
`)}
|
||||
</select>
|
||||
</label>
|
||||
<br>
|
||||
<label>
|
||||
id
|
||||
<input type="text" name="id" @change=${e => this.addr_id = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
<label>
|
||||
Displayname
|
||||
<input type="text" name="displayname" value=${this.displayname} @change=${e => this.displayname = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
<label>
|
||||
Description
|
||||
<input type="text" name="description" @change=${e => this.description = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
<button type="submit">Create</button>
|
||||
<button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button>
|
||||
</form>
|
||||
</dialog>
|
||||
`
|
||||
}
|
||||
|
||||
async submit(e: SubmitEvent) {
|
||||
console.log(this.displayname)
|
||||
e.preventDefault()
|
||||
if (!this.addr_id) {
|
||||
alert("Empty id")
|
||||
return
|
||||
}
|
||||
if (!this.displayname) {
|
||||
alert("Empty displayname")
|
||||
return
|
||||
}
|
||||
await this.client.createDirectory(`/principal/${this.principal || this.user}/${this.addr_id}`, {
|
||||
data: `
|
||||
<mkcol xmlns="DAV:" xmlns:CARD="urn:ietf:params:xml:ns:carddav">
|
||||
<set>
|
||||
<prop>
|
||||
<displayname>${escapeXml(this.displayname)}</displayname>
|
||||
${this.description ? `<CARD:addressbook-description>${escapeXml(this.description)}</CARD:addressbook-description>` : ''}
|
||||
</prop>
|
||||
</set>
|
||||
</mkcol>
|
||||
`
|
||||
})
|
||||
window.location.reload()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'create-addressbook-form': CreateAddressbookForm
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators.js";
|
||||
import { Ref, createRef, ref } from 'lit/directives/ref.js';
|
||||
import { createClient } from "webdav";
|
||||
import { escapeXml } from ".";
|
||||
|
||||
@customElement("create-calendar-form")
|
||||
export class CreateCalendarForm extends LitElement {
|
||||
constructor() {
|
||||
super()
|
||||
}
|
||||
|
||||
protected override createRenderRoot() {
|
||||
return this
|
||||
}
|
||||
|
||||
client = createClient("/caldav")
|
||||
|
||||
@property()
|
||||
user: string = ''
|
||||
@property()
|
||||
principal: string = ''
|
||||
@property()
|
||||
cal_id: string = ''
|
||||
@property()
|
||||
displayname: string = ''
|
||||
@property()
|
||||
description: string = ''
|
||||
@property()
|
||||
color: string = ''
|
||||
@property()
|
||||
isSubscription: boolean = false
|
||||
@property()
|
||||
subscriptionUrl: string = ''
|
||||
@property()
|
||||
components: Set<"VEVENT" | "VTODO" | "VJOURNAL"> = new Set()
|
||||
|
||||
dialog: Ref<HTMLDialogElement> = createRef()
|
||||
form: Ref<HTMLFormElement> = createRef()
|
||||
|
||||
|
||||
override render() {
|
||||
return html`
|
||||
<button @click=${() => this.dialog.value.showModal()}>Create calendar</button>
|
||||
<dialog ${ref(this.dialog)}>
|
||||
<h3>Create calendar</h3>
|
||||
<form @submit=${this.submit} ${ref(this.form)}>
|
||||
<label>
|
||||
principal (for group calendars)
|
||||
<select name="principal" value=${this.user} @change=${e => this.principal = e.target.value}>
|
||||
<option value=${this.user}>${this.user}</option>
|
||||
${window.rusticalUser.memberships.map(membership => html`
|
||||
<option value=${membership}>${membership}</option>
|
||||
`)}
|
||||
</select>
|
||||
</label>
|
||||
<br>
|
||||
<label>
|
||||
id
|
||||
<input type="text" name="id" @change=${e => this.cal_id = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
<label>
|
||||
Displayname
|
||||
<input type="text" name="displayname" value=${this.displayname} @change=${e => this.displayname = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
<label>
|
||||
Description
|
||||
<input type="text" name="description" @change=${e => this.description = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
<label>
|
||||
Color
|
||||
<input type="color" name="color" @change=${e => this.color = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
<br>
|
||||
<label>
|
||||
Calendar is subscription to external calendar
|
||||
<input type="checkbox" name="is_subscription" @change=${e => this.isSubscription = e.target.checked} />
|
||||
</label>
|
||||
<br>
|
||||
${this.isSubscription ? html`
|
||||
<label>
|
||||
Subscription URL
|
||||
<input type="text" name="subscription_url" @change=${e => this.subscriptionUrl = e.target.value} />
|
||||
</label>
|
||||
<br>
|
||||
`: html``}
|
||||
<br>
|
||||
${["VEVENT", "VTODO", "VJOURNAL"].map(comp => html`
|
||||
<label>
|
||||
Support ${comp}
|
||||
<input type="checkbox" value=${comp} @change=${e => e.target.checked ? this.components.add(e.target.value) : this.components.delete(e.target.value)} />
|
||||
</label>
|
||||
<br>
|
||||
`)}
|
||||
<br>
|
||||
<button type="submit">Create</button>
|
||||
<button type="submit" @click=${event => { event.preventDefault(); this.dialog.value.close(); this.form.value.reset() }} class="cancel">Cancel</button>
|
||||
</form>
|
||||
</dialog>
|
||||
`
|
||||
}
|
||||
|
||||
async submit(e: SubmitEvent) {
|
||||
console.log(this.displayname)
|
||||
e.preventDefault()
|
||||
if (!this.cal_id) {
|
||||
alert("Empty id")
|
||||
return
|
||||
}
|
||||
if (!this.displayname) {
|
||||
alert("Empty displayname")
|
||||
return
|
||||
}
|
||||
if (!this.components.size) {
|
||||
alert("No calendar components selected")
|
||||
return
|
||||
}
|
||||
await this.client.createDirectory(`/principal/${this.principal || this.user}/${this.cal_id}`, {
|
||||
data: `
|
||||
<mkcol xmlns="DAV:" xmlns:CAL="urn:ietf:params:xml:ns:caldav" xmlns:CS="http://calendarserver.org/ns/" xmlns:ICAL="http://apple.com/ns/ical/">
|
||||
<set>
|
||||
<prop>
|
||||
<displayname>${escapeXml(this.displayname)}</displayname>
|
||||
${this.description ? `<CAL:calendar-description>${escapeXml(this.description)}</CAL:calendar-description>` : ''}
|
||||
${this.color ? `<ICAL:calendar-color>${escapeXml(this.color)}</ICAL:calendar-color>` : ''}
|
||||
${(this.isSubscription && this.subscriptionUrl) ? `<CS:source><href>${escapeXml(this.subscriptionUrl)}</href></CS:source>` : ''}
|
||||
<CAL:supported-calendar-component-set>
|
||||
${Array.from(this.components.keys()).map(comp => `<CAL:comp name="${escapeXml(comp)}" />`).join('\n')}
|
||||
</CAL:supported-calendar-component-set>
|
||||
</prop>
|
||||
</set>
|
||||
</mkcol>
|
||||
`
|
||||
})
|
||||
window.location.reload()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'create-calendar-form': CreateCalendarForm
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators.js";
|
||||
|
||||
@customElement("delete-button")
|
||||
export class DeleteButton extends LitElement {
|
||||
constructor() {
|
||||
super()
|
||||
}
|
||||
|
||||
@property({ type: Boolean })
|
||||
trash: boolean = false
|
||||
@property()
|
||||
href: string
|
||||
|
||||
protected createRenderRoot() {
|
||||
return this
|
||||
}
|
||||
|
||||
protected render() {
|
||||
let text = this.trash ? 'Move to trash' : 'Delete'
|
||||
return html`<button class="delete" @click=${e => this._onClick(e)}>${text}</button>`
|
||||
}
|
||||
|
||||
async _onClick(event: Event) {
|
||||
event.preventDefault()
|
||||
if (!this.trash && !confirm('Do you want to delete this collection permanently?')) {
|
||||
return
|
||||
}
|
||||
|
||||
let response = await fetch(this.href, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'X-No-Trashbin': this.trash ? '0' : '1'
|
||||
}
|
||||
})
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
alert('An error occured, look into the console')
|
||||
console.error(response)
|
||||
return
|
||||
}
|
||||
window.location.reload()
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
interface Window {
|
||||
rusticalUser: {
|
||||
id: String,
|
||||
displayname: String | null,
|
||||
memberships: Array<String>,
|
||||
principal_type: "individual" | "group" | "room" | String
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
export function escapeXml(unsafe: string): string {
|
||||
return unsafe.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
/// <reference types="vite/client" />
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user