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::render;
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, generated, member_of, members_of, seg};
34use crate::api::pim_api::reachable;
35use crate::api::pim_schedule::{self, Directory, Writer};
36use crate::db::{PimKind, PimObject};
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 render::parse(&String::from_utf8_lossy(data))
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, _) = reachable(&state, &auth, id).await?;
217 let found = member_of(&state, owner, col.id, &name).await?;
218 let (obj, data) = &found.ok_or_else(not_found)?;
219 match kind {
220 PimKind::Calendar => {
221 let cal = parse(data).ok_or_else(not_found)?;
222 let zone = floating(q.tz.as_deref());
223 let rid = q.recurrence_id.as_deref().map(parse_time).transpose()?;
224 let index = view::component_for(&cal, rid, &zone).ok_or_else(not_found)?;
225 let dir = Directory::load(&state).await?;
226 let owns = dir.is(owner);
227 let instance = view::instance_for(&cal, index, rid, &zone);
228 // An instance a THISANDFUTURE override moved takes its text too.
229 let info = view::event_info(
230 &cal,
231 instance.as_ref().map_or(index, |i| i.component),
232 &owns,
233 );
234 let answers = may_answer(&state, &auth, owner, col.id).await?;
235 let attendee = matches!(itip::role(&cal, &owns), Ok(Role::Attendee));
236 Ok(Json(PimObjectDetail::Event(PimEventDetail {
237 collection_id: id,
238 name: obj.name.clone(),
239 uid: obj.uid.clone(),
240 component: info.component,
241 summary: info.summary,
242 description: info.description,
243 location: info.location,
244 url: info.url,
245 status: info.status,
246 transparent: info.transparent,
247 all_day: info.all_day,
248 start: instance.as_ref().map(|i| rfc3339(i.start)),
249 end: instance.as_ref().map(|i| rfc3339(i.end)),
250 categories: info.categories,
251 rrule: info.rrule,
252 organizer: info.organizer.as_ref().map(wire_person),
253 attendees: info
254 .attendees
255 .iter()
256 .map(|a| PimAttendee {
257 person: wire_person(&a.person),
258 partstat: a.partstat.clone(),
259 role: a.role.clone(),
260 is_owner: a.is_owner,
261 })
262 .collect(),
263 is_override: cal.components[index].has_property(&ICalendarProperty::RecurrenceId),
264 series_partstat: view::component_for(&cal, None, &zone)
265 .filter(|&m| !cal.components[m].has_property(&ICalendarProperty::RecurrenceId))
266 .and_then(|m| {
267 view::event_info(&cal, m, &owns)
268 .partstat()
269 .map(str::to_string)
270 }),
271 can_reply: attendee && answers,
272 })))
273 }
274 PimKind::Addressbook => {
275 let card = view::card(&String::from_utf8_lossy(data));
276 let members = match card.is_group {
277 true => {
278 let by_uid: HashMap<String, String> = members_of(&state, owner, col.id)
279 .await?
280 .iter()
281 .map(|(_, d)| view::card(&String::from_utf8_lossy(d)))
282 .filter_map(|c| Some((c.uid?, c.full_name)))
283 .collect();
284 card.members
285 .iter()
286 .map(|m| by_uid.get(m).cloned().unwrap_or_else(|| m.clone()))
287 .collect()
288 }
289 false => Vec::new(),
290 };
291 // photo() reads stored objects only.
292 let photo_url = (card.has_photo && !generated(col.id)).then(|| {
293 format!(
294 "{PIM_COLLECTIONS}/{id}{OBJECTS_SUFFIX}/{}{PHOTO_SUFFIX}",
295 seg(&obj.name)
296 )
297 });
298 Ok(Json(PimObjectDetail::Contact(contact_detail(
299 id, obj, card, members, photo_url,
300 ))))
301 }
302 }
303}
304
305fn labeled(v: Vec<view::Labeled>) -> Vec<PimLabeled> {
306 v.into_iter()
307 .map(|l| PimLabeled {
308 label: l.label,
309 value: l.value,
310 })
311 .collect()
312}
313
314fn contact_detail(
315 id: i64,
316 obj: &PimObject,
317 card: Card,
318 members: Vec<String>,
319 photo_url: Option<String>,
320) -> PimContactDetail {
321 PimContactDetail {
322 collection_id: id,
323 name: obj.name.clone(),
324 uid: card.uid,
325 full_name: card.full_name,
326 org: card.org,
327 title: card.title,
328 emails: labeled(card.emails),
329 phones: labeled(card.phones),
330 addresses: labeled(card.addresses),
331 urls: labeled(card.urls),
332 birthday: card.birthday,
333 anniversary: card.anniversary,
334 note: card.note,
335 is_group: card.is_group,
336 members,
337 photo_url,
338 }
339}
340
341/// Whether the signed-in user may answer invitations in a calendar of
342/// `owner`: their own, or one lent with `rw+schedule`.
343pub(super) async fn may_answer(
344 state: &AppState,
345 auth: &SessionUser,
346 owner: i64,
347 collection_id: i64,
348) -> Result<bool, ApiError> {
349 if collection_id <= DIRECTORY {
350 return Ok(false);
351 }
352 if owner == state.db.principal_of(auth.user.id).await? {
353 return Ok(true);
354 }
355 Ok(state
356 .db
357 .pim_shared_collection(auth.user.id, PimKind::Calendar, collection_id)
358 .await?
359 .is_some_and(|(_, _, mode)| mode == PimShareMode::RwSchedule))
360}
361
362#[derive(Deserialize)]
363pub struct ContactsQuery {
364 q: Option<String>,
365 collections: Option<String>,
366}
367
368/// GET {PIM_CONTACTS}
369pub async fn contacts(
370 State(state): State<Arc<AppState>>,
371 auth: SessionUser,
372 Query(q): Query<ContactsQuery>,
373) -> Result<Json<Vec<PimContact>>, ApiError> {
374 let needle = q.q.as_deref().map(str::trim).unwrap_or("").to_lowercase();
375 let wanted = wanted(q.collections.as_deref());
376 let mut sources = Vec::new();
377 for (id, owner) in readable(&state, &auth, PimKind::Addressbook).await? {
378 if wanted.as_ref().is_some_and(|w| !w.contains(&id)) {
379 continue;
380 }
381 sources.push((id, members_of(&state, owner, id).await?));
382 }
383 let mut out = blocking(move || -> Result<_, ApiError> {
384 let mut out = Vec::new();
385 for (id, members) in sources {
386 for (obj, data) in members {
387 let c = view::card(&String::from_utf8_lossy(&data));
388 let hit = needle.is_empty()
389 || [Some(&c.full_name), c.org.as_ref()]
390 .into_iter()
391 .flatten()
392 .chain(c.emails.iter().map(|e| &e.value))
393 .chain(c.phones.iter().map(|p| &p.value))
394 .any(|v| v.to_lowercase().contains(&needle));
395 if !hit {
396 continue;
397 }
398 out.push(PimContact {
399 collection_id: id,
400 name: obj.name,
401 full_name: c.full_name,
402 org: c.org,
403 email: c.emails.into_iter().next().map(|e| e.value),
404 phone: c.phones.into_iter().next().map(|p| p.value),
405 has_photo: c.has_photo && !generated(id),
406 is_group: c.is_group,
407 });
408 }
409 }
410 Ok(out)
411 })
412 .await?;
413 out.sort_by_cached_key(|c| (c.full_name.to_lowercase(), c.collection_id));
414 Ok(Json(out))
415}
416
417#[derive(Deserialize)]
418pub struct TzQuery {
419 tz: Option<String>,
420}
421
422/// GET {PIM_INVITATIONS}: in the signed-in user's own calendars, the series
423/// and instances they are invited to and have not answered, and whose next
424/// instance is still ahead.
425pub async fn invitations(
426 State(state): State<Arc<AppState>>,
427 auth: SessionUser,
428 Query(q): Query<TzQuery>,
429) -> Result<Json<Vec<PimInvitation>>, ApiError> {
430 let db = &state.db;
431 let pid = db.principal_of(auth.user.id).await?;
432 let dir = Directory::load(&state).await?;
433 let owns = dir.is(pid);
434 let zone = floating(q.tz.as_deref());
435 let now = Utc::now();
436 let window = now..now + TimeDelta::days(INVITATION_HORIZON_DAYS);
437 let mut out = Vec::new();
438 for col in db.pim_collections(pid, PimKind::Calendar).await? {
439 if col.slug == INBOX {
440 continue;
441 }
442 for (obj, data) in db.pim_objects_with_data(col.id).await? {
443 // Most objects invite no one: skip their parse.
444 if !data.windows(8).any(|w| w.eq_ignore_ascii_case(b"ATTENDEE")) {
445 continue;
446 }
447 let Some(cal) = parse(&data) else {
448 continue;
449 };
450 if !matches!(itip::role(&cal, &owns), Ok(Role::Attendee)) {
451 continue;
452 }
453 let instances = expand(&cal, window.clone(), zone.clone()).instances;
454 for (index, c) in cal.components.iter().enumerate() {
455 if c.component_type != ICalendarComponentType::VEvent {
456 continue;
457 }
458 let info = view::event_info(&cal, index, &owns);
459 if info.partstat() != Some("NEEDS-ACTION")
460 || info.status.as_deref() == Some("CANCELLED")
461 {
462 continue;
463 }
464 let Some(next) = instances.iter().find(|i| i.component == index) else {
465 continue;
466 };
467 let is_override = c.has_property(&ICalendarProperty::RecurrenceId);
468 out.push(PimInvitation {
469 collection_id: col.id,
470 name: obj.name.clone(),
471 uid: obj.uid.clone(),
472 recurrence_id: is_override
473 .then_some(next.recurrence_id)
474 .flatten()
475 .map(rfc3339),
476 summary: info.summary.clone(),
477 location: info.location.clone(),
478 organizer: info.organizer.as_ref().map(wire_person),
479 start: rfc3339(next.start),
480 end: rfc3339(next.end),
481 all_day: info.all_day,
482 recurring: info.rrule.is_some() && !is_override,
483 rrule: info.rrule.clone().filter(|_| !is_override),
484 });
485 }
486 }
487 }
488 out.sort_by(|a, b| a.start.cmp(&b.start));
489 Ok(Json(out))
490}
491
492/// POST {PIM_INVITATIONS}: writes the answer into the calendar owner's copy
493/// through the same path as a client's PUT, so the organizer gets the REPLY.
494pub async fn reply(
495 State(state): State<Arc<AppState>>,
496 auth: SessionUser,
497 Json(body): Json<PimReply>,
498) -> Result<Json<OkResp>, ApiError> {
499 let answer = match body.partstat.to_ascii_uppercase().as_str() {
500 "ACCEPTED" => ICalendarParticipationStatus::Accepted,
501 "TENTATIVE" => ICalendarParticipationStatus::Tentative,
502 "DECLINED" => ICalendarParticipationStatus::Declined,
503 _ => {
504 return Err(ApiError::new(
505 StatusCode::BAD_REQUEST,
506 "partstat must be ACCEPTED, TENTATIVE or DECLINED",
507 ));
508 }
509 };
510 let rid = body.recurrence_id.as_deref().map(parse_time).transpose()?;
511 let _lock = pim_schedule::LOCK.lock().await;
512 let (owner, kind, col, _) = reachable(&state, &auth, body.collection_id).await?;
513 if kind != PimKind::Calendar || !may_answer(&state, &auth, owner, col.id).await? {
514 return Err(ApiError::new(StatusCode::FORBIDDEN, "cannot answer here"));
515 }
516 let not_found = || ApiError::new(StatusCode::NOT_FOUND, "object not found");
517 let (obj, old) = state
518 .db
519 .pim_object(col.id, &body.name)
520 .await?
521 .ok_or_else(not_found)?;
522 let cal = parse(&old).ok_or_else(not_found)?;
523 let dir = Directory::load(&state).await?;
524 let principal = dir.get(owner).cloned().ok_or_else(not_found)?;
525 let owns = dir.is(owner);
526 if !matches!(itip::role(&cal, &owns), Ok(Role::Attendee)) {
527 return Err(ApiError::new(
528 StatusCode::BAD_REQUEST,
529 "the calendar owner is not an attendee",
530 ));
531 }
532 let zone = floating(body.tz.as_deref());
533 let new = itip::respond(&cal, &owns, answer, rid, &zone)
534 .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "instance not found"))?;
535 let new = render::write(&new);
536 let me = state.db.principal_of(auth.user.id).await?;
537 let w = Writer::new(&principal, me, &auth.user.name, true);
538 let stored = match pim_schedule::put(
539 &state,
540 &dir,
541 &w,
542 (col.id, &obj.name),
543 Some(&old),
544 new.as_bytes(),
545 )
546 .await?
547 {
548 Ok(s) => s,
549 Err(condition) => return Err(ApiError::new(StatusCode::FORBIDDEN, &condition.name)),
550 };
551 state.db.pim_apply(&stored.into_ops(col.id, obj)).await?;
552 Ok(Json(OkResp {}))
553}
554