Refactor: Rename uid to object_id

This commit is contained in:
Lennart
2024-10-14 10:13:32 +02:00
parent d32f50f472
commit d87b7dcb8d
24 changed files with 153 additions and 287 deletions

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "DELETE FROM calendarobjects WHERE cid = ? AND uid = ?",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "11d6a5b6c273bb60434061846f1fa292d8e9b7d898bbdd1169fe6d4edf1c5758"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "DELETE FROM calendars WHERE (principal, id) = (?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "2834e16e6a7acb58141a2433f7735d5e2bf913c30f9f3e7bd9fecc7d4376be0f"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "REPLACE INTO calendarobjects (principal, cid, uid, ics) VALUES (?, ?, ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 4
},
"nullable": []
},
"hash": "3f600740417b6fd02eb347c24302d3fe2f87dbb09c035f9ad665a5b0f6234701"
}

View File

@@ -1,26 +0,0 @@
{
"db_name": "SQLite",
"query": "SELECT uid, ics FROM calendarobjects WHERE (principal, cid, uid) = (?, ?, ?)",
"describe": {
"columns": [
{
"name": "uid",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "ics",
"ordinal": 1,
"type_info": "Text"
}
],
"parameters": {
"Right": 3
},
"nullable": [
false,
false
]
},
"hash": "3fb50028a203f9865d9440bfd5ef2bbcac61cee89d366aa8b0a9d535b49a3669"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "UPDATE calendars SET principal = ?, id = ?, displayname = ?, description = ?, \"order\" = ?, color = ?, timezone = ?\n WHERE (principal, id) = (?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 9
},
"nullable": []
},
"hash": "c7a56d737fc8627427d0be202c3c77bb95c1a25b6a3c0c389ef0ad4f468320ee"
}

View File

