Files
inbuxa-server/crates/dav/src/calendar/copy_move.rs
jcoffey-dev 35fe09e6da
ci / fork-checks (pull_request) Skipped
ci / build (pull_request) Skipped
github/ci (branch) GitHub Actions
ci / github (pull_request) Successful in 26m47s
Tenant storage: count what's written where it's stored (#499)
Part of the inbuxa/inbuxa-admin#257 remediation (Refs inbuxa/inbuxa-admin#257).

Five places where a tenant's usage didn't match what its accounts store:

- CalDAV/CardDAV COPY and MOVE of a single event or card into another
  account now check that account's quota and its tenant's, as copying a
  whole calendar or address book already did. A member could copy items
  one at a time into a group account or a shared calendar past both
  limits. A move within one account adds nothing and isn't checked.
  Both checks, and the whole-collection one, now use the size the
  item is charged (its stored bytes plus names and properties), not
  the bare iCalendar or vCard length, so they don't run a few hundred
  bytes per item past the limit.
- A tenant's usage counter now moves with the account that owns the
  data, not the tenant of whoever made the change (MT-20). The index
  builder still emits the change, with TENANT_OF_ACCOUNT when the writer
  has no tenant; commit_batch looks up each account's tenant (a kept
  deleted account's from its kept record) and points the change there,
  or drops it for an account with none. A change still unresolved when
  a batch is built is dropped rather than written under the
  placeholder. Writes by a sharee, a delegate or a server
  administrator no longer move the wrong tenant's counter, or none.
- Destroying an account takes its usage off its tenant: the account's
  counter (kept archive bytes included) is read before the data goes
  and subtracted after, so a retried destroy takes it off once. The
  tenant comes from the kept record, or from the account's domain.
- Destroying an account no longer clears the usage counter of the
  tenant with the same number. Accounts and tenants are numbered
  apart, and the tenant's counter key sits inside the account's range
  in the counter subspace, so destroying account 5 set tenant 5's
  usage to 0. danger_destroy_account now skips that one key.
- A tenant recount (recalculateQuota, resetTenantQuotas, a domain
  moving in) now includes deleted members still kept (UD-15): their
  data stays until they're destroyed, which takes it off then.

Tests: webdav Test 20 (COPY/MOVE of events and cards into a group with
2 KiB left: refused once full; failed before the fix with 200 copies
in), store unit tests for the retargeting, and the tenant suite checks
a kept member stays counted through a recount, a destroyed one comes
off, destroying an account numbered like a tenant leaves that
tenant's usage alone, and a tenant with every member destroyed is back
to 0.

Fixes #499
2026-11-20 12:10:15 -07:00

1188 lines
40 KiB
Rust

/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*
* Modified by Coffey Labs in 2026 for INBUXA.
*/
use super::{assert_is_unique_uid, privacy::check_copy_out};
use crate::{
DavError, DavMethod,
common::{
lock::{LockRequestHandler, ResourceState},
uri::DavUriResource,
},
file::DavFileResource,
};
use calcard::common::timezone::Tz;
use common::{DavName, Server, auth::AccessToken};
use dav_proto::{Depth, RequestHeaders};
use groupware::{
DestroyArchive,
cache::GroupwareCache,
calendar::{Calendar, CalendarEvent, CalendarPreferences, Timezone},
};
use http_proto::HttpResponse;
use hyper::StatusCode;
use store::write::{BatchBuilder, now};
use store::{
ValueKey,
write::{AlignedBytes, Archive, ValueClass},
};
use trc::AddContext;
use types::{
acl::Acl,
collection::{Collection, SyncCollection, VanishedCollection},
field::PrincipalField,
};
pub(crate) trait CalendarCopyMoveRequestHandler: Sync + Send {
fn handle_calendar_copy_move_request(
&self,
access_token: &AccessToken,
headers: &RequestHeaders<'_>,
is_move: bool,
) -> impl Future<Output = crate::Result<HttpResponse>> + Send;
}
impl CalendarCopyMoveRequestHandler for Server {
async fn handle_calendar_copy_move_request(
&self,
access_token: &AccessToken,
headers: &RequestHeaders<'_>,
is_move: bool,
) -> crate::Result<HttpResponse> {
// Validate source
let from_resource_ = self
.validate_uri(access_token, headers.uri)
.await?
.into_owned_uri()?;
let from_account_id = from_resource_.account_id;
let from_resources = self
.fetch_dav_resources(
access_token.account_id(),
from_account_id,
SyncCollection::Calendar,
)
.await
.caused_by(trc::location!())?;
let from_resource_name = from_resource_
.resource
.ok_or(DavError::Code(StatusCode::FORBIDDEN))?;
let from_resource = from_resources
.by_path(from_resource_name)
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
#[cfg(not(any(feature = "dev_mode", feature = "test_mode")))]
if is_move
&& from_resource.is_container()
&& self
.core
.groupware
.default_calendar_name
.as_ref()
.is_some_and(|name| name == from_resource_name)
{
return Err(DavError::Condition(crate::DavErrorCondition::new(
StatusCode::FORBIDDEN,
dav_proto::schema::response::CalCondition::DefaultCalendarNeeded,
)));
}
// Validate ACL
if !access_token.is_member(from_account_id)
&& !from_resources.has_access_to_container(
access_token,
if from_resource.is_container() {
from_resource.document_id()
} else {
from_resource.parent_id().unwrap()
},
Acl::ReadItems,
)
{
return Err(DavError::Code(StatusCode::FORBIDDEN));
}
// Validate destination
let destination = self
.validate_uri_with_status(
access_token,
headers
.destination
.ok_or(DavError::Code(StatusCode::BAD_GATEWAY))?,
StatusCode::BAD_GATEWAY,
)
.await?;
if destination.collection != Collection::Calendar {
return Err(DavError::Code(StatusCode::BAD_GATEWAY));
}
let to_account_id = destination
.account_id
.ok_or(DavError::Code(StatusCode::BAD_GATEWAY))?;
let to_resources = if to_account_id == from_account_id {
from_resources.clone()
} else {
self.fetch_dav_resources(
access_token.account_id(),
to_account_id,
SyncCollection::Calendar,
)
.await
.caused_by(trc::location!())?
};
// Validate headers
let destination_resource_name = destination
.resource
.ok_or(DavError::Code(StatusCode::BAD_GATEWAY))?;
let to_resource = to_resources.by_path(destination_resource_name);
self.validate_headers(
access_token,
headers,
vec![
ResourceState {
account_id: from_account_id,
collection: if from_resource.is_container() {
Collection::Calendar
} else {
Collection::CalendarEvent
},
document_id: Some(from_resource.document_id()),
path: from_resource_name,
..Default::default()
},
ResourceState {
account_id: to_account_id,
collection: to_resource
.map(|r| {
if r.is_container() {
Collection::Calendar
} else {
Collection::CalendarEvent
}
})
.unwrap_or(Collection::Calendar),
document_id: Some(to_resource.map(|r| r.document_id()).unwrap_or(u32::MAX)),
path: destination_resource_name,
..Default::default()
},
],
Default::default(),
if is_move {
DavMethod::MOVE
} else {
DavMethod::COPY
},
)
.await?;
// Map destination
if let Some(to_resource) = to_resource {
// inbuxa: paths are compared within one account only
if from_account_id == to_account_id && from_resource.path() == to_resource.path() {
// Same resource
return Err(DavError::Code(StatusCode::BAD_GATEWAY));
}
let new_name = destination_resource_name
.rsplit_once('/')
.map(|(_, name)| name)
.unwrap_or(destination_resource_name);
match (from_resource.is_container(), to_resource.is_container()) {
(true, true) => {
let from_children_ids = from_resources
.subtree(from_resource_name)
.filter(|r| !r.is_container())
.map(|r| r.document_id())
.collect::<Vec<_>>();
let to_document_ids = to_resources
.subtree(destination_resource_name)
.filter(|r| !r.is_container())
.map(|r| r.document_id())
.collect::<Vec<_>>();
// Validate ACLs
if !access_token.is_member(to_account_id)
|| (!access_token.is_member(from_account_id)
// inbuxa: moving a whole collection takes it from its owner, so it
// needs the rights DELETE needs, not just RemoveItems.
&& !(if is_move {
from_resources.has_access_to_container(
access_token,
from_resource.document_id(),
Acl::Delete,
) && from_resources.has_access_to_container(
access_token,
from_resource.document_id(),
Acl::RemoveItems,
)
} else {
from_resources.has_access_to_container(
access_token,
from_resource.document_id(),
Acl::ReadItems,
)
}))
{
return Err(DavError::Code(StatusCode::FORBIDDEN));
}
// Overwrite container
copy_container(
self,
access_token,
from_account_id,
from_resource.document_id(),
from_children_ids,
from_resources.format_collection(from_resource_name),
to_account_id,
to_resource.document_id().into(),
to_document_ids,
new_name,
is_move,
)
.await
}
(false, false) => {
// Overwrite event
let from_calendar_id = from_resource.parent_id().unwrap();
let to_calendar_id = to_resource.parent_id().unwrap();
// Validate ACL
if (!access_token.is_member(from_account_id)
&& !from_resources.has_access_to_container(
access_token,
from_calendar_id,
if is_move {
Acl::RemoveItems
} else {
Acl::ReadItems
},
))
|| (!access_token.is_member(to_account_id)
&& !to_resources.has_access_to_container(
access_token,
to_calendar_id,
Acl::RemoveItems,
))
{
return Err(DavError::Code(StatusCode::FORBIDDEN));
}
if is_move {
move_event(
self,
access_token,
from_account_id,
from_resource.document_id(),
from_calendar_id,
from_resources.format_item(from_resource_name),
to_account_id,
to_resource.document_id().into(),
to_calendar_id,
new_name,
headers.if_schedule_tag,
)
.await
} else {
copy_event(
self,
access_token,
from_account_id,
from_resource.document_id(),
to_account_id,
to_resource.document_id().into(),
to_calendar_id,
new_name,
)
.await
}
}
_ => Err(DavError::Code(StatusCode::BAD_GATEWAY)),
}
} else if let Some((parent_resource, new_name)) =
to_resources.map_parent(destination_resource_name)
{
if let Some(parent_resource) = parent_resource {
// Creating items under an event is not allowed
// Copying/moving containers under a container is not allowed
if !parent_resource.is_container() || from_resource.is_container() {
return Err(DavError::Code(StatusCode::BAD_GATEWAY));
}
// Validate ACL
let from_calendar_id = from_resource.parent_id().unwrap();
let to_calendar_id = parent_resource.document_id();
if (!access_token.is_member(from_account_id)
&& !from_resources.has_access_to_container(
access_token,
from_calendar_id,
if is_move {
Acl::RemoveItems
} else {
Acl::ReadItems
},
))
|| (!access_token.is_member(to_account_id)
&& !to_resources.has_access_to_container(
access_token,
to_calendar_id,
Acl::AddItems,
))
{
return Err(DavError::Code(StatusCode::FORBIDDEN));
}
// Copy/move event
if is_move {
if from_account_id != to_account_id
|| parent_resource.document_id() != from_calendar_id
{
move_event(
self,
access_token,
from_account_id,
from_resource.document_id(),
from_calendar_id,
from_resources.format_item(from_resource_name),
to_account_id,
None,
to_calendar_id,
new_name,
headers.if_schedule_tag,
)
.await
} else {
rename_event(
self,
access_token,
from_account_id,
from_resource.document_id(),
from_calendar_id,
new_name,
from_resources.format_item(from_resource_name),
)
.await
}
} else {
copy_event(
self,
access_token,
from_account_id,
from_resource.document_id(),
to_account_id,
None,
to_calendar_id,
new_name,
)
.await
}
} else {
// Copying/moving events to the root is not allowed
if !from_resource.is_container() {
return Err(DavError::Code(StatusCode::BAD_GATEWAY));
}
// Shared users cannot create containers
if !access_token.is_member(to_account_id) {
return Err(DavError::Code(StatusCode::FORBIDDEN));
}
// Validate ACLs
if !access_token.is_member(from_account_id)
// inbuxa: moving a whole collection takes it from its owner, so it
// needs the rights DELETE needs, not just RemoveItems.
&& !(if is_move {
from_resources.has_access_to_container(
access_token,
from_resource.document_id(),
Acl::Delete,
) && from_resources.has_access_to_container(
access_token,
from_resource.document_id(),
Acl::RemoveItems,
)
} else {
from_resources.has_access_to_container(
access_token,
from_resource.document_id(),
Acl::ReadItems,
)
})
{
return Err(DavError::Code(StatusCode::FORBIDDEN));
}
// Copy/move container
let from_children_ids = from_resources
.subtree(from_resource_name)
.filter(|r| !r.is_container())
.map(|r| r.document_id())
.collect::<Vec<_>>();
if is_move {
if from_account_id != to_account_id {
copy_container(
self,
access_token,
from_account_id,
from_resource.document_id(),
if headers.depth != Depth::Zero {
from_children_ids
} else {
return Err(DavError::Code(StatusCode::BAD_GATEWAY));
},
from_resources.format_collection(from_resource_name),
to_account_id,
None,
vec![],
new_name,
true,
)
.await
} else {
rename_container(
self,
access_token,
from_account_id,
from_resource.document_id(),
new_name,
from_resources.format_collection(from_resource_name),
)
.await
}
} else {
copy_container(
self,
access_token,
from_account_id,
from_resource.document_id(),
if headers.depth != Depth::Zero {
from_children_ids
} else {
vec![]
},
from_resources.format_collection(from_resource_name),
to_account_id,
None,
vec![],
new_name,
false,
)
.await
}
}
} else {
Err(DavError::Code(StatusCode::CONFLICT))
}
}
}
#[allow(clippy::too_many_arguments)]
async fn copy_event(
server: &Server,
access_token: &AccessToken,
from_account_id: u32,
from_document_id: u32,
to_account_id: u32,
to_document_id: Option<u32>,
to_calendar_id: u32,
new_name: &str,
) -> crate::Result<HttpResponse> {
// Fetch event
let event_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
from_account_id,
Collection::CalendarEvent,
from_document_id,
))
.await
.caused_by(trc::location!())?
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
let event = event_
.to_unarchived::<CalendarEvent>()
.caused_by(trc::location!())?;
let mut batch = BatchBuilder::new();
// Validate UID
assert_is_unique_uid(
server,
server
.fetch_dav_resources(
access_token.account_id(),
to_account_id,
SyncCollection::Calendar,
)
.await
.caused_by(trc::location!())?
.as_ref(),
to_account_id,
to_calendar_id,
event.inner.data.event.uids().next(),
)
.await?;
let changed_by = access_token.account_tenant_ids();
if from_account_id == to_account_id {
let mut new_event = event
.deserialize::<CalendarEvent>()
.caused_by(trc::location!())?;
new_event.names.push(DavName {
name: new_name.to_string(),
parent_id: to_calendar_id,
});
new_event
.update(
changed_by,
event,
from_account_id,
from_document_id,
&mut batch,
)
.caused_by(trc::location!())?;
} else {
let next_email_alarm = event.inner.data.next_alarm(now() as i64, Tz::Floating);
let mut new_event = event
.deserialize::<CalendarEvent>()
.caused_by(trc::location!())?;
// inbuxa: a sharee takes out only what it may
check_copy_out(
server,
access_token,
from_account_id,
from_document_id,
&mut new_event,
)
.await?;
new_event.names = vec![DavName {
name: new_name.to_string(),
parent_id: to_calendar_id,
}];
// inbuxa: into another account, it counts against that account's
// quota and its tenant's, as a whole calendar or address book does
server
.has_available_quota(
server.account(to_account_id).await?.as_ref(),
new_event.size() as u64,
)
.await?;
let to_document_id = server
.store()
.assign_document_ids(to_account_id, Collection::CalendarEvent, 1)
.await
.caused_by(trc::location!())?;
new_event
.insert(
changed_by,
to_account_id,
to_document_id,
next_email_alarm,
&mut batch,
)
.caused_by(trc::location!())?;
}
let response = if let Some(to_document_id) = to_document_id {
// Overwrite event on destination
let event_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
to_account_id,
Collection::CalendarEvent,
to_document_id,
))
.await
.caused_by(trc::location!())?;
if let Some(event_) = event_ {
let event = event_
.to_unarchived::<CalendarEvent>()
.caused_by(trc::location!())?;
let account_info = server
.account_info(access_token.account_id())
.await
.caused_by(trc::location!())?;
DestroyArchive(event)
.delete(
&account_info,
to_account_id,
to_document_id,
to_calendar_id,
None,
false,
&mut batch,
)
.caused_by(trc::location!())?;
}
Ok(HttpResponse::new(StatusCode::NO_CONTENT))
} else {
Ok(HttpResponse::new(StatusCode::CREATED))
};
server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
server.notify_task_queue();
response
}
#[allow(clippy::too_many_arguments)]
async fn move_event(
server: &Server,
access_token: &AccessToken,
from_account_id: u32,
from_document_id: u32,
from_calendar_id: u32,
from_resource_path: String,
to_account_id: u32,
to_document_id: Option<u32>,
to_calendar_id: u32,
new_name: &str,
if_schedule_tag: Option<u32>,
) -> crate::Result<HttpResponse> {
// Fetch event
let event_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
from_account_id,
Collection::CalendarEvent,
from_document_id,
))
.await
.caused_by(trc::location!())?
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
let event = event_
.to_unarchived::<CalendarEvent>()
.caused_by(trc::location!())?;
// Validate headers
if if_schedule_tag.is_some()
&& event.inner.schedule_tag.as_ref().map(|t| t.to_native()) != if_schedule_tag
{
return Err(DavError::Code(StatusCode::PRECONDITION_FAILED));
}
// Validate UID
if from_account_id != to_account_id
|| from_calendar_id != to_calendar_id
|| to_document_id.is_none()
{
assert_is_unique_uid(
server,
server
.fetch_dav_resources(
access_token.account_id(),
to_account_id,
SyncCollection::Calendar,
)
.await
.caused_by(trc::location!())?
.as_ref(),
to_account_id,
to_calendar_id,
event.inner.data.event.uids().next(),
)
.await?;
}
let account_info = server
.account_info(access_token.account_id())
.await
.caused_by(trc::location!())?;
let mut batch = BatchBuilder::new();
if from_account_id == to_account_id {
let mut name_idx = None;
for (idx, name) in event.inner.names.iter().enumerate() {
if name.parent_id == from_calendar_id {
name_idx = Some(idx);
break;
}
}
let name_idx = if let Some(name_idx) = name_idx {
name_idx
} else {
return Err(DavError::Code(StatusCode::NOT_FOUND));
};
let mut new_event = event
.deserialize::<CalendarEvent>()
.caused_by(trc::location!())?;
new_event.names.swap_remove(name_idx);
new_event.names.push(DavName {
name: new_name.to_string(),
parent_id: to_calendar_id,
});
new_event
.update(
access_token.account_tenant_ids(),
event.clone(),
from_account_id,
from_document_id,
&mut batch,
)
.caused_by(trc::location!())?;
batch.log_vanished_item(VanishedCollection::Calendar, from_resource_path);
} else {
let next_email_alarm = event.inner.data.next_alarm(now() as i64, Tz::Floating);
let mut new_event = event
.deserialize::<CalendarEvent>()
.caused_by(trc::location!())?;
// inbuxa: a sharee takes out only what it may
check_copy_out(
server,
access_token,
from_account_id,
from_document_id,
&mut new_event,
)
.await?;
new_event.names = vec![DavName {
name: new_name.to_string(),
parent_id: to_calendar_id,
}];
DestroyArchive(event)
.delete(
&account_info,
from_account_id,
from_document_id,
from_calendar_id,
from_resource_path.into(),
false,
&mut batch,
)
.caused_by(trc::location!())?;
// inbuxa: into another account, it counts against that account's
// quota and its tenant's, as a whole calendar or address book does
server
.has_available_quota(
server.account(to_account_id).await?.as_ref(),
new_event.size() as u64,
)
.await?;
let to_document_id = server
.store()
.assign_document_ids(to_account_id, Collection::CalendarEvent, 1)
.await
.caused_by(trc::location!())?;
new_event
.insert(
access_token.account_tenant_ids(),
to_account_id,
to_document_id,
next_email_alarm,
&mut batch,
)
.caused_by(trc::location!())?;
}
let response = if let Some(to_document_id) = to_document_id {
// Overwrite event on destination
let event_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
to_account_id,
Collection::CalendarEvent,
to_document_id,
))
.await
.caused_by(trc::location!())?;
if let Some(event_) = event_ {
let event = event_
.to_unarchived::<CalendarEvent>()
.caused_by(trc::location!())?;
DestroyArchive(event)
.delete(
&account_info,
to_account_id,
to_document_id,
to_calendar_id,
None,
false,
&mut batch,
)
.caused_by(trc::location!())?;
}
Ok(HttpResponse::new(StatusCode::NO_CONTENT))
} else {
Ok(HttpResponse::new(StatusCode::CREATED))
};
server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
server.notify_task_queue();
response
}
#[allow(clippy::too_many_arguments)]
async fn rename_event(
server: &Server,
access_token: &AccessToken,
account_id: u32,
document_id: u32,
calendar_id: u32,
new_name: &str,
from_resource_path: String,
) -> crate::Result<HttpResponse> {
// Fetch event
let event_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::CalendarEvent,
document_id,
))
.await
.caused_by(trc::location!())?
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
let event = event_
.to_unarchived::<CalendarEvent>()
.caused_by(trc::location!())?;
let name_idx = event
.inner
.names
.iter()
.position(|n| n.parent_id == calendar_id)
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
let mut new_event = event
.deserialize::<CalendarEvent>()
.caused_by(trc::location!())?;
new_event.names[name_idx].name = new_name.to_string();
let mut batch = BatchBuilder::new();
new_event
.update(
access_token.account_tenant_ids(),
event,
account_id,
document_id,
&mut batch,
)
.caused_by(trc::location!())?;
batch.log_vanished_item(VanishedCollection::Calendar, from_resource_path);
server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
server.notify_task_queue();
Ok(HttpResponse::new(StatusCode::CREATED))
}
#[allow(clippy::too_many_arguments)]
async fn copy_container(
server: &Server,
access_token: &AccessToken,
from_account_id: u32,
from_document_id: u32,
from_children_ids: Vec<u32>,
from_resource_path: String,
to_account_id: u32,
to_document_id: Option<u32>,
to_children_ids: Vec<u32>,
new_name: &str,
remove_source: bool,
) -> crate::Result<HttpResponse> {
// Fetch calendar
let calendar_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
from_account_id,
Collection::Calendar,
from_document_id,
))
.await
.caused_by(trc::location!())?
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
let old_calendar = calendar_
.to_unarchived::<Calendar>()
.caused_by(trc::location!())?;
let mut calendar = old_calendar
.deserialize::<Calendar>()
.caused_by(trc::location!())?;
// Prepare write batch
let mut batch = BatchBuilder::new();
if remove_source {
DestroyArchive(old_calendar)
.delete(
access_token.account_tenant_ids(),
from_account_id,
from_document_id,
from_resource_path.into(),
&mut batch,
)
.caused_by(trc::location!())?;
// Reset default calendar id
let default_calendar_id = server
.store()
.get_value::<u32>(ValueKey {
account_id: from_account_id,
collection: Collection::Principal.into(),
document_id: 0,
class: ValueClass::Property(PrincipalField::DefaultCalendarId.into()),
})
.await
.caused_by(trc::location!())?;
if default_calendar_id.is_some_and(|id| id == from_document_id) {
batch
.with_account_id(from_account_id)
.with_collection(Collection::Principal)
.with_document(0)
.clear(PrincipalField::DefaultCalendarId);
}
}
let preference = calendar.preferences.into_iter().next().unwrap();
calendar.name = new_name.to_string();
calendar.acls.clear();
calendar.preferences = vec![CalendarPreferences {
account_id: to_account_id,
name: preference.name,
description: preference.description,
default_alerts: preference.default_alerts,
sort_order: 0,
color: preference.color,
flags: 0,
time_zone: Timezone::Default,
}];
let account_info = server
.account_info(access_token.account_id())
.await
.caused_by(trc::location!())?;
let is_overwrite = to_document_id.is_some();
let to_document_id = if let Some(to_document_id) = to_document_id {
// Overwrite destination
let calendar_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
to_account_id,
Collection::Calendar,
to_document_id,
))
.await
.caused_by(trc::location!())?;
if let Some(calendar_) = calendar_ {
let calendar = calendar_
.to_unarchived::<Calendar>()
.caused_by(trc::location!())?;
DestroyArchive(calendar)
.delete_with_events(
server,
&account_info,
to_account_id,
to_document_id,
to_children_ids,
None,
false,
&mut batch,
)
.await
.caused_by(trc::location!())?;
}
to_document_id
} else {
server
.store()
.assign_document_ids(to_account_id, Collection::Calendar, 1)
.await
.caused_by(trc::location!())?
};
calendar
.insert(
access_token.account_tenant_ids(),
to_account_id,
to_document_id,
&mut batch,
)
.caused_by(trc::location!())?;
// Copy children
let mut required_space = 0;
for from_child_document_id in from_children_ids {
if let Some(event_) = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
from_account_id,
Collection::CalendarEvent,
from_child_document_id,
))
.await?
{
let event = event_
.to_unarchived::<CalendarEvent>()
.caused_by(trc::location!())?;
let mut new_name = None;
for name in event.inner.names.iter() {
// inbuxa: ids are compared within one account only; across
// accounts the same id is another collection
if from_account_id == to_account_id && name.parent_id == to_document_id {
continue;
} else if name.parent_id == from_document_id {
new_name = Some(name.name.to_string());
}
}
let new_name = if let Some(new_name) = new_name {
DavName {
name: new_name,
parent_id: to_document_id,
}
} else {
continue;
};
let event = event_
.to_unarchived::<CalendarEvent>()
.caused_by(trc::location!())?;
let mut new_event = event
.deserialize::<CalendarEvent>()
.caused_by(trc::location!())?;
if from_account_id == to_account_id {
if remove_source {
new_event
.names
.retain(|name| name.parent_id != from_document_id);
}
new_event.names.push(new_name);
new_event
.update(
access_token.account_tenant_ids(),
event,
from_account_id,
from_child_document_id,
&mut batch,
)
.caused_by(trc::location!())?;
} else {
// inbuxa: a sharee takes out only what it may
check_copy_out(
server,
access_token,
from_account_id,
from_child_document_id,
&mut new_event,
)
.await?;
let next_email_alarm = event.inner.data.next_alarm(now() as i64, Tz::Floating);
if remove_source {
DestroyArchive(event)
.delete(
&account_info,
from_account_id,
from_child_document_id,
from_document_id,
None,
false,
&mut batch,
)
.caused_by(trc::location!())?;
}
let to_document_id = server
.store()
.assign_document_ids(to_account_id, Collection::CalendarEvent, 1)
.await
.caused_by(trc::location!())?;
new_event.names = vec![new_name];
required_space += new_event.size() as u64;
new_event
.insert(
access_token.account_tenant_ids(),
to_account_id,
to_document_id,
next_email_alarm,
&mut batch,
)
.caused_by(trc::location!())?;
}
}
}
if from_account_id != to_account_id && required_space > 0 {
server
.has_available_quota(
server.account(to_account_id).await?.as_ref(),
required_space,
)
.await?;
}
server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
server.notify_task_queue();
if !is_overwrite {
Ok(HttpResponse::new(StatusCode::CREATED))
} else {
Ok(HttpResponse::new(StatusCode::NO_CONTENT))
}
}
#[allow(clippy::too_many_arguments)]
async fn rename_container(
server: &Server,
access_token: &AccessToken,
account_id: u32,
document_id: u32,
new_name: &str,
from_resource_path: String,
) -> crate::Result<HttpResponse> {
// Fetch calendar
let calendar_ = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::Calendar,
document_id,
))
.await
.caused_by(trc::location!())?
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
let calendar = calendar_
.to_unarchived::<Calendar>()
.caused_by(trc::location!())?;
let mut new_calendar = calendar
.deserialize::<Calendar>()
.caused_by(trc::location!())?;
new_calendar.name = new_name.to_string();
let mut batch = BatchBuilder::new();
new_calendar
.update(
access_token.account_tenant_ids(),
calendar,
account_id,
document_id,
&mut batch,
)
.caused_by(trc::location!())?;
batch.log_vanished_item(VanishedCollection::Calendar, from_resource_path);
server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
server.notify_task_queue();
Ok(HttpResponse::new(StatusCode::CREATED))
}