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 "crypto/rand"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "time"
11
12 "gorm.io/gorm"
13)
14
15// FeedView is a feed with its poll counts, for the share page.
16type FeedView struct {
17 Feed
18 CalendarName string
19}
20
21// MintFeed creates a subscription capability and returns the token —
22// once.
23//
24// Only the hash is stored. A plaintext token in this table would be a
25// live, unauthenticated read capability for somebody's whole calendar,
26// sitting in a file the platform replicates to object storage — which
27// is exactly what the one rule exists to prevent.
28//
29// The consequence is that the URL cannot be shown again. The share page
30// says so at the moment of minting, rather than letting somebody
31// discover it by coming back for it.
32func (s *Store) MintFeed(ctx context.Context, personID, calendarID int64) (string, error) {
33 if _, err := s.Calendar(ctx, personID, calendarID); err != nil {
34 return "", err
35 }
36 raw := make([]byte, 32)
37 if _, err := rand.Read(raw); err != nil {
38 return "", fmt.Errorf("calendar: no randomness for a feed token: %w", err)
39 }
40 token := hex.EncodeToString(raw)
41
42 f := Feed{
43 PersonID: personID,
44 CalendarID: calendarID,
45 TokenHash: HashFeedToken(token),
46 CreatedAt: time.Now().UTC(),
47 }
48 if err := s.guarded(ctx, func(db *gorm.DB) error { return db.Create(&f).Error }); err != nil {
49 return "", fmt.Errorf("calendar: mint feed: %w", err)
50 }
51 return token, nil
52}
53
54// HashFeedToken is the stored form. SHA-256 with no salt, deliberately:
55// the token is 32 bytes of entropy, so there is no dictionary to
56// defend against, and an unsalted hash is what lets a lookup be a
57// single indexed read rather than a scan of every row.
58func HashFeedToken(token string) string {
59 sum := sha256.Sum256([]byte(token))
60 return hex.EncodeToString(sum[:])
61}
62
63// FeedByToken resolves a subscription URL, and records the poll.
64//
65// The poll count is the honest part. A feed is not free: every poll
66// wakes a hibernating instance, and Apple Calendar polls roughly every
67// fifteen minutes forever. Recording it means the share page can show
68// what a feed actually costs rather than implying it is free.
69func (s *Store) FeedByToken(ctx context.Context, token string) (Feed, error) {
70 var f Feed
71 err := s.g.WithContext(ctx).
72 Where("token_hash = ? AND revoked_at IS NULL", HashFeedToken(token)).
73 First(&f).Error
74 if errors.Is(err, gorm.ErrRecordNotFound) {
75 return Feed{}, ErrNotFound
76 }
77 if err != nil {
78 return Feed{}, fmt.Errorf("calendar: read feed: %w", err)
79 }
80 now := time.Now().UTC()
81 // Best effort: a failed counter update must not fail the response.
82 // Somebody's calendar not loading is a real problem; a poll count
83 // being one short is not.
84 _ = s.g.WithContext(ctx).Model(&Feed{}).Where("id = ?", f.ID).
85 Updates(map[string]any{
86 "last_polled_at": now,
87 "poll_count": gorm.Expr("poll_count + 1"),
88 }).Error
89 return f, nil
90}
91
92// FeedsFor lists a person's own feeds on a calendar.
93func (s *Store) FeedsFor(ctx context.Context, personID, calendarID int64) ([]Feed, error) {
94 var out []Feed
95 err := s.g.WithContext(ctx).
96 Where("person_id = ? AND calendar_id = ? AND revoked_at IS NULL", personID, calendarID).
97 Order("created_at DESC").
98 Find(&out).Error
99 if err != nil {
100 return nil, fmt.Errorf("calendar: list feeds: %w", err)
101 }
102 return out, nil
103}
104
105// RevokeFeed turns a subscription URL off.
106//
107// Revoked rather than deleted, so the share page can keep showing that
108// it existed and how much it was polled — and so a URL that is still
109// pasted into somebody's phone stops working rather than silently
110// matching a later feed that happened to reuse the row.
111func (s *Store) RevokeFeed(ctx context.Context, personID, feedID int64) error {
112 now := time.Now().UTC()
113 return s.guarded(ctx, func(db *gorm.DB) error {
114 res := db.Model(&Feed{}).
115 Where("id = ? AND person_id = ?", feedID, personID).
116 Update("revoked_at", now)
117 if res.Error != nil {
118 return fmt.Errorf("calendar: revoke feed: %w", res.Error)
119 }
120 if res.RowsAffected == 0 {
121 return ErrNotFound
122 }
123 return nil
124 })
125}
126
127// EventsForFeed reads a calendar's events for export, opening the UID
128// and attaching the feed owner's own reminder offsets.
129func (s *Store) EventsForFeed(ctx context.Context, personID, calendarID, from, to int64) ([]EventView, error) {
130 all, err := s.feedEventRows(ctx, personID, calendarID, from, to)
131 if err != nil {
132 return nil, err
133 }
134 offsets, err := s.reminderOffsets(ctx, personID)
135 if err != nil {
136 return nil, err
137 }
138 out := make([]EventView, 0, len(all))
139 for _, e := range all {
140 if e.CalendarID != calendarID {
141 continue
142 }
143 uid, err := s.openUID(e.Event)
144 if err != nil {
145 return nil, err
146 }
147 e.UIDSealedOpen = uid
148 e.ReminderOffsetMin = offsets[e.ID]
149 out = append(out, e)
150 }
151 return out, nil
152}
153
154func (s *Store) openUID(e Event) (string, error) {
155 uid, err := s.seal.OpenString("event.uid", e.UIDSealed)
156 if err != nil {
157 return "", fmt.Errorf("calendar: open uid (event %d): %w", e.ID, err)
158 }
159 return uid, nil
160}
161
162// reminderOffsets maps event id to the person's largest warning on it,
163// for the alarms a feed can carry.
164func (s *Store) reminderOffsets(ctx context.Context, personID int64) (map[int64]int, error) {
165 var rows []Reminder
166 if err := s.g.WithContext(ctx).
167 Where("person_id = ?", personID).Find(&rows).Error; err != nil {
168 return nil, fmt.Errorf("calendar: read reminder offsets: %w", err)
169 }
170 out := map[int64]int{}
171 for _, r := range rows {
172 if r.OffsetMin > out[r.EventID] {
173 out[r.EventID] = r.OffsetMin
174 }
175 }
176 return out, nil
177}
178
179// SaveSettings updates a person's own display preferences. channel is
180// the reminder channel their new rules take; "" or one that does not
181// exist leaves it as it was (a Home-only member's form has none: theirs
182// is in-app whatever is stored).
183func (s *Store) SaveSettings(ctx context.Context, personID int64, zone string, weekStart, reminderMin, allDayMin int, channel string) error {
184 if _, err := Zone(zone); err != nil {
185 return ValidationError{"zone", "That is not a time zone we know."}
186 }
187 switch weekStart {
188 case WeekStartMonday, WeekStartSaturday, WeekStartSunday:
189 default:
190 weekStart = WeekStartMonday
191 }
192 cols := map[string]any{
193 "zone": zone,
194 "week_start": weekStart,
195 "default_reminder_min": reminderMin,
196 "default_all_day_min": allDayMin,
197 "updated_at": time.Now().UTC(),
198 }
199 if validChannel(channel) {
200 cols["reminder_channel"] = channel
201 }
202 err := s.guarded(ctx, func(db *gorm.DB) error {
203 return db.Model(&Person{}).Where("id = ?", personID).Updates(cols).Error
204 })
205 if err != nil {
206 return fmt.Errorf("calendar: save settings: %w", err)
207 }
208 return nil
209}
210