oficina / calendar Public

Clone
git clone https://amadan.net/oficina/calendar

Plain git — no account needed to clone.

Download

Download this file

1package calendar
2
3import (
4 "context"
5 "encoding/json"
6 "strconv"
7 "strings"
8 "time"
9
10 access "amadan.net/oficina/agent-access.git"
11)
12
13// agentListPage bounds one calendar_list_events response by count and
14// agentListBytes by its serialized size, which keeps a page inside the
15// tool frame: two hundred events with valid 200-byte titles and
16// locations are already far past it. A month of a busy team is more than
17// one page; the cursor carries the rest.
18const (
19 agentListPage = 200
20 agentListBytes = 48 * 1024
21)
22
23func (a *App) agentListEventsOperation(team string) access.Operation {
24 listed := agentObject(agentAttendeesOutput(map[string]any{
25 "id": agentID(), "calendar_id": agentID(), "calendar": agentString(2048), "title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen),
26 "all_day": map[string]any{"type": "boolean"}, "start": agentString(35), "end": agentString(35), "tz": agentString(128),
27 "status": agentString(32), "kind": agentString(32), "recurring": map[string]any{"type": "boolean"}, "url": agentString(2048),
28 }), "id", "calendar_id", "calendar", "title", "location", "all_day", "start", "end", "tz", "status", "kind", "recurring", "attendees", "url")
29 return access.Operation{Name: "calendar_list_events", Description: "List the events the person can currently see that overlap a half-open RFC3339 range [from, to) with explicit offsets, at most 31 days, in start order. Timed events give RFC3339 start/end in the event's own zone; all-day events give YYYY-MM-DD dates with an exclusive end, matched against the person's own days. Each occurrence of a recurring event is listed separately under the series id. Optional calendar_id narrows to one visible calendar; optional query matches title or location, case-insensitively. At most limit (default and maximum 200) events per call, fewer when they are large; pass next back as cursor, with the same other arguments, for the rest. Attendees are addresses recorded on the event; Calendar has never emailed them. At most 50 are listed per event, with attendees_more counting the rest; long titles, locations and calendar names are shortened.", Scope: "calendar:read", ReadOnly: true, Idempotent: true,
30 Input: agentInput(map[string]any{"from": agentString(35), "to": agentString(35), "calendar_id": agentID(), "query": agentString(200),
31 "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": agentListPage}, "cursor": agentString(12)}, "from", "to"),
32 Output: agentObject(map[string]any{"events": map[string]any{"type": "array", "maxItems": agentListPage, "items": listed}, "next": agentString(12)}, "events"),
33 Invoke: a.agentGuard(team, "calendar:read", a.agentListEvents)}
34}
35
36func (a *App) agentListEvents(ctx context.Context, _ access.Principal, p Person, raw json.RawMessage) (any, error) {
37 var in struct {
38 From string `json:"from"`
39 To string `json:"to"`
40 CalendarID int64 `json:"calendar_id"`
41 Query string `json:"query"`
42 Limit int `json:"limit"`
43 Cursor string `json:"cursor"`
44 }
45 if json.Unmarshal(raw, &in) != nil {
46 return nil, access.Fail("invalid", "Invalid event range.")
47 }
48 from, e1 := time.Parse(time.RFC3339, in.From)
49 to, e2 := time.Parse(time.RFC3339, in.To)
50 if e1 != nil || e2 != nil || !from.Before(to) || to.Sub(from) > 31*24*time.Hour {
51 return nil, access.Fail("invalid", "Supply a positive RFC3339 time range of at most 31 days, with explicit offsets.")
52 }
53 offset := 0
54 if in.Cursor != "" {
55 n, err := strconv.Atoi(in.Cursor)
56 if err != nil || n < 0 || strconv.Itoa(n) != in.Cursor {
57 return nil, access.Fail("invalid", "Pass back the next value from the previous page as cursor.")
58 }
59 offset = n
60 }
61 limit := agentListPage
62 if in.Limit != 0 {
63 limit = in.Limit
64 }
65 if in.CalendarID != 0 {
66 c, err := a.store.Calendar(ctx, p.ID, in.CalendarID)
67 if err != nil {
68 return nil, err
69 }
70 if c.ArchivedAt != nil {
71 return nil, ErrNotFound
72 }
73 captureAgentCalendar(ctx, c.ID)
74 }
75 personLoc, err := Zone(p.Zone)
76 if err != nil {
77 personLoc = time.UTC
78 }
79 // The tolerant reader the views use, widened by a day each way so an
80 // all-day event indexed at midnight in its own zone is found and then
81 // judged by the person's own days below.
82 events, err := a.store.EventsInRange(ctx, p.ID, from.Unix()-86400, to.Unix()+86400)
83 if err != nil {
84 return nil, err
85 }
86 // The last civil day is the one holding the last instant before `to`:
87 // the day `to` falls in, unless `to` is exactly that day's start.
88 // Compared at full precision, so 00:00:00.5 still reaches into the day.
89 end := to.In(personLoc)
90 lowDay, highDay := civilDate(from.In(personLoc)), civilDate(end)
91 if to.Equal(time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, personLoc)) {
92 highDay = highDay.AddDate(0, 0, -1)
93 }
94 query := strings.ToLower(strings.TrimSpace(in.Query))
95 matched := []EventView{}
96 for _, e := range events {
97 if in.CalendarID != 0 && e.CalendarID != in.CalendarID {
98 continue
99 }
100 if e.AllDay {
101 first, last := allDayDates(e)
102 if last.Before(lowDay) || first.After(highDay) {
103 continue
104 }
105 } else if !time.Unix(e.OccEndUTC, 0).After(from) || !time.Unix(e.OccStartUTC, 0).Before(to) {
106 continue
107 }
108 if query != "" && !strings.Contains(strings.ToLower(e.Title), query) && !strings.Contains(strings.ToLower(e.Location), query) {
109 continue
110 }
111 matched = append(matched, e)
112 }
113 page := []EventView{}
114 if offset < len(matched) {
115 page = matched[offset:min(len(matched), offset+limit)]
116 }
117 if err := a.store.AttachAttendees(ctx, page); err != nil {
118 return nil, err
119 }
120 out := []json.RawMessage{}
121 size := len(`{"events":[],"next":"000000000000"}`)
122 for _, e := range page {
123 start, end, tz := "", "", e.TZ
124 if e.AllDay {
125 first, last := allDayDates(e)
126 start, end = first.Format(LayoutDate), last.AddDate(0, 0, 1).Format(LayoutDate)
127 } else {
128 loc, err := Zone(e.TZ)
129 if err != nil {
130 loc, tz = time.UTC, "UTC"
131 }
132 start, end = time.Unix(e.OccStartUTC, 0).In(loc).Format(time.RFC3339), time.Unix(e.OccEndUTC, 0).In(loc).Format(time.RFC3339)
133 }
134 row, err := json.Marshal(agentAttendeeFields(map[string]any{"id": occurrenceOwner(e), "calendar_id": e.CalendarID, "calendar": agentClip(e.CalendarName, MaxTitleLen),
135 "title": agentClip(e.Title, MaxTitleLen), "location": agentClip(e.Location, MaxLocationLen), "all_day": e.AllDay, "start": start, "end": end,
136 "tz": agentClip(tz, 128), "status": e.Status, "kind": e.Kind, "recurring": e.OccurrenceLocal != "", "url": a.cfg.Origin + eventHref(e)}, e.Attendees))
137 if err != nil {
138 return nil, err
139 }
140 // Every field above is bounded, so one event is far below the
141 // budget; the check still holds for the first, never exempting it.
142 if size+len(row)+1 > agentListBytes {
143 if len(out) == 0 {
144 return nil, access.Fail("too_large", "This event is too large to list.")
145 }
146 break
147 }
148 size += len(row) + 1
149 out = append(out, row)
150 captureAgentCalendar(ctx, e.CalendarID)
151 }
152 result := map[string]any{"events": out}
153 if offset+len(out) < len(matched) {
154 result["next"] = strconv.Itoa(offset + len(out))
155 }
156 return result, nil
157}
158
159func civilDate(t time.Time) time.Time {
160 return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
161}
162
163// allDayDates recovers an all-day occurrence's first and last civil dates
164// (inclusive) from its index, which is midnight in the event's own zone —
165// UTC for every all-day event the form makes. As in allDayBusy.
166func allDayDates(e EventView) (time.Time, time.Time) {
167 loc, err := Zone(e.TZ)
168 if err != nil {
169 loc = time.UTC
170 }
171 first := civilDate(time.Unix(e.OccStartUTC, 0).In(loc))
172 last := civilDate(time.Unix(e.OccEndUTC-1, 0).In(loc))
173 if last.Before(first) {
174 last = first
175 }
176 return first, last
177}
178