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 "errors"
7 "math"
8 "strconv"
9 "time"
10
11 access "amadan.net/oficina/agent-access.git"
12 "github.com/google/uuid"
13 "gorm.io/gorm"
14)
15
16type agentEventUpdateInput struct {
17 Team string `json:"team"`
18 ID int64 `json:"id"`
19 ClientID string `json:"client_id"`
20 ExpectedRevision int `json:"expected_revision"`
21 Changes map[string]json.RawMessage `json:"changes"`
22}
23
24func (a *App) agentUpdateEvent(ctx context.Context, p access.Principal, person Person, raw json.RawMessage) (any, error) {
25 var in agentEventUpdateInput
26 if json.Unmarshal(raw, &in) != nil {
27 return nil, access.Fail("invalid", "Invalid event update.")
28 }
29 uid, err := uuid.Parse(in.ClientID)
30 if err != nil || uid == uuid.Nil || uid.String() != in.ClientID || in.ID <= 0 || in.ExpectedRevision < 0 || len(in.Changes) == 0 {
31 return nil, access.Fail("invalid", "Supply event ID, revision, changes and canonical UUID client_id.")
32 }
33 var attendees []string
34 if value, ok := in.Changes["attendees"]; ok {
35 var list []string
36 if string(value) == "null" || json.Unmarshal(value, &list) != nil {
37 return nil, access.Fail("invalid", "Supply attendees as a list of email addresses.")
38 }
39 if attendees, err = agentAttendees(list); err != nil {
40 return nil, err
41 }
42 }
43 coordinate, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, p.Subject, p.Client, in.Team, "calendar_update_event", in.ClientID})
44 key, err := a.store.seal.Fingerprint("agent.event.update.coordinate.v1", string(coordinate))
45 if err != nil {
46 return nil, err
47 }
48 payload, _ := json.Marshal(in)
49 print, err := a.store.seal.Fingerprint("agent.event.update.content.v1", string(payload))
50 if err != nil {
51 return nil, err
52 }
53 revision := 0
54 var calendarID int64
55 err = a.store.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
56 if err := a.bindAgent(tx); err != nil {
57 return err
58 }
59 // bindAgent takes the SQLite writer reservation before any precondition.
60 current := a.agentStore(tx)
61 event, err := current.Event(ctx, person.ID, in.ID)
62 if err != nil {
63 return err
64 }
65 calendarID = event.CalendarID
66 if _, err := a.checkAgentWriter(ctx, tx, p, person, calendarID); err != nil {
67 return err
68 }
69 return current.guard(ctx, func() error {
70 var saved struct {
71 Content string
72 EventID, CalendarID int64
73 Revision int
74 }
75 result := tx.Table("calendar_agent_updates").Where("coordinate=?", key).Take(&saved)
76 if result.Error == nil {
77 if saved.Content != print {
78 return access.Fail("conflict", "This client_id was used with different event fields.")
79 }
80 if saved.EventID != in.ID || saved.CalendarID != calendarID || saved.Revision < 1 {
81 return access.Fail("unavailable", "Event receipt requires repair.")
82 }
83 revision = saved.Revision
84 _, err := a.checkAgentWriter(ctx, tx, p, person, calendarID)
85 return err
86 }
87 if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
88 return result.Error
89 }
90 if event.Sequence == math.MaxInt {
91 return access.Fail("conflict", "The event revision is exhausted.")
92 }
93 if event.Sequence != in.ExpectedRevision {
94 return access.Fail("conflict", "This event has changed. Read it before updating.")
95 }
96 if event.RRule != "" || event.SeriesID != nil || event.RecurrenceIDLocal != "" || event.Exdates != "" || event.RRuleForeign || event.Status == StatusCancelled {
97 return access.Fail("invalid", "Only noncancelled single events can be updated here; recurring events require Calendar.")
98 }
99 next, err := agentEventPatch(event, in.Changes)
100 if err != nil {
101 return err
102 }
103 if attendees != nil {
104 // A booked event's attendee is its booker, recorded by the
105 // booking flow; replacing it would lose who booked.
106 if _, booked, err := bookingFor(tx, event.ID); err != nil {
107 return err
108 } else if booked {
109 return access.Fail("invalid", "A booked event's attendees belong to its booking and cannot be changed here.")
110 }
111 }
112 if err := current.updateEventOn(tx, event.Event, next, time.Now().UTC()); err != nil {
113 return err
114 }
115 if attendees != nil {
116 if err := current.setAttendeesOn(tx, event.ID, attendees); err != nil {
117 return err
118 }
119 }
120 revision = event.Sequence + 1
121 if err := tx.Exec("INSERT INTO calendar_agent_updates(coordinate,content,event_id,calendar_id,revision) VALUES(?,?,?,?,?)", key, print, in.ID, calendarID, revision).Error; err != nil {
122 return err
123 }
124 _, err = a.checkAgentWriter(ctx, tx, p, person, calendarID)
125 return err
126 })
127 })
128 if err != nil {
129 return nil, err
130 }
131 captureAgentEvent(ctx, in.ID, calendarID)
132 return map[string]any{"id": in.ID, "revision": revision, "url": a.cfg.Origin + "/events/" + strconv.FormatInt(in.ID, 10), "invitations_sent": false}, nil
133}
134
135func agentEventPatch(e EventView, changes map[string]json.RawMessage) (EventInput, error) {
136 in := EventInput{CalendarID: e.CalendarID, Title: e.Title, Location: e.Location, Notes: e.Notes, AllDay: e.AllDay, StartLocal: e.StartLocal, EndLocal: e.EndLocal, TZ: e.TZ, Kind: e.Kind, Status: e.Status, RRule: e.RRule, Exdates: e.Exdates}
137 for field, value := range changes {
138 var target any
139 switch field {
140 case "title":
141 target = &in.Title
142 case "location":
143 target = &in.Location
144 case "notes":
145 target = &in.Notes
146 case "all_day":
147 target = &in.AllDay
148 case "start_local":
149 target = &in.StartLocal
150 case "end_local":
151 target = &in.EndLocal
152 case "tz":
153 target = &in.TZ
154 case "kind":
155 target = &in.Kind
156 case "attendees":
157 // Validated and applied by agentUpdateEvent: not an event column.
158 continue
159 default:
160 return in, access.Fail("invalid", "Unsupported event field.")
161 }
162 if string(value) == "null" || json.Unmarshal(value, target) != nil {
163 return in, access.Fail("invalid", "Invalid event field.")
164 }
165 }
166 // ValidateEventInput clears all-day zones. Refuse an explicit or retained
167 // timed zone before that normalizer can silently discard it.
168 if in.AllDay && in.TZ != "" {
169 return in, access.Fail("invalid", "An all-day event uses dates without a time zone.")
170 }
171 if err := ValidateEventInput(&in); err != nil {
172 return in, err
173 }
174 if in.AllDay && in.TZ != "" || !in.AllDay && (in.TZ == "Local" || !agentUnambiguous(in.StartLocal, in.TZ) || !agentUnambiguous(in.EndLocal, in.TZ)) {
175 return in, access.Fail("invalid", "Supply unambiguous local times and an explicit IANA zone, or all-day dates without a zone.")
176 }
177 // The full-form validator trims text. A patch preserves omitted fields,
178 // including imported whitespace, while supplied fields use domain normalization.
179 if _, ok := changes["title"]; !ok {
180 in.Title = e.Title
181 }
182 if _, ok := changes["location"]; !ok {
183 in.Location = e.Location
184 }
185 if _, ok := changes["notes"]; !ok {
186 in.Notes = e.Notes
187 }
188 return in, nil
189}
190
191func (a *App) agentUpdateOperation(team string) access.Operation {
192 changes := agentObject(map[string]any{"title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen), "notes": agentString(MaxNotesLen), "all_day": map[string]any{"type": "boolean"}, "start_local": agentString(16), "end_local": agentString(16), "tz": agentString(128), "kind": map[string]any{"enum": []string{KindMeeting, KindCommitment, KindNote}}, "attendees": agentAttendeesSchema()})
193 return access.Operation{Name: "calendar_update_event", Description: "Patch a noncancelled single event using expected_revision from calendar_get_event.sequence. Omitted fields are preserved. changes.attendees, when given, replaces the whole list of attendee email addresses ([] clears it); a booked event's attendees cannot be changed. Attendees are recorded on the event, never invited: Calendar emails nobody. Recurrence, cancellation and reminder changes are unsupported. Booked scheduling remains controlled by booking. No invitations are sent. Returned revision is the original committed sequence, including on an identical retry.", Scope: "calendar:write", Idempotent: true,
194 Input: agentInput(map[string]any{"id": agentID(), "client_id": map[string]any{"type": "string", "minLength": 36, "maxLength": 36}, "expected_revision": map[string]any{"type": "integer", "minimum": 0}, "changes": changes}, "id", "client_id", "expected_revision", "changes"),
195 Output: agentObject(map[string]any{"id": agentID(), "revision": map[string]any{"type": "integer", "minimum": 1}, "url": agentString(2048), "invitations_sent": map[string]any{"const": false}}, "id", "revision", "url", "invitations_sent"), Invoke: a.agentGuard(team, "calendar:write", a.agentUpdateEvent)}
196}
197