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 "encoding/json"
5 "io"
6 "net/http"
7 "strconv"
8 "time"
9
10 nativeauth "amadan.net/rastrillo/native/server"
11 "github.com/go-chi/chi/v5"
12
13 // The one import left on rastrillo's pre-move path, on purpose:
14 // rastrillo/native's server (2a5d07b, and its main) still takes a
15 // github.com/carlosframework/rastrillo *sessions.Sessions. Both
16 // sessions packages read and write the same sessions table, so a
17 // session native sign-in mints is an ordinary session to the app
18 // (native_exchange_test.go). Move this to
19 // amadan.net/rastrillo/rastrillo/sessions when native/server moves.
20 presessions "github.com/carlosframework/rastrillo/sessions"
21)
22
23func (a *App) wireNative() error {
24 s, err := presessions.New(presessions.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, SigninPath: "/signin", Logger: a.logger})
25 if err != nil {
26 return err
27 }
28 require := func(next http.Handler) http.Handler {
29 if a.home != nil {
30 return a.home.sessions.Require(a.requirePerson(next))
31 }
32 return a.auth.RequireSession(a.requirePerson(next))
33 }
34 a.native = nativeauth.New(s, a.cfg.Origin, "Calendar", require)
35 return nil
36}
37func nativeJSON(w http.ResponseWriter, value any) {
38 w.Header().Set("Content-Type", "application/json")
39 w.Header().Set("Cache-Control", "no-store")
40 _ = json.NewEncoder(w).Encode(value)
41}
42func (h *handlers) nativeSession(w http.ResponseWriter, r *http.Request) {
43 p, _ := CurrentPerson(r)
44 cals, err := h.store.Calendars(r.Context(), p.ID)
45 if err != nil {
46 http.Error(w, "Cannot load calendars", 500)
47 return
48 }
49 if requestUnknown(r) {
50 h.teamUnavailable(w, r)
51 return
52 }
53 type cal struct {
54 ID int64 `json:"id"`
55 Name string `json:"name"`
56 Hue int `json:"hue"`
57 Writable bool `json:"writable"`
58 }
59 out := make([]cal, 0, len(cals))
60 for _, c := range cals {
61 out = append(out, cal{c.ID, c.Name, c.Hue, CanWrite(c.Role)})
62 }
63 id, err := h.store.DefaultCalendarID(r.Context(), p.ID)
64 if err != nil {
65 http.Error(w, "Cannot load default calendar", 500)
66 return
67 }
68 nativeJSON(w, map[string]any{"zone": p.Zone, "week_start": p.WeekStart, "calendars": out, "default_calendar_id": id})
69}
70
71type nativeEvent struct {
72 ID int64 `json:"id"`
73 CalendarID int64 `json:"calendar_id"`
74 Title string `json:"title"`
75 Location string `json:"location"`
76 Notes string `json:"notes"`
77 AllDay bool `json:"all_day"`
78 StartLocal string `json:"start_local"`
79 EndLocal string `json:"end_local"`
80 TZ string `json:"tz"`
81 Start int64 `json:"start"`
82 End int64 `json:"end"`
83 Recurring bool `json:"recurring"`
84 Writable bool `json:"writable"`
85 CalendarName string `json:"calendar_name"`
86 Occurrence string `json:"occurrence"`
87 DayStart string `json:"day_start"`
88 DayEnd string `json:"day_end"`
89 Status string `json:"status"`
90}
91
92func (h *handlers) nativeEvents(w http.ResponseWriter, r *http.Request) {
93 p, _ := CurrentPerson(r)
94 zone, ok := nativeViewZone(r.URL.Query().Get("zone"), personZone(p))
95 if !ok {
96 http.Error(w, "Choose a valid time zone", 422)
97 return
98 }
99 from, e := ParseDate(r.URL.Query().Get("from"), zone)
100 to, e2 := ParseDate(r.URL.Query().Get("to"), zone)
101 if e != nil || e2 != nil || !to.After(from) || to.After(from.AddDate(0, 0, 62)) {
102 http.Error(w, "Choose a range of at most 62 days", 400)
103 return
104 }
105 events, err := h.store.EventsInRange(r.Context(), p.ID, from.AddDate(0, 0, -2).Unix(), to.AddDate(0, 0, 2).Unix())
106 if err != nil {
107 http.Error(w, "Cannot load events", 500)
108 return
109 }
110 // Team mode: JSON has no room for a partial notice, so a list built
111 // on standing that lapsed while building is a 503, never short
112 // (Paul's ruling, 2026-10-28). The gate already refused Unknown.
113 if requestUnknown(r) {
114 h.teamUnavailable(w, r)
115 return
116 }
117 out := make([]nativeEvent, 0, len(events))
118 for _, ev := range events {
119 // The first editor handles single, non-booked events; series remain intact.
120 _, booked := h.store.BookingSummaryFor(r.Context(), ev.ID)
121 dayStart, dayEnd := "", ""
122 if ev.AllDay {
123 dayStart = ev.StartLocal
124 if ev.RRule != "" && ev.SeriesID == nil && ev.OccurrenceLocal != "" {
125 dayStart = ev.OccurrenceLocal
126 }
127 masterStart, e1 := time.Parse(LayoutDate, ev.StartLocal)
128 masterEnd, e2 := time.Parse(LayoutDate, ev.EndLocal)
129 occurrenceStart, e3 := time.Parse(LayoutDate, dayStart)
130 if e1 != nil || e2 != nil || e3 != nil {
131 http.Error(w, "Cannot load dates", 500)
132 return
133 }
134 dayEnd = occurrenceStart.Add(masterEnd.Sub(masterStart)).Format(LayoutDate)
135 if dayEnd <= r.URL.Query().Get("from") || dayStart >= r.URL.Query().Get("to") {
136 continue
137 }
138 } else if ev.OccEndUTC <= from.Unix() || ev.OccStartUTC >= to.Unix() {
139 continue
140 }
141 recurring := ev.RRule != "" || ev.SeriesID != nil
142 out = append(out, nativeEvent{ev.ID, ev.CalendarID, ev.Title, ev.Location, ev.Notes, ev.AllDay, ev.StartLocal, ev.EndLocal, ev.TZ, ev.OccStartUTC, ev.OccEndUTC, recurring, ev.Writable() && !recurring && !booked, ev.CalendarName, ev.OccurrenceLocal, dayStart, dayEnd, ev.Status})
143 }
144 nativeJSON(w, map[string]any{"events": out})
145}
146func (h *handlers) nativeSave(w http.ResponseWriter, r *http.Request) {
147 p, _ := CurrentPerson(r)
148 r.Body = http.MaxBytesReader(w, r.Body, 128<<10)
149 var in nativeEvent
150 d := json.NewDecoder(r.Body)
151 d.DisallowUnknownFields()
152 if err := d.Decode(&in); err != nil || d.Decode(new(any)) != io.EOF {
153 http.Error(w, "Invalid event", 400)
154 return
155 }
156 id := int64(0)
157 if raw := chi.URLParam(r, "id"); raw != "" {
158 var err error
159 id, err = strconv.ParseInt(raw, 10, 64)
160 if err != nil || id <= 0 {
161 http.NotFound(w, r)
162 return
163 }
164 }
165 value := EventInput{CalendarID: in.CalendarID, Title: in.Title, Location: in.Location, Notes: in.Notes, AllDay: in.AllDay, StartLocal: in.StartLocal, EndLocal: in.EndLocal, TZ: in.TZ, Kind: KindMeeting, Status: StatusConfirmed}
166 if value.TZ == "" {
167 value.TZ = p.Zone
168 }
169 if id != 0 {
170 ev, err := h.store.Event(r.Context(), p.ID, id)
171 if err != nil {
172 h.nativeNotFound(w, r)
173 return
174 }
175 _, booked := h.store.BookingSummaryFor(r.Context(), id)
176 if ev.RRule != "" || ev.SeriesID != nil || booked {
177 http.Error(w, "Edit this series or booking in the web calendar", 409)
178 return
179 }
180 value.CalendarID = ev.CalendarID
181 value.Kind = ev.Kind
182 value.Status = ev.Status
183 if err = h.store.UpdateEvent(r.Context(), p.ID, id, value); err != nil {
184 h.nativeEventError(w, r, err)
185 return
186 }
187 } else {
188 ev, err := h.store.CreateEvent(r.Context(), p.ID, value)
189 if err != nil {
190 h.nativeEventError(w, r, err)
191 return
192 }
193 id = ev.ID
194 if err := h.store.EnsureDefaultReminder(r.Context(), p, ev); err != nil {
195 nativeJSON(w, map[string]any{"id": id, "warning": "Event saved, but its reminder could not be scheduled."})
196 return
197 }
198 }
199 nativeJSON(w, map[string]any{"id": id, "saved_at": time.Now().Unix()})
200}
201func (h *handlers) nativeEventError(w http.ResponseWriter, r *http.Request, err error) {
202 if standingRefusal(err) {
203 h.guardRefused(w, r, err)
204 return
205 }
206 if NotFound(err) {
207 h.nativeNotFound(w, r)
208 return
209 }
210 if err == ErrReadOnly {
211 http.Error(w, "This calendar is read-only", 403)
212 return
213 }
214 if v, ok := Invalid(err); ok {
215 http.Error(w, v.Message, 422)
216 return
217 }
218 http.Error(w, "Cannot save event", 500)
219}
220
221// nativeNotFound is the native API's 404, or in team mode, when the
222// request's standing lapsed between the gate and the read, the retryable
223// 503 it really is (team_answers.go).
224func (h *handlers) nativeNotFound(w http.ResponseWriter, r *http.Request) {
225 if requestUnknown(r) {
226 h.teamUnavailable(w, r)
227 return
228 }
229 http.NotFound(w, r)
230}
231