mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-14 01:12:24 +00:00
Add initial carddav support
This commit is contained in:
90
crates/carddav/src/addressbook/methods/mkcol.rs
Normal file
90
crates/carddav/src/addressbook/methods/mkcol.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use crate::Error;
|
||||
use actix_web::web::Path;
|
||||
use actix_web::{web::Data, HttpResponse};
|
||||
use rustical_store::model::Addressbook;
|
||||
use rustical_store::{auth::User, AddressbookStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct Resourcetype {
|
||||
#[serde(rename = "CARD:addressbook", alias = "addressbook")]
|
||||
addressbook: Option<()>,
|
||||
collection: Option<()>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct MkcolAddressbookProp {
|
||||
resourcetype: Option<Resourcetype>,
|
||||
displayname: Option<String>,
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct PropElement<T: Serialize> {
|
||||
prop: T,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
#[serde(rename = "mkcol")]
|
||||
struct MkcolRequest {
|
||||
set: PropElement<MkcolAddressbookProp>,
|
||||
}
|
||||
|
||||
pub async fn route_mkcol<AS: AddressbookStore + ?Sized>(
|
||||
path: Path<(String, String)>,
|
||||
body: String,
|
||||
user: User,
|
||||
store: Data<RwLock<AS>>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let (principal, addressbook_id) = path.into_inner();
|
||||
if principal != user.id {
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let request: MkcolRequest = quick_xml::de::from_str(&body)?;
|
||||
let request = request.set.prop;
|
||||
|
||||
let addressbook = Addressbook {
|
||||
id: addressbook_id.to_owned(),
|
||||
principal: principal.to_owned(),
|
||||
displayname: request.displayname,
|
||||
description: request.description,
|
||||
deleted_at: None,
|
||||
synctoken: 0,
|
||||
};
|
||||
|
||||
match store
|
||||
.read()
|
||||
.await
|
||||
.get_addressbook(&principal, &addressbook_id)
|
||||
.await
|
||||
{
|
||||
Err(rustical_store::Error::NotFound) => {
|
||||
// No conflict, no worries
|
||||
}
|
||||
Ok(_) => {
|
||||
// oh no, there's a conflict
|
||||
return Ok(HttpResponse::Conflict().body("An addressbook already exists at this URI"));
|
||||
}
|
||||
Err(err) => {
|
||||
// some other error
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
match store.write().await.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(HttpResponse::Created()
|
||||
.insert_header(("Cache-Control", "no-cache"))
|
||||
.body("")),
|
||||
Err(err) => {
|
||||
dbg!(err.to_string());
|
||||
Err(err.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
2
crates/carddav/src/addressbook/methods/mod.rs
Normal file
2
crates/carddav/src/addressbook/methods/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod mkcol;
|
||||
pub mod report;
|
||||
@@ -0,0 +1,118 @@
|
||||
use crate::{
|
||||
address_object::resource::{AddressObjectProp, AddressObjectResource},
|
||||
principal::PrincipalResource,
|
||||
Error,
|
||||
};
|
||||
use actix_web::{
|
||||
dev::{Path, ResourceDef},
|
||||
http::StatusCode,
|
||||
HttpRequest,
|
||||
};
|
||||
use rustical_dav::{
|
||||
methods::propfind::{PropElement, PropfindType},
|
||||
resource::Resource,
|
||||
xml::{
|
||||
multistatus::{PropstatWrapper, ResponseElement},
|
||||
MultistatusElement,
|
||||
},
|
||||
};
|
||||
use rustical_store::{model::AddressObject, AddressbookStore};
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
#[allow(dead_code)]
|
||||
pub struct AddressbookMultigetRequest {
|
||||
#[serde(flatten)]
|
||||
prop: PropfindType,
|
||||
href: Vec<String>,
|
||||
}
|
||||
|
||||
pub async fn get_objects_addressbook_multiget<AS: AddressbookStore + ?Sized>(
|
||||
addressbook_multiget: &AddressbookMultigetRequest,
|
||||
principal_url: &str,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
store: &RwLock<AS>,
|
||||
) -> Result<(Vec<AddressObject>, Vec<String>), Error> {
|
||||
let resource_def =
|
||||
ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{addressbook_id}/{object_id}"));
|
||||
|
||||
let mut result = vec![];
|
||||
let mut not_found = vec![];
|
||||
|
||||
let store = store.read().await;
|
||||
for href in &addressbook_multiget.href {
|
||||
let mut path = Path::new(href.as_str());
|
||||
if !resource_def.capture_match_info(&mut path) {
|
||||
not_found.push(href.to_owned());
|
||||
};
|
||||
if path.get("addressbook_id").unwrap() != addressbook_id {
|
||||
not_found.push(href.to_owned());
|
||||
}
|
||||
let object_id = path.get("object_id").unwrap();
|
||||
match store.get_object(principal, addressbook_id, object_id).await {
|
||||
Ok(object) => result.push(object),
|
||||
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
|
||||
// TODO: Maybe add error handling on a per-object basis
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
}
|
||||
|
||||
Ok((result, not_found))
|
||||
}
|
||||
|
||||
pub async fn handle_addressbook_multiget<AS: AddressbookStore + ?Sized>(
|
||||
addr_multiget: AddressbookMultigetRequest,
|
||||
req: HttpRequest,
|
||||
principal: &str,
|
||||
cal_id: &str,
|
||||
addr_store: &RwLock<AS>,
|
||||
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> {
|
||||
let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap();
|
||||
let (objects, not_found) = get_objects_addressbook_multiget(
|
||||
&addr_multiget,
|
||||
&principal_url,
|
||||
principal,
|
||||
cal_id,
|
||||
addr_store,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let props = match addr_multiget.prop {
|
||||
PropfindType::Allprop => {
|
||||
vec!["allprop".to_owned()]
|
||||
}
|
||||
PropfindType::Propname => {
|
||||
vec!["propname".to_owned()]
|
||||
}
|
||||
PropfindType::Prop(PropElement { prop: prop_tags }) => prop_tags.into_inner(),
|
||||
};
|
||||
let props: Vec<&str> = props.iter().map(String::as_str).collect();
|
||||
|
||||
let mut responses = Vec::new();
|
||||
for object in objects {
|
||||
let path = format!("{}/{}", req.path(), object.get_id());
|
||||
responses.push(AddressObjectResource::from(object).propfind(
|
||||
&path,
|
||||
props.clone(),
|
||||
req.resource_map(),
|
||||
)?);
|
||||
}
|
||||
|
||||
let not_found_responses = not_found
|
||||
.into_iter()
|
||||
.map(|path| ResponseElement {
|
||||
href: path,
|
||||
status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(MultistatusElement {
|
||||
responses,
|
||||
member_responses: not_found_responses,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
68
crates/carddav/src/addressbook/methods/report/mod.rs
Normal file
68
crates/carddav/src/addressbook/methods/report/mod.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use crate::Error;
|
||||
use actix_web::{
|
||||
web::{Data, Path},
|
||||
HttpRequest, Responder,
|
||||
};
|
||||
use addressbook_multiget::{handle_addressbook_multiget, AddressbookMultigetRequest};
|
||||
use rustical_store::{auth::User, AddressbookStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sync_collection::{handle_sync_collection, SyncCollectionRequest};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::instrument;
|
||||
|
||||
mod addressbook_multiget;
|
||||
mod sync_collection;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum PropQuery {
|
||||
Allprop,
|
||||
Prop,
|
||||
Propname,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum ReportRequest {
|
||||
AddressbookMultiget(AddressbookMultigetRequest),
|
||||
SyncCollection(SyncCollectionRequest),
|
||||
}
|
||||
|
||||
#[instrument(skip(req, addr_store))]
|
||||
pub async fn route_report_addressbook<AS: AddressbookStore + ?Sized>(
|
||||
path: Path<(String, String)>,
|
||||
body: String,
|
||||
user: User,
|
||||
req: HttpRequest,
|
||||
addr_store: Data<RwLock<AS>>,
|
||||
) -> Result<impl Responder, Error> {
|
||||
let (principal, addressbook_id) = path.into_inner();
|
||||
if principal != user.id {
|
||||
return Err(Error::Unauthorized);
|
||||
}
|
||||
|
||||
let request: ReportRequest = quick_xml::de::from_str(&body)?;
|
||||
|
||||
Ok(match request.clone() {
|
||||
ReportRequest::AddressbookMultiget(addr_multiget) => {
|
||||
handle_addressbook_multiget(
|
||||
addr_multiget,
|
||||
req,
|
||||
&principal,
|
||||
&addressbook_id,
|
||||
&addr_store,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
ReportRequest::SyncCollection(sync_collection) => {
|
||||
handle_sync_collection(
|
||||
sync_collection,
|
||||
req,
|
||||
&principal,
|
||||
&addressbook_id,
|
||||
&addr_store,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
})
|
||||
}
|
||||
100
crates/carddav/src/addressbook/methods/report/sync_collection.rs
Normal file
100
crates/carddav/src/addressbook/methods/report/sync_collection.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use crate::{
|
||||
address_object::resource::{AddressObjectProp, AddressObjectResource},
|
||||
Error,
|
||||
};
|
||||
use actix_web::{http::StatusCode, HttpRequest};
|
||||
use rustical_dav::{
|
||||
methods::propfind::{PropElement, PropfindType},
|
||||
resource::Resource,
|
||||
xml::{
|
||||
multistatus::{PropstatWrapper, ResponseElement},
|
||||
MultistatusElement,
|
||||
},
|
||||
};
|
||||
use rustical_store::{
|
||||
model::addressbook::{format_synctoken, parse_synctoken},
|
||||
AddressbookStore,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum SyncLevel {
|
||||
#[serde(rename = "1")]
|
||||
One,
|
||||
Infinity,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
#[allow(dead_code)]
|
||||
// <!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 -->
|
||||
pub struct SyncCollectionRequest {
|
||||
sync_token: String,
|
||||
sync_level: SyncLevel,
|
||||
#[serde(flatten)]
|
||||
pub prop: PropfindType,
|
||||
limit: Option<u64>,
|
||||
}
|
||||
|
||||
pub async fn handle_sync_collection<AS: AddressbookStore + ?Sized>(
|
||||
sync_collection: SyncCollectionRequest,
|
||||
req: HttpRequest,
|
||||
principal: &str,
|
||||
addressbook_id: &str,
|
||||
addr_store: &RwLock<AS>,
|
||||
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> {
|
||||
let props = match sync_collection.prop {
|
||||
PropfindType::Allprop => {
|
||||
vec!["allprop".to_owned()]
|
||||
}
|
||||
PropfindType::Propname => {
|
||||
vec!["propname".to_owned()]
|
||||
}
|
||||
PropfindType::Prop(PropElement { prop: prop_tags }) => prop_tags.into_inner(),
|
||||
};
|
||||
let props: Vec<&str> = props.iter().map(String::as_str).collect();
|
||||
|
||||
let old_synctoken = parse_synctoken(&sync_collection.sync_token).unwrap_or(0);
|
||||
let (new_objects, deleted_objects, new_synctoken) = addr_store
|
||||
.read()
|
||||
.await
|
||||
.sync_changes(principal, addressbook_id, old_synctoken)
|
||||
.await?;
|
||||
|
||||
let mut responses = Vec::new();
|
||||
for object in new_objects {
|
||||
let path = AddressObjectResource::get_url(
|
||||
req.resource_map(),
|
||||
vec![principal, addressbook_id, &object.get_id()],
|
||||
)
|
||||
.unwrap();
|
||||
responses.push(AddressObjectResource::from(object).propfind(
|
||||
&path,
|
||||
props.clone(),
|
||||
req.resource_map(),
|
||||
)?);
|
||||
}
|
||||
|
||||
for object_id in deleted_objects {
|
||||
let path = AddressObjectResource::get_url(
|
||||
req.resource_map(),
|
||||
vec![principal, addressbook_id, &object_id],
|
||||
)
|
||||
.unwrap();
|
||||
responses.push(ResponseElement {
|
||||
href: path,
|
||||
status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
Ok(MultistatusElement {
|
||||
responses,
|
||||
sync_token: Some(format_synctoken(new_synctoken)),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user