pim_schedule.rs
⎇
Raw
1//! Implicit scheduling (RFC 6638) between the principals of this server.
2//!
3//! `pimdav::itip` decides what a change sends to whom. This module finds the
4//! recipients and their objects, and turns every message into writes that
5//! commit together with the change itself. Nothing leaves the server: an
6//! address outside it gets a delivery failure in its SCHEDULE-STATUS.
7//!
8//! Rooms and resources answer at once, from their own bookings. The outbox
9//! answers free-busy requests from the recipients' calendars.
10
11use chrono::{DateTime, Utc};
12use percent_encoding::percent_decode_str;
13use pimdav::calcard::icalendar::{ICalendar, ICalendarComponentType};
14use pimdav::filter::TimeRange;
15use pimdav::freebusy::{self, Period};
16use pimdav::itip::{self, Message, Method, Role};
17use pimdav::principal::UserType;
18use pimdav::xml::{CALDAV, el, hrefs, with_children};
19use pimdav::zone::{self, Zone};
20use sha2::{Digest, Sha256};
21use tokio::sync::Mutex;
22use xmltree::Element;
23
24use super::pim::{
25 INBOX, MAIL_DOMAIN, OUTBOX, collection_href, etag_of, local_part, need_privilege,
26 principal_name, principal_uuid, seg,
27};
28use crate::db::{PimKind, PimObject, PimOp, PimPrincipal};
29use crate::error::{ApiError, AppState};
30
31/// Held from reading a calendar object to committing the change, so that a
32/// change and the writes it causes see a consistent store.
33// ponytail: one lock for every object write. Per-UID locks if write
34// throughput ever matters.
35pub(crate) static LOCK: Mutex<()> = Mutex::const_new(());
36
37/// The delivery status codes of RFC 6638, 3.2.9.
38const DELIVERED: &str = "1.2";
39/// An address in this server's domains that names no one.
40const INVALID_USER: &str = "3.7";
41/// An address outside this server: there is no iMIP to reach it.
42const NO_ROUTE: &str = "5.2";
43/// The recipient has no calendar for the component.
44const REFUSED: &str = "5.3";
45
46/// Who writes into a calendar, as far as scheduling cares.
47pub(crate) struct Writer<'a> {
48 pub owner: &'a PimPrincipal,
49 /// May send messages as the owner (RFC 6638 `schedule-send`).
50 pub may_schedule: bool,
51 /// The writer's address when it is not the owner, for SENT-BY.
52 pub sent_by: Option<String>,
53}
54
55impl Writer<'_> {
56 /// The owner itself.
57 pub(crate) fn owner(owner: &PimPrincipal) -> Writer<'_> {
58 Writer {
59 owner,
60 may_schedule: true,
61 sent_by: None,
62 }
63 }
64
65 /// 403 `need-privileges` on the owner's outbox.
66 fn refused(&self, privilege: &str) -> Element {
67 let outbox = collection_href(&self.owner.name, PimKind::Calendar, OUTBOX, None);
68 need_privilege(&outbox, CALDAV, privilege)
69 }
70}
71
72/// Every principal, for mapping calendar user addresses.
73pub(crate) struct Directory(Vec<PimPrincipal>);
74
75enum Recipient<'a> {
76 Local(&'a PimPrincipal),
77 Unknown,
78 External,
79}
80
81fn found(p: Option<&PimPrincipal>) -> Recipient<'_> {
82 match p {
83 Some(p) => Recipient::Local(p),
84 None => Recipient::Unknown,
85 }
86}
87
88impl Directory {
89 pub(crate) async fn load(state: &AppState) -> Result<Self, ApiError> {
90 Ok(Directory(state.db.pim_principals().await?))
91 }
92
93 pub(crate) fn get(&self, id: i64) -> Option<&PimPrincipal> {
94 self.0.iter().find(|p| p.id == id)
95 }
96
97 /// The forms `calendar-user-address-set` lists: the mailto address, the
98 /// principal URL and the `urn:uuid:`. Compared without case.
99 fn resolve(&self, addr: &str) -> Recipient<'_> {
100 let addr = addr.trim();
101 let lower = addr.to_ascii_lowercase();
102 if let Some(rest) = lower.strip_prefix("mailto:") {
103 let Some((local, domain)) = rest.rsplit_once('@') else {
104 return Recipient::External;
105 };
106 let kind = match domain.strip_suffix(MAIL_DOMAIN) {
107 Some("") => UserType::Individual,
108 Some("rooms.") => UserType::Room,
109 Some("resources.") => UserType::Resource,
110 // The tombstone of a deleted principal.
111 Some("deleted.") => return Recipient::Unknown,
112 _ => return Recipient::External,
113 };
114 let name = percent_decode_str(local).decode_utf8_lossy();
115 return found(
116 self.0
117 .iter()
118 .find(|p| p.kind == kind && p.name.eq_ignore_ascii_case(&name)),
119 );
120 }
121 if let Some(uuid) = lower.strip_prefix("urn:uuid:") {
122 return found(self.0.iter().find(|p| principal_uuid(p.id) == uuid));
123 }
124 match principal_name(addr) {
125 Some(name) => found(self.0.iter().find(|p| p.name.eq_ignore_ascii_case(&name))),
126 None if lower.starts_with('/') || lower.starts_with("http") => Recipient::Unknown,
127 None => Recipient::External,
128 }
129 }
130
131 /// Whether an address names principal `id`.
132 pub(crate) fn is(&self, id: i64) -> impl Fn(&str) -> bool + '_ {
133 move |a: &str| matches!(self.resolve(a), Recipient::Local(p) if p.id == id)
134 }
135}
136
137/// The writes that make other principals' objects forget `gone` before it
138/// is deleted. Its addresses become a tombstone in `deleted.` of the mail
139/// domain, which names no one, so a later principal of the same name gets
140/// nothing meant for the old one. Commit them together with the delete,
141/// holding [`LOCK`].
142pub(crate) async fn forget(state: &AppState, gone: &PimPrincipal) -> Result<Vec<PimOp>, ApiError> {
143 let dir = Directory(vec![gone.clone()]);
144 let is_gone = dir.is(gone.id);
145 let encoded = local_part(&gone.name);
146 let tombstone = format!("mailto:{encoded}-{}@deleted.{MAIL_DOMAIN}", gone.id);
147 let uuid = principal_uuid(gone.id);
148 let needles = [gone.name.as_str(), encoded.as_str(), uuid.as_str()];
149 let mut ops = Vec::new();
150 for (collection_id, obj, data) in state.db.pim_objects_mentioning(gone.id, &needles).await? {
151 let Some(new) = itip::forget(&String::from_utf8_lossy(&data), &is_gone, &tombstone) else {
152 continue;
153 };
154 let data = new.into_bytes();
155 ops.push(PimOp::Put {
156 collection_id,
157 obj: PimObject {
158 etag: etag_of(&data),
159 ..obj
160 },
161 data,
162 });
163 }
164 Ok(ops)
165}
166
167/// What a PUT of a calendar object stores, and what else it writes.
168pub(crate) struct Stored {
169 pub data: Vec<u8>,
170 /// Whether `data` differs from the request body.
171 pub changed: bool,
172 pub schedule_tag: Option<String>,
173 pub ops: Vec<PimOp>,
174}
175
176/// A PUT of `body` over `old` into collection `at.0` under the name `at.1`.
177/// `Err` names a failed scheduling precondition.
178pub(crate) async fn put(
179 state: &AppState,
180 dir: &Directory,
181 w: &Writer<'_>,
182 at: (i64, &str),
183 old: Option<&[u8]>,
184 body: &[u8],
185) -> Result<Result<Stored, Element>, ApiError> {
186 let parse = |b: &[u8]| ICalendar::parse(String::from_utf8_lossy(b).as_ref()).ok();
187 let Some(sent) = parse(body) else {
188 return Ok(Ok(unchanged(body, None)));
189 };
190 let owner = w.owner;
191 let owns = dir.is(owner.id);
192 let role = match itip::role(&sent, &owns) {
193 Ok(r) => r,
194 Err(refused) => return Ok(Err(refused.condition())),
195 };
196 if role != Role::None
197 && let Some(holder) = elsewhere(state, owner, &sent, at).await?
198 {
199 return Ok(Err(holder));
200 }
201 let old = old.and_then(parse);
202 let old_role = old.as_ref().and_then(|o| itip::role(o, &owns).ok());
203 let now = Utc::now();
204 let mut ops = Vec::new();
205
206 let stored = match (role, old_role) {
207 (Role::Organizer, _) => {
208 let old = old.as_ref().filter(|_| old_role == Some(Role::Organizer));
209 let (mut store, force) = itip::prepare(old, &sent, &owns);
210 let mut messages = itip::messages(old, Some(&store), &owns, &force, now);
211 if !messages.is_empty() {
212 if !w.may_schedule {
213 return Ok(Err(w.refused("schedule-send-invite")));
214 }
215 itip::stamp_sender(&mut store, &owns, w.sent_by.as_deref());
216 messages = itip::messages(old, Some(&store), &owns, &force, now);
217 }
218 // Rooms answer first, so the others' copies carry their answers.
219 if answer_rooms(state, dir, owner, &mut store, &messages, &mut ops, now).await? {
220 messages = itip::messages(old, Some(&store), &owns, &force, now);
221 }
222 for m in &messages {
223 if let Some(status) = deliver(state, dir, owner, m, &mut ops).await? {
224 itip::set_attendee_status(&mut store, &m.to, status);
225 }
226 }
227 store
228 }
229 (Role::Attendee, Some(Role::Attendee)) => {
230 let old = old.as_ref().expect("an attendee role needs the old object");
231 let (mut store, reply) = match itip::attend(old, sent.clone(), &owns, now) {
232 Ok(v) => v,
233 Err(refused) => return Ok(Err(refused.condition())),
234 };
235 if let Some(mut reply) = reply {
236 if !w.may_schedule {
237 return Ok(Err(w.refused("schedule-send-reply")));
238 }
239 itip::stamp_sender(&mut store, &owns, w.sent_by.as_deref());
240 itip::stamp_sender(&mut reply.cal, &owns, w.sent_by.as_deref());
241 let status = reply_to(state, dir, owner, &reply, &mut ops).await?;
242 itip::set_organizer_status(&mut store, status);
243 }
244 store
245 }
246 // No longer a scheduling object, or a copy the attendee brings in
247 // itself (RFC 6638, 3.2.2.2): stored as sent.
248 (_, previous) => {
249 if let Some(old) = &old {
250 match removed(state, dir, w, old, previous, true).await? {
251 Ok(more) => ops.extend(more),
252 Err(refused) => return Ok(Err(refused)),
253 }
254 }
255 let tag = (role != Role::None).then(|| etag_of(body));
256 return Ok(Ok(Stored {
257 ops,
258 ..unchanged(body, tag)
259 }));
260 }
261 };
262 let changed = stored != sent;
263 let data = match changed {
264 true => stored.to_string().into_bytes(),
265 false => body.to_vec(),
266 };
267 Ok(Ok(Stored {
268 schedule_tag: Some(etag_of(&data)),
269 data,
270 changed,
271 ops,
272 }))
273}
274
275/// The Schedule-Tag an import stores with `body`, `None` for an object that
276/// schedules nothing. An import sends no messages: the object is stored as
277/// sent. `Err` names the precondition that refuses it.
278pub(crate) async fn import_tag(
279 state: &AppState,
280 dir: &Directory,
281 owner: &PimPrincipal,
282 at: (i64, &str),
283 body: &[u8],
284) -> Result<Result<Option<String>, Element>, ApiError> {
285 let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(body).as_ref()) else {
286 return Ok(Ok(None));
287 };
288 match itip::role(&cal, &dir.is(owner.id)) {
289 Err(refused) => Ok(Err(refused.condition())),
290 Ok(Role::None) => Ok(Ok(None)),
291 Ok(_) => Ok(match elsewhere(state, owner, &cal, at).await? {
292 Some(holder) => Err(holder),
293 None => Ok(Some(etag_of(body))),
294 }),
295 }
296}
297
298/// The resource name the server picks for an object it creates.
299pub(crate) fn object_name(uid: &str, kind: PimKind) -> String {
300 let ext = match kind {
301 PimKind::Calendar => "ics",
302 PimKind::AddressBook => "vcf",
303 };
304 format!("{}.{ext}", &crate::hex(&Sha256::digest(uid))[..32])
305}
306
307fn unchanged(body: &[u8], schedule_tag: Option<String>) -> Stored {
308 Stored {
309 data: body.to_vec(),
310 changed: false,
311 schedule_tag,
312 ops: Vec::new(),
313 }
314}
315
316/// The writes a DELETE of `old` causes. `reply` is false for
317/// `Schedule-Reply: F` (RFC 6638, 8.1). `Err` names a lacking privilege.
318pub(crate) async fn delete(
319 state: &AppState,
320 dir: &Directory,
321 w: &Writer<'_>,
322 old: &[u8],
323 reply: bool,
324) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
325 let Ok(old) = ICalendar::parse(String::from_utf8_lossy(old).as_ref()) else {
326 return Ok(Ok(Vec::new()));
327 };
328 let role = itip::role(&old, &dir.is(w.owner.id)).ok();
329 removed(state, dir, w, &old, role, reply).await
330}
331
332/// An organizer object going away cancels; an attendee copy declines.
333async fn removed(
334 state: &AppState,
335 dir: &Directory,
336 w: &Writer<'_>,
337 old: &ICalendar,
338 role: Option<Role>,
339 reply: bool,
340) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
341 let owner = w.owner;
342 let owns = dir.is(owner.id);
343 let now = Utc::now();
344 let mut old = old.clone();
345 itip::stamp_sender(&mut old, &owns, w.sent_by.as_deref());
346 let mut ops = Vec::new();
347 match role {
348 Some(Role::Organizer) => {
349 let (_, messages) = itip::organize(Some(&old), None, &owns, now);
350 if !messages.is_empty() && !w.may_schedule {
351 return Ok(Err(w.refused("schedule-send-invite")));
352 }
353 for m in &messages {
354 deliver(state, dir, owner, m, &mut ops).await?;
355 }
356 }
357 Some(Role::Attendee) if reply => {
358 if let Some(m) = itip::decline(&old, &owns, now) {
359 if !w.may_schedule {
360 return Ok(Err(w.refused("schedule-send-reply")));
361 }
362 reply_to(state, dir, owner, &m, &mut ops).await?;
363 }
364 }
365 _ => {}
366 }
367 Ok(Ok(ops))
368}
369
370/// The resource of the owner that already schedules this UID elsewhere:
371/// RFC 6638 allows one per UID (3.2.4.1).
372async fn elsewhere(
373 state: &AppState,
374 owner: &PimPrincipal,
375 cal: &ICalendar,
376 (collection_id, name): (i64, &str),
377) -> Result<Option<Element>, ApiError> {
378 let Some((uid, _)) = identity(cal) else {
379 return Ok(None);
380 };
381 let Some((holder_id, holder, _)) = state.db.pim_find_uid(owner.id, &uid).await? else {
382 return Ok(None);
383 };
384 if holder_id == collection_id && holder.name == name {
385 return Ok(None);
386 }
387 let slug = match state.db.pim_collection_by_id(holder_id).await? {
388 Some((_, _, c)) => c.slug,
389 None => return Ok(None),
390 };
391 let href = collection_href(&owner.name, PimKind::Calendar, &slug, None) + &seg(&holder.name);
392 Ok(Some(with_children(
393 el(CALDAV, "unique-scheduling-object-resource"),
394 hrefs([href.as_str()]),
395 )))
396}
397
398/// Rooms and resources answer their invitations at once: accepted where
399/// free, declined where their bookings overlap. The answers go into the
400/// organizer's `store` and inbox. Returns whether any room answered.
401async fn answer_rooms(
402 state: &AppState,
403 dir: &Directory,
404 organizer: &PimPrincipal,
405 store: &mut ICalendar,
406 messages: &[Message],
407 ops: &mut Vec<PimOp>,
408 now: DateTime<Utc>,
409) -> Result<bool, ApiError> {
410 let mut answered = false;
411 for m in messages
412 .iter()
413 .filter(|m| m.method == Method::Request && !m.quiet)
414 {
415 let Recipient::Local(room) = dir.resolve(&m.to) else {
416 continue;
417 };
418 let Some((uid, component)) = identity(&m.cal) else {
419 continue;
420 };
421 if room.kind == UserType::Individual {
422 continue;
423 }
424 let Some(calendar) = state.db.pim_calendar_for(room.id, &component).await? else {
425 continue;
426 };
427 let current = state
428 .db
429 .pim_find_uid(room.id, &uid)
430 .await?
431 .and_then(|(_, _, d)| ICalendar::parse(String::from_utf8_lossy(&d).as_ref()).ok());
432 let Some(received) = itip::receive(current.as_ref(), m) else {
433 continue;
434 };
435 let is_room = dir.is(room.id);
436 let window = now..now + itip::answer_horizon(&received);
437 let taken = busy_of(state, dir, room, &window, Some(&uid)).await?;
438 let floating = floating_of(calendar.timezone.as_deref());
439 let answer = itip::auto_answer(&received, &is_room, &taken, &window, &floating);
440 let Ok((_, Some(reply))) = itip::attend(&received, answer, &is_room, now) else {
441 continue;
442 };
443 answered |= itip::apply_reply(store, &reply.cal, &is_room);
444 ops.push(inbox(organizer, &reply, &component));
445 }
446 Ok(answered)
447}
448
449/// The busy time a principal shows to scheduling: its opaque calendars that
450/// take events, never the inbox. Objects with UID `skip` do not count.
451// ponytail: reads every object of those calendars per call. Keep busy
452// periods in a table if principals grow large calendars.
453pub(crate) async fn busy_of(
454 state: &AppState,
455 dir: &Directory,
456 p: &PimPrincipal,
457 range: &TimeRange,
458 skip: Option<&str>,
459) -> Result<Vec<Period>, ApiError> {
460 let me = dir.is(p.id);
461 let mut busy = Vec::new();
462 for c in state.db.pim_collections(p.id, PimKind::Calendar).await? {
463 if c.slug == INBOX || c.transparent || !c.components.split(',').any(|x| x == "VEVENT") {
464 continue;
465 }
466 let floating = floating_of(c.timezone.as_deref());
467 for (o, data) in state.db.pim_objects_with_data(c.id).await? {
468 if skip.is_some_and(|u| u == o.uid) {
469 continue;
470 }
471 if let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) {
472 busy.extend(freebusy::busy(&cal, range, &floating, Some(&me)));
473 }
474 }
475 }
476 Ok(freebusy::merge(busy))
477}
478
479fn floating_of(timezone: Option<&str>) -> Zone {
480 timezone.and_then(zone::from_vtimezone).unwrap_or(Zone::Utc)
481}
482
483/// The answers to a free-busy request to an outbox (RFC 6638, 5.2): per
484/// recipient its address, the REQUEST-STATUS and the VFREEBUSY reply.
485pub(crate) async fn free_busy(
486 state: &AppState,
487 dir: &Directory,
488 req: &freebusy::Request,
489) -> Result<Vec<(String, &'static str, Option<String>)>, ApiError> {
490 let now = Utc::now();
491 let mut out = Vec::new();
492 for to in &req.attendees {
493 let (status, data) = match dir.resolve(to) {
494 Recipient::Local(p) => {
495 let busy = busy_of(state, dir, p, &req.range, None).await?;
496 ("2.0;Success", Some(freebusy::reply(&busy, req, to, now)))
497 }
498 Recipient::Unknown => ("3.7;Invalid calendar user", None),
499 Recipient::External => ("5.2;Invalid calendar service", None),
500 };
501 out.push((to.clone(), status, data));
502 }
503 Ok(out)
504}
505
506/// A REQUEST or CANCEL from `sender` into the recipient's calendar and
507/// inbox. Returns the delivery status, `None` for the sender itself.
508async fn deliver(
509 state: &AppState,
510 dir: &Directory,
511 sender: &PimPrincipal,
512 m: &Message,
513 ops: &mut Vec<PimOp>,
514) -> Result<Option<&'static str>, ApiError> {
515 let p = match dir.resolve(&m.to) {
516 Recipient::Local(p) if p.id == sender.id => return Ok(None),
517 Recipient::Local(p) => p,
518 Recipient::Unknown => return Ok(Some(INVALID_USER)),
519 Recipient::External => return Ok(Some(NO_ROUTE)),
520 };
521 ensure(state, p).await?;
522 let Some((uid, component)) = identity(&m.cal) else {
523 return Ok(Some(REFUSED));
524 };
525 let copy = state.db.pim_find_uid(p.id, &uid).await?;
526 let current = copy
527 .as_ref()
528 .and_then(|(_, _, d)| ICalendar::parse(String::from_utf8_lossy(d).as_ref()).ok());
529 if let Some(next) = itip::receive(current.as_ref(), m) {
530 let data = next.to_string().into_bytes();
531 let etag = etag_of(&data);
532 let (collection_id, name, schedule_tag) = match copy {
533 // Only the others' answers changed: the attendee's pending edit
534 // may still go through (RFC 6638, 3.2.10).
535 Some((id, obj, _)) => (
536 id,
537 obj.name,
538 if m.quiet {
539 obj.schedule_tag
540 } else {
541 Some(etag.clone())
542 },
543 ),
544 None => match state.db.pim_calendar_for(p.id, &component).await? {
545 Some(c) => (
546 c.id,
547 object_name(&uid, PimKind::Calendar),
548 Some(etag.clone()),
549 ),
550 None => return Ok(Some(REFUSED)),
551 },
552 };
553 ops.push(PimOp::Put {
554 collection_id,
555 obj: PimObject {
556 name,
557 uid,
558 component: component.clone(),
559 etag,
560 schedule_tag,
561 ..Default::default()
562 },
563 data,
564 });
565 }
566 if !m.quiet {
567 ops.push(inbox(p, m, &component));
568 }
569 Ok(Some(DELIVERED))
570}
571
572/// An attendee's REPLY: applied to the organizer's object, passed on to the
573/// other attendees, and left in the organizer's inbox. Returns the delivery
574/// status for the attendee's copy.
575async fn reply_to(
576 state: &AppState,
577 dir: &Directory,
578 attendee: &PimPrincipal,
579 m: &Message,
580 ops: &mut Vec<PimOp>,
581) -> Result<&'static str, ApiError> {
582 let organizer = match dir.resolve(&m.to) {
583 Recipient::Local(p) => p,
584 Recipient::Unknown => return Ok(INVALID_USER),
585 Recipient::External => return Ok(NO_ROUTE),
586 };
587 let Some((uid, component)) = identity(&m.cal) else {
588 return Ok(REFUSED);
589 };
590 // RFC 6638, 4.2: a reply to an object the organizer no longer has is
591 // ignored.
592 let Some((collection_id, obj, data)) = state.db.pim_find_uid(organizer.id, &uid).await? else {
593 return Ok(NO_ROUTE);
594 };
595 let Ok(before) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) else {
596 return Ok(NO_ROUTE);
597 };
598 let mut after = before.clone();
599 let replier = dir.is(attendee.id);
600 if itip::apply_reply(&mut after, &m.cal, &replier) {
601 let data = after.to_string().into_bytes();
602 ops.push(PimOp::Put {
603 collection_id,
604 obj: PimObject {
605 etag: etag_of(&data),
606 ..obj
607 },
608 data,
609 });
610 // The others learn the new answer without a new Schedule-Tag.
611 let organizes = dir.is(organizer.id);
612 for mut other in itip::messages(Some(&before), Some(&after), &organizes, &[], Utc::now()) {
613 if other.method == Method::Request && !replier(&other.to) {
614 other.quiet = true;
615 deliver(state, dir, organizer, &other, ops).await?;
616 }
617 }
618 }
619 ops.push(inbox(organizer, m, &component));
620 Ok(DELIVERED)
621}
622
623async fn ensure(state: &AppState, p: &PimPrincipal) -> Result<(), ApiError> {
624 match p.kind {
625 UserType::Individual => state.db.pim_ensure_defaults(p.id).await?,
626 _ => state.db.pim_ensure_inbox(p.id).await?,
627 }
628 Ok(())
629}
630
631fn inbox(p: &PimPrincipal, m: &Message, component: &str) -> PimOp {
632 let data = m.cal.to_string().into_bytes();
633 let stamp = Utc::now().timestamp_nanos_opt().unwrap_or_default();
634 let seed = format!(
635 "{}\n{}\n{stamp}\n{:?}",
636 m.to,
637 String::from_utf8_lossy(&data),
638 m.method
639 );
640 let name = format!("{}.ics", &crate::hex(&Sha256::digest(seed))[..32]);
641 PimOp::Inbox {
642 principal_id: p.id,
643 obj: PimObject {
644 // Inbox messages share UIDs, and the store keeps UIDs unique.
645 uid: name.clone(),
646 name,
647 component: component.to_string(),
648 etag: etag_of(&data),
649 ..Default::default()
650 },
651 data,
652 }
653}
654
655/// UID and component type of a scheduling message or object.
656fn identity(cal: &ICalendar) -> Option<(String, String)> {
657 let c = cal.components.iter().find(|c| {
658 matches!(
659 c.component_type,
660 ICalendarComponentType::VEvent
661 | ICalendarComponentType::VTodo
662 | ICalendarComponentType::VJournal
663 )
664 })?;
665 Some((c.uid()?.to_string(), c.component_type.as_str().to_string()))
666}
667