@@ -1,26 +0,0 @@
{
"db_name": "SQLite",
"query": "SELECT uid, ics FROM calendarobjects WHERE principal = ? AND cid = ? AND deleted_at IS NULL",
"describe": {
"columns": [
{
"name": "uid",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "ics",
"ordinal": 1,
"type_info": "Text"
}
],
"parameters": {
"Right": 2
},
"nullable": [
false,
false
]
},
"hash": "cbfcbe0e211d6104bd0120fb0eb28e6b8420f749a4071919bf2a83e26454a694"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "UPDATE calendarobjects SET deleted_at = datetime(), updated_at = datetime() WHERE (principal, cid, uid) = (?, ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "d162556505138438dd2b8ae14fffc9279d3a5c5386922fa63361d345bd4f93cb"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "UPDATE calendarobjects SET deleted_at = NULL, updated_at = datetime() WHERE (principal, cid, uid) = (?, ?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "deeee7413b3d03d3a68709ae10bf1d596f54d50f5421142dc02d2d7798be47e1"
}

View File

@@ -1,26 +0,0 @@
{
"db_name": "SQLite",
"query": "\n SELECT DISTINCT uid, max(0, synctoken) as \"synctoken!: i64\" from calendarobjectchangelog\n WHERE synctoken > ?\n ORDER BY synctoken ASC\n ",
"describe": {
"columns": [
{
"name": "uid",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "synctoken!: i64",
"ordinal": 1,
"type_info": "Null"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
null
]
},
"hash": "ec583c44374b71591c2a76881f5d42826c8b31f06d16a09687de70a881bec57f"
}

View File

@@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "\n INSERT INTO calendarobjectchangelog (principal, cid, uid, operation, synctoken)\n VALUES (?1, ?2, ?3, ?4, (\n SELECT synctoken FROM calendars WHERE (principal, id) = (?1, ?2)\n ))",
"describe": {
"columns": [],
"parameters": {
"Right": 4
},
"nullable": []
},
"hash": "f13006549869125c63731055d242bc29f66761eb52adcb16cde56d56ab5c1ecf"
}

View File

@@ -59,7 +59,7 @@ pub async fn route_mkcalendar<C: CalendarStore + ?Sized>(
user: User, user: User,
context: Data<CalDavContext<C>>, context: Data<CalDavContext<C>>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let (principal, cid) = path.into_inner(); let (principal, cal_id) = path.into_inner();
if principal != user.id { if principal != user.id {
return Err(Error::Unauthorized); return Err(Error::Unauthorized);
} }
@@ -68,7 +68,7 @@ pub async fn route_mkcalendar<C: CalendarStore + ?Sized>(
let request = request.set.prop; let request = request.set.prop;
let calendar = Calendar { let calendar = Calendar {
id: cid.to_owned(), id: cal_id.to_owned(),
principal: principal.to_owned(), principal: principal.to_owned(),
order: request.order.unwrap_or(0), order: request.order.unwrap_or(0),
displayname: request.displayname, displayname: request.displayname,
@@ -83,7 +83,7 @@ pub async fn route_mkcalendar<C: CalendarStore + ?Sized>(
.store .store
.read() .read()
.await .await
.get_calendar(&principal, &cid) .get_calendar(&principal, &cal_id)
.await .await
{ {
Err(rustical_store::Error::NotFound) => { Err(rustical_store::Error::NotFound) => {

View File

@@ -34,10 +34,11 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore + ?Sized>(
cal_query: &CalendarMultigetRequest, cal_query: &CalendarMultigetRequest,
principal_url: &str, principal_url: &str,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
store: &RwLock<C>, store: &RwLock<C>,
) -> Result<(Vec<CalendarObject>, Vec<String>), Error> { ) -> Result<(Vec<CalendarObject>, Vec<String>), Error> {
let resource_def = ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{cid}/{uid}")); let resource_def =
ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{cal_id}/{object_id}"));
let mut result = vec![]; let mut result = vec![];
let mut not_found = vec![]; let mut not_found = vec![];
@@ -48,11 +49,11 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore + ?Sized>(
if !resource_def.capture_match_info(&mut path) { if !resource_def.capture_match_info(&mut path) {
not_found.push(href.to_owned()); not_found.push(href.to_owned());
}; };
if path.get("cid").unwrap() != cid { if path.get("cal_id").unwrap() != cal_id {
not_found.push(href.to_owned()); not_found.push(href.to_owned());
} }
let uid = path.get("uid").unwrap(); let object_id = path.get("object_id").unwrap();
match store.get_object(principal, cid, uid).await { match store.get_object(principal, cal_id, object_id).await {
Ok(object) => result.push(object), Ok(object) => result.push(object),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()), Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
// TODO: Maybe add error handling on a per-object basis // TODO: Maybe add error handling on a per-object basis
@@ -67,12 +68,12 @@ pub async fn handle_calendar_multiget<C: CalendarStore + ?Sized>(
cal_multiget: CalendarMultigetRequest, cal_multiget: CalendarMultigetRequest,
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
cal_store: &RwLock<C>, cal_store: &RwLock<C>,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> {
let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap(); let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap();
let (objects, not_found) = let (objects, not_found) =
get_objects_calendar_multiget(&cal_multiget, &principal_url, principal, cid, cal_store) get_objects_calendar_multiget(&cal_multiget, &principal_url, principal, cal_id, cal_store)
.await?; .await?;
let props = match cal_multiget.prop { let props = match cal_multiget.prop {
@@ -88,7 +89,7 @@ pub async fn handle_calendar_multiget<C: CalendarStore + ?Sized>(
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in objects { for object in objects {
let path = format!("{}/{}", req.path(), object.get_uid()); let path = format!("{}/{}", req.path(), object.get_id());
responses.push(CalendarObjectResource::from(object).propfind( responses.push(CalendarObjectResource::from(object).propfind(
&path, &path,
props.clone(), props.clone(),

View File

@@ -194,10 +194,10 @@ pub struct CalendarQueryRequest {
pub async fn get_objects_calendar_query<C: CalendarStore + ?Sized>( pub async fn get_objects_calendar_query<C: CalendarStore + ?Sized>(
cal_query: &CalendarQueryRequest, cal_query: &CalendarQueryRequest,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
store: &RwLock<C>, store: &RwLock<C>,
) -> Result<Vec<CalendarObject>, Error> { ) -> Result<Vec<CalendarObject>, Error> {
let mut objects = store.read().await.get_objects(principal, cid).await?; let mut objects = store.read().await.get_objects(principal, cal_id).await?;
if let Some(filter) = &cal_query.filter { if let Some(filter) = &cal_query.filter {
objects.retain(|object| filter.matches(object)); objects.retain(|object| filter.matches(object));
} }
@@ -208,10 +208,10 @@ pub async fn handle_calendar_query<C: CalendarStore + ?Sized>(
cal_query: CalendarQueryRequest, cal_query: CalendarQueryRequest,
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
cal_store: &RwLock<C>, cal_store: &RwLock<C>,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> {
let objects = get_objects_calendar_query(&cal_query, principal, cid, cal_store).await?; let objects = get_objects_calendar_query(&cal_query, principal, cal_id, cal_store).await?;
let props = match cal_query.prop { let props = match cal_query.prop {
PropfindType::Allprop => { PropfindType::Allprop => {
@@ -228,7 +228,7 @@ pub async fn handle_calendar_query<C: CalendarStore + ?Sized>(
for object in objects { for object in objects {
let path = CalendarObjectResource::get_url( let path = CalendarObjectResource::get_url(
req.resource_map(), req.resource_map(),
vec![principal, cid, object.get_uid()], vec![principal, cal_id, object.get_id()],
) )
.unwrap(); .unwrap();
responses.push(CalendarObjectResource::from(object).propfind( responses.push(CalendarObjectResource::from(object).propfind(

View File

@@ -39,7 +39,7 @@ pub async fn route_report_calendar<C: CalendarStore + ?Sized>(
req: HttpRequest, req: HttpRequest,
cal_store: Data<RwLock<C>>, cal_store: Data<RwLock<C>>,
) -> Result<impl Responder, Error> { ) -> Result<impl Responder, Error> {
let (principal, cid) = path.into_inner(); let (principal, cal_id) = path.into_inner();
if principal != user.id { if principal != user.id {
return Err(Error::Unauthorized); return Err(Error::Unauthorized);
} }
@@ -48,13 +48,13 @@ pub async fn route_report_calendar<C: CalendarStore + ?Sized>(
Ok(match request.clone() { Ok(match request.clone() {
ReportRequest::CalendarQuery(cal_query) => { ReportRequest::CalendarQuery(cal_query) => {
handle_calendar_query(cal_query, req, &principal, &cid, &cal_store).await? handle_calendar_query(cal_query, req, &principal, &cal_id, &cal_store).await?
} }
ReportRequest::CalendarMultiget(cal_multiget) => { ReportRequest::CalendarMultiget(cal_multiget) => {
handle_calendar_multiget(cal_multiget, req, &principal, &cid, &cal_store).await? handle_calendar_multiget(cal_multiget, req, &principal, &cal_id, &cal_store).await?
} }
ReportRequest::SyncCollection(sync_collection) => { ReportRequest::SyncCollection(sync_collection) => {
handle_sync_collection(sync_collection, req, &principal, &cid, &cal_store).await? handle_sync_collection(sync_collection, req, &principal, &cal_id, &cal_store).await?
} }
}) })
} }

View File

@@ -46,7 +46,7 @@ pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
sync_collection: SyncCollectionRequest, sync_collection: SyncCollectionRequest,
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
cal_store: &RwLock<C>, cal_store: &RwLock<C>,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> {
let props = match sync_collection.prop { let props = match sync_collection.prop {
@@ -64,14 +64,14 @@ pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
let (new_objects, deleted_objects, new_synctoken) = cal_store let (new_objects, deleted_objects, new_synctoken) = cal_store
.read() .read()
.await .await
.sync_changes(principal, cid, old_synctoken) .sync_changes(principal, cal_id, old_synctoken)
.await?; .await?;
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in new_objects { for object in new_objects {
let path = CalendarObjectResource::get_url( let path = CalendarObjectResource::get_url(
req.resource_map(), req.resource_map(),
vec![principal, cid, &object.get_uid()], vec![principal, cal_id, &object.get_id()],
) )
.unwrap(); .unwrap();
responses.push(CalendarObjectResource::from(object).propfind( responses.push(CalendarObjectResource::from(object).propfind(
@@ -81,10 +81,12 @@ pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
)?); )?);
} }
for object_uid in deleted_objects { for object_id in deleted_objects {
let path = let path = CalendarObjectResource::get_url(
CalendarObjectResource::get_url(req.resource_map(), vec![principal, cid, &object_uid]) req.resource_map(),
.unwrap(); vec![principal, cal_id, &object_id],
)
.unwrap();
responses.push(ResponseElement { responses.push(ResponseElement {
href: path, href: path,
status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)), status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)),

View File

@@ -273,7 +273,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
( (
CalendarObjectResource::get_url( CalendarObjectResource::get_url(
rmap, rmap,
vec![&self.principal, &self.calendar_id, object.get_uid()], vec![&self.principal, &self.calendar_id, object.get_id()],
) )
.unwrap(), .unwrap(),
object.into(), object.into(),

View File

@@ -22,8 +22,8 @@ pub async fn get_event<C: CalendarStore + ?Sized>(
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let CalendarObjectPathComponents { let CalendarObjectPathComponents {
principal, principal,
cid, cal_id,
uid, object_id,
} = path.into_inner(); } = path.into_inner();
if user.id != principal { if user.id != principal {
@@ -34,7 +34,7 @@ pub async fn get_event<C: CalendarStore + ?Sized>(
.store .store
.read() .read()
.await .await
.get_calendar(&principal, &cid) .get_calendar(&principal, &cal_id)
.await?; .await?;
if user.id != calendar.principal { if user.id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
@@ -44,7 +44,7 @@ pub async fn get_event<C: CalendarStore + ?Sized>(
.store .store
.read() .read()
.await .await
.get_object(&principal, &cid, &uid) .get_object(&principal, &cal_id, &object_id)
.await?; .await?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
@@ -64,8 +64,8 @@ pub async fn put_event<C: CalendarStore + ?Sized>(
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let CalendarObjectPathComponents { let CalendarObjectPathComponents {
principal, principal,
cid, cal_id,
uid, object_id,
} = path.into_inner(); } = path.into_inner();
if user.id != principal { if user.id != principal {
@@ -76,7 +76,7 @@ pub async fn put_event<C: CalendarStore + ?Sized>(
.store .store
.read() .read()
.await .await
.get_calendar(&principal, &cid) .get_calendar(&principal, &cal_id)
.await?; .await?;
if user.id != calendar.principal { if user.id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
@@ -89,7 +89,7 @@ pub async fn put_event<C: CalendarStore + ?Sized>(
if Some(&HeaderValue::from_static("*")) == req.headers().get(header::IF_NONE_MATCH) { if Some(&HeaderValue::from_static("*")) == req.headers().get(header::IF_NONE_MATCH) {
// Only write if not existing // Only write if not existing
match store.get_object(&principal, &cid, &uid).await { match store.get_object(&principal, &cal_id, &object_id).await {
Ok(_) => { Ok(_) => {
// Conflict // Conflict
return Ok(HttpResponse::Conflict().body("Resource with this URI already exists")); return Ok(HttpResponse::Conflict().body("Resource with this URI already exists"));
@@ -104,8 +104,8 @@ pub async fn put_event<C: CalendarStore + ?Sized>(
} }
} }
let object = CalendarObject::from_ics(uid, body)?; let object = CalendarObject::from_ics(object_id, body)?;
store.put_object(principal, cid, object).await?; store.put_object(principal, cal_id, object).await?;
Ok(HttpResponse::Created().body("")) Ok(HttpResponse::Created().body(""))
} }

View File

@@ -16,8 +16,8 @@ pub struct CalendarObjectResourceService<C: CalendarStore + ?Sized> {
pub cal_store: Arc<RwLock<C>>, pub cal_store: Arc<RwLock<C>>,
pub path: String, pub path: String,
pub principal: String, pub principal: String,
pub cid: String, pub cal_id: String,
pub uid: String, pub object_id: String,
} }
#[derive(EnumString, Debug, VariantNames, Clone)] #[derive(EnumString, Debug, VariantNames, Clone)]
@@ -78,8 +78,8 @@ impl Resource for CalendarObjectResource {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CalendarObjectPathComponents { pub struct CalendarObjectPathComponents {
pub principal: String, pub principal: String,
pub cid: String, pub cal_id: String,
pub uid: String, pub object_id: String,
} }
impl<'de> Deserialize<'de> for CalendarObjectPathComponents { impl<'de> Deserialize<'de> for CalendarObjectPathComponents {
@@ -94,8 +94,8 @@ impl<'de> Deserialize<'de> for CalendarObjectPathComponents {
} }
Ok(Self { Ok(Self {
principal, principal,
cid: calendar, cal_id: calendar,
uid: object, object_id: object,
}) })
} }
} }
@@ -113,8 +113,8 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
) -> Result<Self, Self::Error> { ) -> Result<Self, Self::Error> {
let CalendarObjectPathComponents { let CalendarObjectPathComponents {
principal, principal,
cid, cal_id,
uid, object_id,
} = path_components; } = path_components;
let cal_store = req let cal_store = req
@@ -126,8 +126,8 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
Ok(Self { Ok(Self {
cal_store, cal_store,
principal, principal,
cid, cal_id,
uid, object_id,
path: req.path().to_string(), path: req.path().to_string(),
}) })
} }
@@ -140,7 +140,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
.cal_store .cal_store
.read() .read()
.await .await
.get_object(&self.principal, &self.cid, &self.uid) .get_object(&self.principal, &self.cal_id, &self.object_id)
.await?; .await?;
Ok(event.into()) Ok(event.into())
} }
@@ -153,7 +153,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
self.cal_store self.cal_store
.write() .write()
.await .await
.delete_object(&self.principal, &self.cid, &self.uid, use_trashbin) .delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())
} }

View File

@@ -52,10 +52,10 @@ async fn route_calendar<C: CalendarStore + ?Sized>(
store: Data<RwLock<C>>, store: Data<RwLock<C>>,
) -> impl Responder { ) -> impl Responder {
let store = store.read().await; let store = store.read().await;
let (owner, cid) = path.into_inner(); let (owner, cal_id) = path.into_inner();
CalendarPage { CalendarPage {
owner: owner.to_owned(), owner: owner.to_owned(),
calendar: store.get_calendar(&owner, &cid).await.unwrap(), calendar: store.get_calendar(&owner, &cal_id).await.unwrap(),
} }
} }

View File

@@ -13,25 +13,25 @@ CREATE TABLE calendars (
CREATE TABLE calendarobjects ( CREATE TABLE calendarobjects (
principal TEXT NOT NULL, principal TEXT NOT NULL,
cid TEXT NOT NULL, cal_id TEXT NOT NULL,
uid TEXT NOT NULL, id TEXT NOT NULL,
ics TEXT NOT NULL, ics TEXT NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME, deleted_at DATETIME,
PRIMARY KEY (principal, cid, uid), PRIMARY KEY (principal, cal_id, id),
FOREIGN KEY (principal, cid) FOREIGN KEY (principal, cal_id)
REFERENCES calendars (principal, id) ON DELETE CASCADE REFERENCES calendars (principal, id) ON DELETE CASCADE
); );
CREATE TABLE calendarobjectchangelog ( CREATE TABLE calendarobjectchangelog (
-- The actual sync token is the SQLite field 'ROWID' -- The actual sync token is the SQLite field 'ROWID'
principal TEXT NOT NULL, principal TEXT NOT NULL,
cid TEXT NOT NULL, cal_id TEXT NOT NULL,
uid TEXT NOT NULL, object_id TEXT NOT NULL,
operation INTEGER NOT NULL, operation INTEGER NOT NULL,
synctoken INTEGER DEFAULT 0 NOT NULL, synctoken INTEGER DEFAULT 0 NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (principal, cid, created_at), PRIMARY KEY (principal, cal_id, created_at),
FOREIGN KEY (principal, cid) FOREIGN KEY (principal, cal_id)
REFERENCES calendars (principal, id) ON DELETE CASCADE REFERENCES calendars (principal, id) ON DELETE CASCADE
); );

View File

@@ -28,29 +28,38 @@ pub trait CalendarStore: Send + Sync + 'static {
async fn sync_changes( async fn sync_changes(
&self, &self,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
synctoken: i64, synctoken: i64,
) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error>; ) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error>;
async fn get_objects(&self, principal: &str, cid: &str) -> Result<Vec<CalendarObject>, Error>; async fn get_objects(
&self,
principal: &str,
cal_id: &str,
) -> Result<Vec<CalendarObject>, Error>;
async fn get_object( async fn get_object(
&self, &self,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
uid: &str, object_id: &str,
) -> Result<CalendarObject, Error>; ) -> Result<CalendarObject, Error>;
async fn put_object( async fn put_object(
&mut self, &mut self,
principal: String, principal: String,
cid: String, cal_id: String,
object: CalendarObject, object: CalendarObject,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn delete_object( async fn delete_object(
&mut self, &mut self,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
uid: &str, object_id: &str,
use_trashbin: bool, use_trashbin: bool,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn restore_object(&mut self, principal: &str, cid: &str, uid: &str) -> Result<(), Error>; async fn restore_object(
&mut self,
principal: &str,
cal_id: &str,
object_id: &str,
) -> Result<(), Error>;
} }

View File

@@ -22,7 +22,7 @@ pub enum CalendarObjectComponent {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CalendarObject { pub struct CalendarObject {
uid: String, id: String,
ics: String, ics: String,
data: CalendarObjectComponent, data: CalendarObjectComponent,
} }
@@ -35,11 +35,11 @@ impl<'de> Deserialize<'de> for CalendarObject {
{ {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Inner { struct Inner {
uid: String, id: String,
ics: String, ics: String,
} }
let Inner { uid, ics } = Inner::deserialize(deserializer)?; let Inner { id, ics } = Inner::deserialize(deserializer)?;
Self::from_ics(uid, ics).map_err(serde::de::Error::custom) Self::from_ics(id, ics).map_err(serde::de::Error::custom)
} }
} }
@@ -50,12 +50,12 @@ impl Serialize for CalendarObject {
{ {
#[derive(Serialize)] #[derive(Serialize)]
struct Inner { struct Inner {
uid: String, id: String,
ics: String, ics: String,
} }
Inner::serialize( Inner::serialize(
&Inner { &Inner {
uid: self.get_uid().to_string(), id: self.get_id().to_string(),
ics: self.get_ics().to_string(), ics: self.get_ics().to_string(),
}, },
serializer, serializer,
@@ -64,7 +64,7 @@ impl Serialize for CalendarObject {
} }
impl CalendarObject { impl CalendarObject {
pub fn from_ics(uid: String, ics: String) -> Result<Self, Error> { pub fn from_ics(object_id: String, ics: String) -> Result<Self, Error> {
let mut parser = ical::IcalParser::new(BufReader::new(ics.as_bytes())); let mut parser = ical::IcalParser::new(BufReader::new(ics.as_bytes()));
let cal = parser.next().ok_or(Error::NotFound)??; let cal = parser.next().ok_or(Error::NotFound)??;
if parser.next().is_some() { if parser.next().is_some() {
@@ -98,7 +98,7 @@ impl CalendarObject {
if let Some(event) = cal.events.first() { if let Some(event) = cal.events.first() {
return Ok(CalendarObject { return Ok(CalendarObject {
uid, id: object_id,
ics, ics,
data: CalendarObjectComponent::Event(EventObject { data: CalendarObjectComponent::Event(EventObject {
event: event.clone(), event: event.clone(),
@@ -108,7 +108,7 @@ impl CalendarObject {
} }
if let Some(todo) = cal.todos.first() { if let Some(todo) = cal.todos.first() {
return Ok(CalendarObject { return Ok(CalendarObject {
uid, id: object_id,
ics, ics,
data: CalendarObjectComponent::Todo(TodoObject { todo: todo.clone() }), data: CalendarObjectComponent::Todo(TodoObject { todo: todo.clone() }),
}); });
@@ -119,12 +119,12 @@ impl CalendarObject {
)) ))
} }
pub fn get_uid(&self) -> &str { pub fn get_id(&self) -> &str {
&self.uid &self.id
} }
pub fn get_etag(&self) -> String { pub fn get_etag(&self) -> String {
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
hasher.update(&self.uid); hasher.update(&self.id);
hasher.update(self.get_ics()); hasher.update(self.get_ics());
format!("{:x}", hasher.finalize()) format!("{:x}", hasher.finalize())
} }

View File

@@ -21,7 +21,7 @@ impl SqliteCalendarStore {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct CalendarObjectRow { struct CalendarObjectRow {
uid: String, id: String,
ics: String, ics: String,
} }
@@ -29,7 +29,7 @@ impl TryFrom<CalendarObjectRow> for CalendarObject {
type Error = Error; type Error = Error;
fn try_from(value: CalendarObjectRow) -> Result<Self, Error> { fn try_from(value: CalendarObjectRow) -> Result<Self, Error> {
CalendarObject::from_ics(value.uid, value.ics) CalendarObject::from_ics(value.id, value.ics)
} }
} }
@@ -45,8 +45,8 @@ enum CalendarChangeOperation {
async fn log_object_operation( async fn log_object_operation(
tx: &mut Transaction<'_, Sqlite>, tx: &mut Transaction<'_, Sqlite>,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
uid: &str, object_id: &str,
operation: CalendarChangeOperation, operation: CalendarChangeOperation,
) -> Result<(), Error> { ) -> Result<(), Error> {
sqlx::query!( sqlx::query!(
@@ -55,20 +55,20 @@ async fn log_object_operation(
SET synctoken = synctoken + 1 SET synctoken = synctoken + 1
WHERE (principal, id) = (?1, ?2)"#, WHERE (principal, id) = (?1, ?2)"#,
principal, principal,
cid cal_id
) )
.execute(&mut **tx) .execute(&mut **tx)
.await?; .await?;
sqlx::query!( sqlx::query!(
r#" r#"
INSERT INTO calendarobjectchangelog (principal, cid, uid, operation, synctoken) INSERT INTO calendarobjectchangelog (principal, cal_id, object_id, operation, synctoken)
VALUES (?1, ?2, ?3, ?4, ( VALUES (?1, ?2, ?3, ?4, (
SELECT synctoken FROM calendars WHERE (principal, id) = (?1, ?2) SELECT synctoken FROM calendars WHERE (principal, id) = (?1, ?2)
))"#, ))"#,
principal, principal,
cid, cal_id,
uid, object_id,
operation operation
) )
.execute(&mut **tx) .execute(&mut **tx)
@@ -194,12 +194,16 @@ impl CalendarStore for SqliteCalendarStore {
} }
#[instrument] #[instrument]
async fn get_objects(&self, principal: &str, cid: &str) -> Result<Vec<CalendarObject>, Error> { async fn get_objects(
&self,
principal: &str,
cal_id: &str,
) -> Result<Vec<CalendarObject>, Error> {
sqlx::query_as!( sqlx::query_as!(
CalendarObjectRow, CalendarObjectRow,
"SELECT uid, ics FROM calendarobjects WHERE principal = ? AND cid = ? AND deleted_at IS NULL", "SELECT id, ics FROM calendarobjects WHERE principal = ? AND cal_id = ? AND deleted_at IS NULL",
principal, principal,
cid cal_id
) )
.fetch_all(&self.db) .fetch_all(&self.db)
.await? .await?
@@ -212,15 +216,15 @@ impl CalendarStore for SqliteCalendarStore {
async fn get_object( async fn get_object(
&self, &self,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
uid: &str, object_id: &str,
) -> Result<CalendarObject, Error> { ) -> Result<CalendarObject, Error> {
Ok(sqlx::query_as!( Ok(sqlx::query_as!(
CalendarObjectRow, CalendarObjectRow,
"SELECT uid, ics FROM calendarobjects WHERE (principal, cid, uid) = (?, ?, ?)", "SELECT id, ics FROM calendarobjects WHERE (principal, cal_id, id) = (?, ?, ?)",
principal, principal,
cid, cal_id,
uid object_id
) )
.fetch_one(&self.db) .fetch_one(&self.db)
.await? .await?
@@ -231,24 +235,31 @@ impl CalendarStore for SqliteCalendarStore {
async fn put_object( async fn put_object(
&mut self, &mut self,
principal: String, principal: String,
cid: String, cal_id: String,
object: CalendarObject, object: CalendarObject,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut tx = self.db.begin().await?; let mut tx = self.db.begin().await?;
let (uid, ics) = (object.get_uid(), object.get_ics()); let (object_id, ics) = (object.get_id(), object.get_ics());
sqlx::query!( sqlx::query!(
"REPLACE INTO calendarobjects (principal, cid, uid, ics) VALUES (?, ?, ?, ?)", "REPLACE INTO calendarobjects (principal, cal_id, id, ics) VALUES (?, ?, ?, ?)",
principal, principal,
cid, cal_id,
uid, object_id,
ics ics
) )
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
log_object_operation(&mut tx, &principal, &cid, uid, CalendarChangeOperation::Add).await?; log_object_operation(
&mut tx,
&principal,
&cal_id,
object_id,
CalendarChangeOperation::Add,
)
.await?;
tx.commit().await?; tx.commit().await?;
Ok(()) Ok(())
@@ -258,8 +269,8 @@ impl CalendarStore for SqliteCalendarStore {
async fn delete_object( async fn delete_object(
&mut self, &mut self,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
uid: &str, id: &str,
use_trashbin: bool, use_trashbin: bool,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut tx = self.db.begin().await?; let mut tx = self.db.begin().await?;
@@ -267,19 +278,19 @@ impl CalendarStore for SqliteCalendarStore {
match use_trashbin { match use_trashbin {
true => { true => {
sqlx::query!( sqlx::query!(
"UPDATE calendarobjects SET deleted_at = datetime(), updated_at = datetime() WHERE (principal, cid, uid) = (?, ?, ?)", "UPDATE calendarobjects SET deleted_at = datetime(), updated_at = datetime() WHERE (principal, cal_id, id) = (?, ?, ?)",
principal, principal,
cid, cal_id,
uid id
) )
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
} }
false => { false => {
sqlx::query!( sqlx::query!(
"DELETE FROM calendarobjects WHERE cid = ? AND uid = ?", "DELETE FROM calendarobjects WHERE cal_id = ? AND id = ?",
cid, cal_id,
uid id
) )
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
@@ -288,8 +299,8 @@ impl CalendarStore for SqliteCalendarStore {
log_object_operation( log_object_operation(
&mut tx, &mut tx,
principal, principal,
cid, cal_id,
uid, id,
CalendarChangeOperation::Delete, CalendarChangeOperation::Delete,
) )
.await?; .await?;
@@ -298,14 +309,19 @@ impl CalendarStore for SqliteCalendarStore {
} }
#[instrument] #[instrument]
async fn restore_object(&mut self, principal: &str, cid: &str, uid: &str) -> Result<(), Error> { async fn restore_object(
&mut self,
principal: &str,
cal_id: &str,
object_id: &str,
) -> Result<(), Error> {
let mut tx = self.db.begin().await?; let mut tx = self.db.begin().await?;
sqlx::query!( sqlx::query!(
r#"UPDATE calendarobjects SET deleted_at = NULL, updated_at = datetime() WHERE (principal, cid, uid) = (?, ?, ?)"#, r#"UPDATE calendarobjects SET deleted_at = NULL, updated_at = datetime() WHERE (principal, cal_id, id) = (?, ?, ?)"#,
principal, principal,
cid, cal_id,
uid object_id
) )
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
@@ -313,8 +329,8 @@ impl CalendarStore for SqliteCalendarStore {
log_object_operation( log_object_operation(
&mut tx, &mut tx,
principal, principal,
cid, cal_id,
uid, object_id,
CalendarChangeOperation::Delete, CalendarChangeOperation::Delete,
) )
.await?; .await?;
@@ -326,17 +342,17 @@ impl CalendarStore for SqliteCalendarStore {
async fn sync_changes( async fn sync_changes(
&self, &self,
principal: &str, principal: &str,
cid: &str, cal_id: &str,
synctoken: i64, synctoken: i64,
) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error> { ) -> Result<(Vec<CalendarObject>, Vec<String>, i64), Error> {
struct Row { struct Row {
uid: String, object_id: String,
synctoken: i64, synctoken: i64,
} }
let changes = sqlx::query_as!( let changes = sqlx::query_as!(
Row, Row,
r#" r#"
SELECT DISTINCT uid, max(0, synctoken) as "synctoken!: i64" from calendarobjectchangelog SELECT DISTINCT object_id, max(0, synctoken) as "synctoken!: i64" from calendarobjectchangelog
WHERE synctoken > ? WHERE synctoken > ?
ORDER BY synctoken ASC ORDER BY synctoken ASC
"#, "#,
@@ -353,10 +369,10 @@ impl CalendarStore for SqliteCalendarStore {
.map(|&Row { synctoken, .. }| synctoken) .map(|&Row { synctoken, .. }| synctoken)
.unwrap_or(0); .unwrap_or(0);
for Row { uid, .. } in changes { for Row { object_id, .. } in changes {
match self.get_object(principal, cid, &uid).await { match self.get_object(principal, cal_id, &object_id).await {
Ok(object) => objects.push(object), Ok(object) => objects.push(object),
Err(Error::NotFound) => deleted_objects.push(uid), Err(Error::NotFound) => deleted_objects.push(object_id),
Err(err) => return Err(err), Err(err) => return Err(err),
} }
} }

View File

@@ -44,5 +44,5 @@ async fn test_create_event<CS: CalendarStore>(mut store: CS) {
let event = store.get_object("testuser", "test", "asd").await.unwrap(); let event = store.get_object("testuser", "test", "asd").await.unwrap();
assert_eq!(event.get_ics(), EVENT); assert_eq!(event.get_ics(), EVENT);
assert_eq!(event.get_uid(), "asd"); assert_eq!(event.get_id(), "asd");
} }