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 "fmt"
5 "net/http"
6 "strconv"
7 "time"
8
9 "github.com/go-chi/chi/v5"
10)
11
12// calendars lists what the viewer can see.
13func (h *handlers) calendars(w http.ResponseWriter, r *http.Request) {
14 p, _ := CurrentPerson(r)
15 cals, err := h.store.Calendars(r.Context(), p.ID)
16 if err != nil {
17 h.fail(w, r, "list calendars", err)
18 return
19 }
20 render(w, "calendars", h.page(r, "Calendars", map[string]any{"Calendars": cals}))
21}
22
23// share shows a calendar's subscription feeds, and what they cost.
24func (h *handlers) share(w http.ResponseWriter, r *http.Request) {
25 p, cal, ok := h.calendarParam(w, r)
26 if !ok {
27 return
28 }
29 feeds, err := h.store.FeedsFor(r.Context(), p.ID, cal.ID)
30 if err != nil {
31 h.fail(w, r, "list feeds", err)
32 return
33 }
34 // The database hands every time back in UTC (rastrillo's
35 // _timezone=UTC); the page prints them in the viewer's own zone, as
36 // every other surface does.
37 if loc, err := Zone(personZone(p)); err == nil {
38 for i := range feeds {
39 feeds[i].CreatedAt = feeds[i].CreatedAt.In(loc)
40 if at := feeds[i].LastPolledAt; at != nil {
41 local := at.In(loc)
42 feeds[i].LastPolledAt = &local
43 }
44 }
45 }
46 render(w, "share", h.page(r, "Share "+cal.Name, map[string]any{
47 "Calendar": cal,
48 "Feeds": feeds,
49 "Origin": h.origin,
50 "NewToken": r.URL.Query().Get("token"),
51 }))
52}
53
54// mintFeed creates a subscription URL and shows it once.
55func (h *handlers) mintFeed(w http.ResponseWriter, r *http.Request) {
56 p, cal, ok := h.calendarParam(w, r)
57 if !ok {
58 return
59 }
60 token, err := h.store.MintFeed(r.Context(), p.ID, cal.ID)
61 if err != nil {
62 h.fail(w, r, "mint feed", err)
63 return
64 }
65 // The token rides back in the query because this is the only moment
66 // it can ever be shown: only its hash is stored.
67 http.Redirect(w, r,
68 fmt.Sprintf("/calendars/%d/share?token=%s", cal.ID, token),
69 http.StatusSeeOther)
70}
71
72func (h *handlers) revokeFeed(w http.ResponseWriter, r *http.Request) {
73 p, cal, ok := h.calendarParam(w, r)
74 if !ok {
75 return
76 }
77 _ = r.ParseForm()
78 feedID, _ := strconv.ParseInt(r.FormValue("feed_id"), 10, 64)
79 if err := h.store.RevokeFeed(r.Context(), p.ID, feedID); err != nil && !NotFound(err) {
80 h.fail(w, r, "revoke feed", err)
81 return
82 }
83 http.Redirect(w, r, fmt.Sprintf("/calendars/%d/share", cal.ID), http.StatusSeeOther)
84}
85
86// feed serves a subscription. No session: the token IS the
87// authorisation, because Google and Apple will not sign in.
88func (h *handlers) feed(w http.ResponseWriter, r *http.Request) {
89 token := chi.URLParam(r, "token")
90 f, err := h.store.FeedByToken(r.Context(), token)
91 if err != nil {
92 // A bad token is a 404, never a 403: a distinguishable refusal
93 // would let somebody test tokens for existence.
94 http.NotFound(w, r)
95 return
96 }
97 // Team mode: a feed reads on its minter's standing (team_feed.go).
98 ctx, ok := h.feedStanding(w, r, f)
99 if !ok {
100 return
101 }
102 cal, err := h.store.Calendar(ctx, f.PersonID, f.CalendarID)
103 if err != nil {
104 h.feedNotFound(w, r, ctx)
105 return
106 }
107 from, to := feedWindow()
108 events, err := h.store.EventsForFeed(ctx, f.PersonID, f.CalendarID, from, to)
109 if err != nil && standingLapsed(ctx) {
110 // Team mode: the minter's lease ran out between the two reads.
111 teamUnavailablePlain(w)
112 return
113 }
114 if err != nil {
115 h.logger.Error("calendar: feed events", "err", err)
116 http.Error(w, "unavailable", http.StatusInternalServerError)
117 return
118 }
119 // Attendees are carried in the export and nowhere else in a view,
120 // so they are loaded here rather than by the query.
121 if err := h.store.AttachAttendees(r.Context(), events); err != nil {
122 h.logger.Error("calendar: feed attendees", "stage", "feed.attendees",
123 "err", scrubErr(err))
124 }
125 if standingLapsed(ctx) {
126 // The minter's lease ran out while this was built: never a short
127 // calendar to a reader that cannot see why (team_feed.go).
128 teamUnavailablePlain(w)
129 return
130 }
131 body := WriteICS(cal.Name, events, r.URL.Query().Get("alarms") == "1")
132
133 // An ETag so a subscriber that polls every fifteen minutes usually
134 // gets a 304. On a platform billed by residency, a 304 is the
135 // difference between a feed that costs a little and one that costs
136 // a lot.
137 etag := etagFor(body)
138 w.Header().Set("ETag", etag)
139 w.Header().Set("Cache-Control", "private, max-age=300")
140 if match := r.Header.Get("If-None-Match"); match == etag {
141 w.WriteHeader(http.StatusNotModified)
142 return
143 }
144 w.Header().Set("Content-Type", "text/calendar; charset=utf-8")
145 _, _ = w.Write([]byte(body))
146}
147
148// feedWindow is how much of a calendar a subscription carries: a year
149// back and two forward. Unbounded would mean re-sending a decade of
150// history every poll.
151func feedWindow() (int64, int64) {
152 now := time.Now()
153 return now.AddDate(-1, 0, 0).Unix(), now.AddDate(2, 0, 0).Unix()
154}
155
156// exportCalendar downloads one calendar as a file.
157func (h *handlers) exportCalendar(w http.ResponseWriter, r *http.Request) {
158 p, cal, ok := h.calendarParam(w, r)
159 if !ok {
160 return
161 }
162 from, to := feedWindow()
163 events, err := h.store.EventsForFeed(r.Context(), p.ID, cal.ID, from, to)
164 if err != nil {
165 h.fail(w, r, "export calendar", err)
166 return
167 }
168 if err := h.store.AttachAttendees(r.Context(), events); err != nil {
169 h.fail(w, r, "export attendees", err)
170 return
171 }
172 if requestUnknown(r) {
173 // Team mode: a download is the whole calendar or a retry, never
174 // one some of whose events a lapse withheld.
175 h.teamUnavailable(w, r)
176 return
177 }
178 w.Header().Set("Content-Type", "text/calendar; charset=utf-8")
179 w.Header().Set("Content-Disposition",
180 fmt.Sprintf("attachment; filename=%q", safeFilename(cal.Name)+".ics"))
181 _, _ = w.Write([]byte(WriteICS(cal.Name, events, true)))
182}
183
184func (h *handlers) importForm(w http.ResponseWriter, r *http.Request) {
185 p, _ := CurrentPerson(r)
186 cals, err := h.store.Calendars(r.Context(), p.ID)
187 if err != nil {
188 h.fail(w, r, "list calendars", err)
189 return
190 }
191 render(w, "import", h.page(r, "Import", map[string]any{
192 "Calendars": writable(cals),
193 }))
194}
195
196// importICS reads an uploaded file synchronously.
197//
198// Synchronous, not a background job: a job needs a status page, a
199// polling shim and a story for what happens when the instance
200// hibernates mid-import. A file small enough to upload is small enough
201// to parse in the request, and the deferred work has a written trigger
202// — an import that exceeds the request timeout.
203func (h *handlers) importICS(w http.ResponseWriter, r *http.Request) {
204 p, _ := CurrentPerson(r)
205 if err := r.ParseMultipartForm(MaxImportBytes); err != nil {
206 h.importFailed(w, r, "That file could not be read.")
207 return
208 }
209 calID, _ := strconv.ParseInt(r.FormValue("calendar_id"), 10, 64)
210 if _, err := h.store.Calendar(r.Context(), p.ID, calID); err != nil {
211 h.errorPage(w, r, http.StatusNotFound, "")
212 return
213 }
214 file, _, err := r.FormFile("file")
215 if err != nil {
216 h.importFailed(w, r, "Choose a .ics file to import.")
217 return
218 }
219 defer file.Close()
220
221 inputs, res, err := ParseICS(file, p.Zone)
222 if err != nil {
223 h.importFailed(w, r, "That file could not be read.")
224 return
225 }
226 for _, in := range inputs {
227 in.CalendarID = calID
228 if _, err := h.store.CreateEvent(r.Context(), p.ID, in); err != nil {
229 // Team mode: standing that lapsed mid-file stops the import
230 // with a retry, never a count of "skipped" events that were
231 // refused for who was importing them (team_guard.go).
232 if h.importRefused(w, r, err, res) {
233 return
234 }
235 // One unusable event does not fail the file. It is counted
236 // and the page says how many.
237 res.Skipped++
238 continue
239 }
240 res.Created++
241 }
242 render(w, "import_done", h.page(r, "Imported", map[string]any{"Result": res}))
243}
244
245func (h *handlers) importFailed(w http.ResponseWriter, r *http.Request, msg string) {
246 p, _ := CurrentPerson(r)
247 cals, _ := h.store.Calendars(r.Context(), p.ID)
248 w.WriteHeader(http.StatusUnprocessableEntity)
249 render(w, "import", h.page(r, "Import", map[string]any{
250 "Calendars": writable(cals),
251 "Error": msg,
252 }))
253}
254
255// calendarParam resolves {id}, answering 404 for anything the viewer
256// may not see.
257func (h *handlers) calendarParam(w http.ResponseWriter, r *http.Request) (Person, CalendarView, bool) {
258 p, _ := CurrentPerson(r)
259 id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
260 if err != nil {
261 h.errorPage(w, r, http.StatusNotFound, "")
262 return p, CalendarView{}, false
263 }
264 cal, err := h.store.Calendar(r.Context(), p.ID, id)
265 if NotFound(err) {
266 h.errorPage(w, r, http.StatusNotFound, "")
267 return p, CalendarView{}, false
268 }
269 if err != nil {
270 h.fail(w, r, "read calendar", err)
271 return p, CalendarView{}, false
272 }
273 return p, cal, true
274}
275