pim_views.rs
⎇
Raw
1//! What the web UI shows of calendars and address books (session-authenticated):
2//! - `GET {PIM_INSTANCES}` — occurrences in a range
3//! - `GET {PIM_COLLECTIONS}/{id}{OBJECTS_SUFFIX}/{name}` — one event or contact
4//! - `GET {PIM_CONTACTS}` — contacts, searched
5//! - `GET {PIM_INVITATIONS}`, `POST` a reply — unanswered invitations
6//!
7//! The UI never parses iCalendar or vCard: these endpoints do.
8
9use std::collections::{HashMap, HashSet};
10use std::sync::Arc;
11
12use api_types::{
13 OBJECTS_SUFFIX, OkResp, PHOTO_SUFFIX, PIM_COLLECTIONS, PimAttendee, PimContact,
14 PimContactDetail, PimEventDetail, PimInstance, PimInstances, PimInvitation, PimLabeled,
15 PimObjectDetail, PimPerson, PimReply, PimShareMode,
16};
17use axum::Json;
18use axum::extract::{Path as AxumPath, Query, State};
19use axum::http::StatusCode;
20use chrono::{DateTime, SecondsFormat, TimeDelta, Utc};
21use pimdav::calcard::icalendar::{
22 ICalendar, ICalendarComponentType, ICalendarParticipationStatus, ICalendarProperty,
23};
24use pimdav::expand::expand;
25use pimdav::itip::{self, Role};
26use pimdav::principal::UserType;
27use pimdav::view::{self, Card, EventInfo, Person};
28use pimdav::zone::{self, Zone};
29use serde::Deserialize;
30
31use crate::api::common::SessionUser;
32use crate::api::common::blocking;
33use crate::api::pim::{BIRTHDAYS, DIRECTORY, INBOX, etag_of, generated, mailto, members_of, seg};
34use crate::api::pim_api::reachable;
35use crate::api::pim_schedule::{self, Directory, Writer};
36use crate::db::{PimKind, PimObject, PimOp};
37use crate::error::{ApiError, AppState};
38
39/// The widest range `GET {PIM_INSTANCES}` expands.
40const MAX_RANGE_DAYS: i64 = 400;
41/// The most instances one answer holds.
42const MAX_INSTANCES: usize = 5000;
43/// How far ahead an invitation's next instance is looked for.
44const INVITATION_HORIZON_DAYS: i64 = 3653;
45
46fn rfc3339(t: DateTime<Utc>) -> String {
47 t.to_rfc3339_opts(SecondsFormat::Secs, true)
48}
49
50fn parse_time(s: &str) -> Result<DateTime<Utc>, ApiError> {
51 DateTime::parse_from_rfc3339(s)
52 .map(|t| t.with_timezone(&Utc))
53 .map_err(|_| ApiError::new(StatusCode::BAD_REQUEST, "times must be RFC 3339"))
54}
55
56/// The zone all-day and floating times are read in: the viewer's.
57fn floating(tz: Option<&str>) -> Zone {
58 tz.and_then(zone::by_name).unwrap_or(Zone::Utc)
59}
60
61fn wanted(ids: Option<&str>) -> Option<HashSet<i64>> {
62 ids.map(|s| s.split(',').filter_map(|i| i.trim().parse().ok()).collect())
63}
64
65/// `(collection id, owner principal)` of the calendars or address books the
66/// signed-in user reads: own ones, the generated one and lent ones. Not the
67/// scheduling inbox.
68async fn readable(
69 state: &AppState,
70 auth: &SessionUser,
71 kind: PimKind,
72) -> Result<Vec<(i64, i64)>, ApiError> {
73 let db = &state.db;
74 let pid = db.principal_of(auth.user.id).await?;
75 db.pim_ensure_defaults(pid).await?;
76 let mut out: Vec<(i64, i64)> = db
77 .pim_collections(pid, kind)
78 .await?
79 .into_iter()
80 .filter(|c| c.slug != INBOX)
81 .map(|c| (c.id, pid))
82 .collect();
83 out.push(match kind {
84 PimKind::Calendar => (BIRTHDAYS, pid),
85 PimKind::AddressBook => (DIRECTORY, pid),
86 });
87 for (col, _, _) in db.pim_shared_collections(auth.user.id, kind).await? {
88 if let Some((owner, _, _)) = db.pim_collection_by_id(col.id).await? {
89 out.push((col.id, owner));
90 }
91 }
92 Ok(out)
93}
94
95fn parse(data: &[u8]) -> Option<ICalendar> {
96 ICalendar::parse(String::from_utf8_lossy(data).as_ref()).ok()
97}
98
99fn display(p: &Person) -> String {
100 p.name.clone().unwrap_or_else(|| {
101 p.address
102 .strip_prefix("mailto:")
103 .unwrap_or(&p.address)
104 .to_string()
105 })
106}
107
108fn wire_person(p: &Person) -> PimPerson {
109 PimPerson {
110 name: p.name.clone(),
111 address: p.address.clone(),
112 }
113}
114
115#[derive(Deserialize)]
116pub struct InstancesQuery {
117 from: String,
118 to: String,
119 tz: Option<String>,
120 collections: Option<String>,
121}
122
123/// GET {PIM_INSTANCES}
124// ponytail: parses and expands every object of every calendar on each call.
125// Index each object's first and last instance if large calendars get slow.
126pub async fn instances(
127 State(state): State<Arc<AppState>>,
128 auth: SessionUser,
129 Query(q): Query<InstancesQuery>,
130) -> Result<Json<PimInstances>, ApiError> {
131 let (from, to) = (parse_time(&q.from)?, parse_time(&q.to)?);
132 if to <= from || to - from > TimeDelta::days(MAX_RANGE_DAYS) {
133 return Err(ApiError::new(
134 StatusCode::BAD_REQUEST,
135 "the range must be positive and at most 400 days",
136 ));
137 }
138 let zone = floating(q.tz.as_deref());
139 let wanted = wanted(q.collections.as_deref());
140 let dir = Directory::load(&state).await?;
141 let mut sources = Vec::new();
142 for (id, owner) in readable(&state, &auth, PimKind::Calendar).await? {
143 if wanted.as_ref().is_some_and(|w| !w.contains(&id)) {
144 continue;
145 }
146 sources.push((id, owner, members_of(&state, owner, id).await?));
147 }
148 let (mut out, truncated) = blocking(move || -> Result<_, ApiError> {
149 let mut out = Vec::new();
150 let mut truncated = false;
151 'all: for (id, owner, members) in sources {
152 let owns = dir.is(owner);
153 for (obj, data) in members {
154 let Some(cal) = parse(&data) else {
155 continue;
156 };
157 let exp = expand(&cal, from..to, zone.clone());
158 truncated |= exp.truncated;
159 let mut infos: HashMap<usize, EventInfo> = HashMap::new();
160 for i in exp.instances {
161 if cal.components[i.component].component_type != ICalendarComponentType::VEvent
162 {
163 continue;
164 }
165 if out.len() == MAX_INSTANCES {
166 truncated = true;
167 break 'all;
168 }
169 let info = infos
170 .entry(i.component)
171 .or_insert_with(|| view::event_info(&cal, i.component, &owns));
172 out.push(PimInstance {
173 collection_id: id,
174 name: obj.name.clone(),
175 uid: obj.uid.clone(),
176 recurrence_id: i.recurrence_id.map(rfc3339),
177 start: rfc3339(i.start),
178 end: rfc3339(i.end),
179 all_day: info.all_day,
180 component: info.component.clone(),
181 summary: info.summary.clone(),
182 location: info.location.clone(),
183 status: info.status.clone(),
184 transparent: info.transparent,
185 has_attendees: !info.attendees.is_empty(),
186 partstat: info.partstat().map(str::to_string),
187 organizer: info.organizer.as_ref().map(display),
188 });
189 }
190 }
191 }
192 Ok((out, truncated))
193 })
194 .await?;
195 out.sort_by(|a, b| (&a.start, &a.end).cmp(&(&b.start, &b.end)));
196 Ok(Json(PimInstances {
197 instances: out,
198 truncated,
199 }))
200}
201
202#[derive(Deserialize)]
203pub struct DetailQuery {
204 recurrence_id: Option<String>,
205 tz: Option<String>,
206}
207
208/// GET {PIM_COLLECTIONS}/{id}{OBJECTS_SUFFIX}/{name}
209pub async fn object(
210 State(state): State<Arc<AppState>>,
211 auth: SessionUser,
212 AxumPath((id, name)): AxumPath<(i64, String)>,
213 Query(q): Query<DetailQuery>,
214) -> Result<Json<PimObjectDetail>, ApiError> {
215 let not_found = || ApiError::new(StatusCode::NOT_FOUND, "object not found");
216 let (owner, kind, col, writable) = reachable(&state, &auth, id).await?;
217 let found = match generated(col.id) {
218 true => members_of(&state, owner, col.id)
219 .await?
220 .into_iter()
221 .find(|(o, _)| o.name == name),
222 false => state.db.pim_object(col.id, &name).await?,
223 };
224 let (obj, data) = &found.ok_or_else(not_found)?;
225 match kind {
226 PimKind::Calendar => {
227 let cal = parse(data).ok_or_else(not_found)?;
228 let zone = floating(q.tz.as_deref());
229 let rid = q.recurrence_id.as_deref().map(parse_time).transpose()?;
230 let index = view::component_for(&cal, rid, &zone).ok_or_else(not_found)?;
231 let dir = Directory::load(&state).await?;
232 let owns = dir.is(owner);
233 let info = view::event_info(&cal, index, &owns);
234 let instance = view::instance_for(&cal, index, rid, &zone);
235 let answers = may_answer(&state, &auth, owner, col.id).await?;
236 let attendee = matches!(itip::role(&cal, &owns), Ok(Role::Attendee));
237 Ok(Json(PimObjectDetail::Event(PimEventDetail {
238 collection_id: id,
239 name: obj.name.clone(),
240 uid: obj.uid.clone(),
241 component: info.component,
242 summary: info.summary,
243 description: info.description,
244 location: info.location,
245 url: info.url,
246 status: info.status,
247 transparent: info.transparent,
248 all_day: info.all_day,
249 start: instance.as_ref().map(|i| rfc3339(i.start)),
250 end: instance.as_ref().map(|i| rfc3339(i.end)),
251 categories: info.categories,
252 rrule: info.rrule,
253 organizer: info.organizer.as_ref().map(wire_person),
254 attendees: info
255 .attendees
256 .iter()
257 .map(|a| PimAttendee {
258 person: wire_person(&a.person),
259 partstat: a.partstat.clone(),
260 role: a.role.clone(),
261 is_owner: a.is_owner,
262 })
263 .collect(),
264 can_edit: writable,
265 can_reply: attendee && answers,
266 })))
267 }
268 PimKind::AddressBook => {
269 let card = view::card(&String::from_utf8_lossy(data));
270 let members = match card.is_group {
271 true => {
272 let by_uid: HashMap<String, String> = members_of(&state, owner, col.id)
273 .await?
274 .iter()
275 .map(|(_, d)| view::card(&String::from_utf8_lossy(d)))
276 .filter_map(|c| Some((c.uid?, c.full_name)))
277 .collect();
278 card.members
279 .iter()
280 .map(|m| by_uid.get(m).cloned().unwrap_or_else(|| m.clone()))
281 .collect()
282 }
283 false => Vec::new(),
284 };
285 let photo_url = card.has_photo.then(|| {
286 format!(
287 "{PIM_COLLECTIONS}/{id}{OBJECTS_SUFFIX}/{}{PHOTO_SUFFIX}",
288 seg(&obj.name)
289 )
290 });
291 Ok(Json(PimObjectDetail::Contact(contact_detail(
292 id, obj, card, members, photo_url, writable,
293 ))))
294 }
295 }
296}
297
298fn labeled(v: Vec<view::Labeled>) -> Vec<PimLabeled> {
299 v.into_iter()
300 .map(|l| PimLabeled {
301 label: l.label,
302 value: l.value,
303 })
304 .collect()
305}
306
307fn contact_detail(
308 id: i64,
309 obj: &PimObject,
310 card: Card,
311 members: Vec<String>,
312 photo_url: Option<String>,
313 can_edit: bool,
314) -> PimContactDetail {
315 PimContactDetail {
316 collection_id: id,
317 name: obj.name.clone(),
318 uid: card.uid,
319 full_name: card.full_name,
320 org: card.org,
321 title: card.title,
322 emails: labeled(card.emails),
323 phones: labeled(card.phones),
324 addresses: labeled(card.addresses),
325 urls: labeled(card.urls),
326 birthday: card.birthday,
327 anniversary: card.anniversary,
328 note: card.note,
329 is_group: card.is_group,
330 members,
331 photo_url,
332 can_edit,
333 }
334}
335
336/// Whether the signed-in user may answer invitations in a calendar of
337/// `owner`: their own, or one lent with `rw+schedule`.
338pub(super) async fn may_answer(
339 state: &AppState,
340 auth: &SessionUser,
341 owner: i64,
342 collection_id: i64,
343) -> Result<bool, ApiError> {
344 if collection_id <= DIRECTORY {
345 return Ok(false);
346 }
347 if owner == state.db.principal_of(auth.user.id).await? {
348 return Ok(true);
349 }
350 Ok(state
351 .db
352 .pim_shared_collection(auth.user.id, PimKind::Calendar, collection_id)
353 .await?
354 .is_some_and(|(_, _, mode)| mode == PimShareMode::RwSchedule))
355}
356
357#[derive(Deserialize)]
358pub struct ContactsQuery {
359 q: Option<String>,
360 collections: Option<String>,
361}
362
363/// GET {PIM_CONTACTS}
364pub async fn contacts(
365 State(state): State<Arc<AppState>>,
366 auth: SessionUser,
367 Query(q): Query<ContactsQuery>,
368) -> Result<Json<Vec<PimContact>>, ApiError> {
369 let needle = q.q.as_deref().map(str::trim).unwrap_or("").to_lowercase();
370 let wanted = wanted(q.collections.as_deref());
371 let mut sources = Vec::new();
372 for (id, owner) in readable(&state, &auth, PimKind::AddressBook).await? {
373 if wanted.as_ref().is_some_and(|w| !w.contains(&id)) {
374 continue;
375 }
376 sources.push((id, members_of(&state, owner, id).await?));
377 }
378 let mut out = blocking(move || -> Result<_, ApiError> {
379 let mut out = Vec::new();
380 for (id, members) in sources {
381 for (obj, data) in members {
382 let c = view::card(&String::from_utf8_lossy(&data));
383 let hit = needle.is_empty()
384 || [Some(&c.full_name), c.org.as_ref()]
385 .into_iter()
386 .flatten()
387 .chain(c.emails.iter().map(|e| &e.value))
388 .chain(c.phones.iter().map(|p| &p.value))
389 .any(|v| v.to_lowercase().contains(&needle));
390 if !hit {
391 continue;
392 }
393 out.push(PimContact {
394 collection_id: id,
395 name: obj.name,
396 full_name: c.full_name,
397 org: c.org,
398 email: c.emails.into_iter().next().map(|e| e.value),
399 phone: c.phones.into_iter().next().map(|p| p.value),
400 has_photo: c.has_photo,
401 is_group: c.is_group,
402 });
403 }
404 }
405 Ok(out)
406 })
407 .await?;
408 out.sort_by_cached_key(|c| (c.full_name.to_lowercase(), c.collection_id));
409 Ok(Json(out))
410}
411
412#[derive(Deserialize)]
413pub struct TzQuery {
414 tz: Option<String>,
415}
416
417/// GET {PIM_INVITATIONS}: in the signed-in user's own calendars, the series
418/// and instances they are invited to and have not answered, and whose next
419/// instance is still ahead.
420pub async fn invitations(
421 State(state): State<Arc<AppState>>,
422 auth: SessionUser,
423 Query(q): Query<TzQuery>,
424) -> Result<Json<Vec<PimInvitation>>, ApiError> {
425 let db = &state.db;
426 let pid = db.principal_of(auth.user.id).await?;
427 let dir = Directory::load(&state).await?;
428 let owns = dir.is(pid);
429 let zone = floating(q.tz.as_deref());
430 let now = Utc::now();
431 let window = now..now + TimeDelta::days(INVITATION_HORIZON_DAYS);
432 let mut out = Vec::new();
433 for col in db.pim_collections(pid, PimKind::Calendar).await? {
434 if col.slug == INBOX {
435 continue;
436 }
437 for (obj, data) in db.pim_objects_with_data(col.id).await? {
438 // Most objects invite no one: skip their parse.
439 if !data.windows(8).any(|w| w.eq_ignore_ascii_case(b"ATTENDEE")) {
440 continue;
441 }
442 let Some(cal) = parse(&data) else {
443 continue;
444 };
445 if !matches!(itip::role(&cal, &owns), Ok(Role::Attendee)) {
446 continue;
447 }
448 let instances = expand(&cal, window.clone(), zone.clone()).instances;
449 for (index, c) in cal.components.iter().enumerate() {
450 if c.component_type != ICalendarComponentType::VEvent {
451 continue;
452 }
453 let info = view::event_info(&cal, index, &owns);
454 if info.partstat() != Some("NEEDS-ACTION")
455 || info.status.as_deref() == Some("CANCELLED")
456 {
457 continue;
458 }
459 let Some(next) = instances.iter().find(|i| i.component == index) else {
460 continue;
461 };
462 let is_override = c.has_property(&ICalendarProperty::RecurrenceId);
463 out.push(PimInvitation {
464 collection_id: col.id,
465 name: obj.name.clone(),
466 uid: obj.uid.clone(),
467 recurrence_id: is_override
468 .then_some(next.recurrence_id)
469 .flatten()
470 .map(rfc3339),
471 summary: info.summary.clone(),
472 location: info.location.clone(),
473 organizer: info.organizer.as_ref().map(wire_person),
474 start: rfc3339(next.start),
475 end: rfc3339(next.end),
476 all_day: info.all_day,
477 recurring: info.rrule.is_some() && !is_override,
478 rrule: info.rrule.clone().filter(|_| !is_override),
479 });
480 }
481 }
482 }
483 out.sort_by(|a, b| a.start.cmp(&b.start));
484 Ok(Json(out))
485}
486
487/// POST {PIM_INVITATIONS}: writes the answer into the calendar owner's copy
488/// through the same path as a client's PUT, so the organizer gets the REPLY.
489pub async fn reply(
490 State(state): State<Arc<AppState>>,
491 auth: SessionUser,
492 Json(body): Json<PimReply>,
493) -> Result<Json<OkResp>, ApiError> {
494 let answer = match body.partstat.to_ascii_uppercase().as_str() {
495 "ACCEPTED" => ICalendarParticipationStatus::Accepted,
496 "TENTATIVE" => ICalendarParticipationStatus::Tentative,
497 "DECLINED" => ICalendarParticipationStatus::Declined,
498 _ => {
499 return Err(ApiError::new(
500 StatusCode::BAD_REQUEST,
501 "partstat must be ACCEPTED, TENTATIVE or DECLINED",
502 ));
503 }
504 };
505 let rid = body.recurrence_id.as_deref().map(parse_time).transpose()?;
506 let (owner, kind, col, _) = reachable(&state, &auth, body.collection_id).await?;
507 if kind != PimKind::Calendar || !may_answer(&state, &auth, owner, col.id).await? {
508 return Err(ApiError::new(StatusCode::FORBIDDEN, "cannot answer here"));
509 }
510 let not_found = || ApiError::new(StatusCode::NOT_FOUND, "object not found");
511 let _lock = pim_schedule::LOCK.lock().await;
512 let (obj, old) = state
513 .db
514 .pim_object(col.id, &body.name)
515 .await?
516 .ok_or_else(not_found)?;
517 let cal = parse(&old).ok_or_else(not_found)?;
518 let dir = Directory::load(&state).await?;
519 let principal = dir.get(owner).cloned().ok_or_else(not_found)?;
520 let owns = dir.is(owner);
521 if !matches!(itip::role(&cal, &owns), Ok(Role::Attendee)) {
522 return Err(ApiError::new(
523 StatusCode::BAD_REQUEST,
524 "the calendar owner is not an attendee",
525 ));
526 }
527 let zone = floating(body.tz.as_deref());
528 let new = itip::respond(&cal, &owns, answer, rid, &zone).to_string();
529 let me = state.db.principal_of(auth.user.id).await?;
530 let w = Writer {
531 owner: &principal,
532 may_schedule: true,
533 sent_by: (me != owner)
534 .then(|| format!("mailto:{}", mailto(&auth.user.name, UserType::Individual))),
535 };
536 let stored = match pim_schedule::put(
537 &state,
538 &dir,
539 &w,
540 (col.id, &obj.name),
541 Some(&old),
542 new.as_bytes(),
543 )
544 .await?
545 {
546 Ok(s) => s,
547 Err(condition) => return Err(ApiError::new(StatusCode::FORBIDDEN, &condition.name)),
548 };
549 let mut ops = vec![PimOp::Put {
550 collection_id: col.id,
551 obj: PimObject {
552 etag: etag_of(&stored.data),
553 schedule_tag: stored.schedule_tag.clone(),
554 ..obj
555 },
556 data: stored.data,
557 }];
558 ops.extend(stored.ops);
559 state.db.pim_apply(&ops).await?;
560 Ok(Json(OkResp {}))
561}
562