Files
Docwell/Server/internal/calendar/calendar.go
T
tajniak81andClaude Opus 5.5 6984c7d162 Connect Google Calendar, import OneNote notebooks, sync Readwise, and package the clipper
Phase F follow-ups (ADR-16):

- Calendars: events are now stored in calendar_events by a
  calendars.sync job (every 15 minutes per account, 90 days back and
  400 ahead), so journals open at once and keep showing events while a
  source is down. Google accounts connect with OAuth (calendar.readonly)
  through DOCWELL_GOOGLE_CLIENT_ID/SECRET; reconnecting renews access.
- OneNote: whole notebooks import through Microsoft Graph (Notes.Read,
  DOCWELL_MICROSOFT_CLIENT_ID/SECRET/TENANT) in the background, with
  section groups, sections, subpages, pictures and attached files. The
  Microsoft sign-in lives in memory for an hour and is never stored.
- Readwise: an hourly sync with the person's sealed access token; new
  books get a page under "Readwise", new highlights are appended once.
  New readwise_syncs collection.
- internal/oauth: signed states and one callback route per provider,
  routed by purpose. directory gains ImportConverted and CallerOf.
- Phone app: "Today's journal" on the home screen and calendar events
  on journal pages.
- Web clipper: `npm run package` builds Chrome/Edge, Firefox and source
  zips; store/ holds listing texts, permission notes and a privacy
  policy.
- OpenAPI, generated clients, translations, compose and .env examples,
  and user docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:59:34 +01:00

785 lines
23 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package calendar reads people's calendars for their journals (Phase F,
// ADR-16): read-only subscriptions to an iCalendar feed (an .ics or webcal
// address, Outlook's published calendar, any feed), a CalDAV account
// (Nextcloud, iCloud, Fastmail…) or a Google account signed in with OAuth.
// Each person sees only their own. The calendars.sync job copies the events
// of every account, a few months back and a year ahead, into
// calendar_events every 15 minutes, so journals on the web and on phones
// read them at once and still show them when a source is down.
package calendar
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"slices"
"strings"
"sync"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/oauth"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/webhooks"
)
// Kinds of calendar accounts.
const (
KindICS = "ics"
KindCalDAV = "caldav"
KindGoogle = "google"
)
const (
maxAccounts = 20
// maxRange caps the days one events request covers.
maxRange = 92
// fetchTimeout caps one source fetch.
fetchTimeout = 30 * time.Second
// maxStored caps the occurrences kept per account.
maxStored = 5000
)
// The events kept: from windowBack days ago to windowAhead days ahead.
const (
windowBack = 90
windowAhead = 400
)
// GoogleAPI is where Google's APIs are (a variable for test builds).
var GoogleAPI = "https://www.googleapis.com"
// Colours an account can have; the apps draw them from the theme.
var colors = []string{"gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"}
// Options configure the service.
type Options struct {
// Secret seals the accounts' passwords and tokens (DOCWELL_SECRET_KEY).
Secret string
// AllowLocal lets sources on loopback addresses through (development).
AllowLocal bool
// TTL is how often each account is read again (15 min).
TTL time.Duration
// Client replaces the HTTP client (tests).
Client *http.Client
// Google is the OAuth app for Google Calendar; disabled when empty.
Google oauth.Provider
// States signs OAuth states. PublicURL is docwell-server's address (for
// the OAuth callback), WebURL the web app's (where the callback returns).
States *oauth.States
PublicURL string
WebURL string
// GoogleAPI replaces https://www.googleapis.com (tests).
GoogleAPI string
}
type Service struct {
pb *pocketbase.Client
aead cipher.AEAD
client *http.Client
ttl time.Duration
google oauth.Provider
states *oauth.States
publicURL string
webURL string
googleAPI string
// syncing holds the accounts being synced, so two syncs never overlap.
mu sync.Mutex
syncing map[string]bool
}
func New(pb *pocketbase.Client, o Options) *Service {
key := sha256.Sum256([]byte("docwell-calendar:" + o.Secret))
block, _ := aes.NewCipher(key[:])
aead, _ := cipher.NewGCM(block)
client := o.Client
if client == nil {
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: webhooks.Guard(o.AllowLocal)}
client = &http.Client{
Timeout: fetchTimeout,
Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: http.ProxyFromEnvironment, MaxResponseHeaderBytes: 64 << 10},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return errors.New("too many redirects")
}
return nil
},
}
}
ttl := o.TTL
if ttl <= 0 {
ttl = 15 * time.Minute
}
api := strings.TrimRight(o.GoogleAPI, "/")
if api == "" {
api = GoogleAPI
}
states := o.States
if states == nil {
states = oauth.NewStates(o.Secret)
}
return &Service{
pb: pb, aead: aead, client: client, ttl: ttl, google: o.Google, states: states,
publicURL: strings.TrimRight(o.PublicURL, "/"), webURL: strings.TrimRight(o.WebURL, "/"), googleAPI: api,
syncing: map[string]bool{},
}
}
func (s *Service) seal(plain string) string {
if plain == "" {
return ""
}
nonce := make([]byte, s.aead.NonceSize())
_, _ = rand.Read(nonce)
return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil))
}
var errUnreadable = errors.New("the stored password cannot be decrypted (the server secret changed); enter it again")
func (s *Service) open(sealed string) (string, error) {
if sealed == "" {
return "", nil
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:"))
n := s.aead.NonceSize()
if err != nil || len(raw) < n {
return "", errUnreadable
}
plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil)
if err != nil {
return "", errUnreadable
}
return string(plain), nil
}
// ---- Accounts ------------------------------------------------------------------
type record struct {
ID string `json:"id"`
User string `json:"user"`
Name string `json:"name"`
Kind string `json:"kind"`
URL string `json:"url"`
Username string `json:"username"`
Secret string `json:"secret"`
Color string `json:"color"`
Enabled bool `json:"enabled"`
LastSync string `json:"last_sync"`
LastError string `json:"last_error"`
Events float64 `json:"events"`
Created string `json:"created"`
}
// Account is a calendar subscription as its owner sees it, without the password.
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
URL string `json:"url"`
Username string `json:"username"`
HasPassword bool `json:"hasPassword"`
Color string `json:"color"`
Enabled bool `json:"enabled"`
// LastSync is when the source was last read; LastError why that failed ("" when it worked).
LastSync string `json:"lastSync"`
LastError string `json:"lastError"`
// Events counts the events (repeating ones once) the source held then.
Events int `json:"events"`
Created string `json:"created"`
}
func (r record) view() Account {
return Account{
ID: r.ID, Name: r.Name, Kind: r.Kind, URL: r.URL, Username: r.Username, HasPassword: r.Secret != "",
Color: r.Color, Enabled: r.Enabled, LastSync: r.LastSync, LastError: r.LastError, Events: int(r.Events),
Created: r.Created,
}
}
// AccountInput creates an account, or changes the fields that are set. An
// empty Password keeps the stored one when changing; ClearPassword removes it.
type AccountInput struct {
Name *string `json:"name"`
Kind *string `json:"kind"`
URL *string `json:"url"`
Username *string `json:"username"`
Password *string `json:"password"`
ClearPassword bool `json:"clearPassword"`
Color *string `json:"color"`
Enabled *bool `json:"enabled"`
}
func signedIn(c access.Caller) error {
if c.ID == "" {
return apperr.NotFound("calendar not found")
}
return nil
}
func (s *Service) records(ctx context.Context, user string) ([]record, error) {
res, err := pocketbase.List[record](ctx, s.pb, "calendar_accounts", pocketbase.ListOptions{
PerPage: maxAccounts * 2, Filter: fmt.Sprintf("user = '%s'", user), Sort: "created",
})
return res.Items, err
}
func (s *Service) get(ctx context.Context, c access.Caller, id string) (record, error) {
if err := signedIn(c); err != nil {
return record{}, err
}
if len(id) == 0 || len(id) > 64 || strings.ContainsAny(id, `'"\`) {
return record{}, apperr.NotFound("calendar not found")
}
r, err := pocketbase.Get[record](ctx, s.pb, "calendar_accounts", id)
if err != nil || r.User != c.ID {
return record{}, apperr.NotFound("calendar not found")
}
return r, nil
}
// List lists the caller's calendars.
func (s *Service) List(ctx context.Context, c access.Caller) ([]Account, error) {
if err := signedIn(c); err != nil {
return nil, err
}
rows, err := s.records(ctx, c.ID)
if err != nil {
return nil, err
}
out := make([]Account, len(rows))
for i, r := range rows {
out[i] = r.view()
}
return out, nil
}
// patch checks the input against what is stored (zero for a new account).
func (s *Service) patch(in AccountInput, old record) (map[string]any, record, error) {
p := map[string]any{}
next := old
bad := func(field, msg string) (map[string]any, record, error) {
return nil, record{}, apperr.InvalidFields(map[string]string{field: msg})
}
if old.Kind == KindGoogle && (in.Kind != nil || in.URL != nil || in.Username != nil || in.Password != nil || in.ClearPassword) {
return bad("kind", "A Google account is changed by connecting it again.")
}
if in.Name != nil {
name := strings.TrimSpace(*in.Name)
if name == "" || len([]rune(name)) > 80 {
return bad("name", "Give the calendar a name of at most 80 characters.")
}
p["name"], next.Name = name, name
}
if in.Kind != nil {
if *in.Kind != KindICS && *in.Kind != KindCalDAV {
return bad("kind", "Kind must be ics or caldav; Google accounts are connected with Connect Google.")
}
p["kind"], next.Kind = *in.Kind, *in.Kind
}
if in.URL != nil {
if _, err := feedURL(*in.URL); err != nil || len(*in.URL) > 2000 {
return bad("url", "Enter an http, https or webcal address.")
}
v := strings.TrimSpace(*in.URL)
p["url"], next.URL = v, v
}
if in.Username != nil {
v := strings.TrimSpace(*in.Username)
if len(v) > 200 {
return bad("username", "The user name is too long.")
}
p["username"], next.Username = v, v
}
switch {
case in.Password != nil && *in.Password != "":
if len(*in.Password) > 1000 {
return bad("password", "The password is too long.")
}
sealed := s.seal(*in.Password)
p["secret"], next.Secret = sealed, sealed
case in.ClearPassword:
p["secret"], next.Secret = "", ""
}
if in.Color != nil {
if !slices.Contains(colors, *in.Color) {
return bad("color", "Unknown colour.")
}
p["color"], next.Color = *in.Color, *in.Color
}
if in.Enabled != nil {
p["enabled"], next.Enabled = *in.Enabled, *in.Enabled
}
return p, next, nil
}
// Create adds a calendar after reading it once, so a wrong address or
// password is reported now rather than as an empty journal. Its events are
// stored in the background.
func (s *Service) Create(ctx context.Context, c access.Caller, in AccountInput) (Account, error) {
if err := signedIn(c); err != nil {
return Account{}, err
}
if in.Name == nil || in.Kind == nil || in.URL == nil {
return Account{}, apperr.InvalidFields(map[string]string{"url": "Name, kind and address are required."})
}
rows, err := s.records(ctx, c.ID)
if err != nil {
return Account{}, err
}
if len(rows) >= maxAccounts {
return Account{}, apperr.Invalid(fmt.Sprintf("you can add at most %d calendars", maxAccounts))
}
if in.Color == nil {
color := colors[(len(rows)+6)%len(colors)]
in.Color = &color
}
on := true
if in.Enabled == nil {
in.Enabled = &on
}
body, next, err := s.patch(in, record{})
if err != nil {
return Account{}, err
}
return s.add(ctx, c.ID, body, next)
}
// add reads a new account, then stores it and (in the background) its events.
func (s *Service) add(ctx context.Context, user string, body map[string]any, next record) (Account, error) {
items, count, err := s.collect(ctx, next)
if err != nil {
return Account{}, apperr.InvalidFields(map[string]string{"url": err.Error()})
}
body["user"] = user
body["last_sync"] = pbTime(time.Now())
body["last_error"] = ""
body["events"] = count
rec, err := pocketbase.Create[record](ctx, s.pb, "calendar_accounts", body)
if err != nil {
return Account{}, err
}
s.storeLater(rec, items)
return rec.view(), nil
}
// Update changes a calendar; a new address, kind or sign-in is read first.
func (s *Service) Update(ctx context.Context, c access.Caller, id string, in AccountInput) (Account, error) {
old, err := s.get(ctx, c, id)
if err != nil {
return Account{}, err
}
body, next, err := s.patch(in, old)
if err != nil {
return Account{}, err
}
if len(body) == 0 {
return old.view(), nil
}
var items []item
changed := sourceKey(next) != sourceKey(old)
if changed {
var count int
if items, count, err = s.collect(ctx, next); err != nil {
return Account{}, apperr.InvalidFields(map[string]string{"url": err.Error()})
}
body["last_sync"], body["last_error"], body["events"] = pbTime(time.Now()), "", count
}
rec, err := pocketbase.Update[record](ctx, s.pb, "calendar_accounts", old.ID, body)
if err != nil {
return Account{}, err
}
if changed {
s.storeLater(rec, items)
}
return rec.view(), nil
}
// Delete removes a calendar and its stored events.
func (s *Service) Delete(ctx context.Context, c access.Caller, id string) error {
r, err := s.get(ctx, c, id)
if err != nil {
return err
}
return s.pb.Delete(ctx, "calendar_accounts", r.ID)
}
// Refresh reads a calendar from its source and stores its events now.
func (s *Service) Refresh(ctx context.Context, c access.Caller, id string) (Account, error) {
r, err := s.get(ctx, c, id)
if err != nil {
return Account{}, err
}
if err := s.Sync(ctx, r); err != nil {
slog.Debug("calendar refresh failed", "calendar", r.ID, "err", err)
}
r, err = s.get(ctx, c, id)
return r.view(), err
}
func pbTime(t time.Time) string { return t.UTC().Format("2006-01-02 15:04:05.000Z") }
func sourceKey(r record) string {
return r.Kind + "\x00" + r.URL + "\x00" + r.Username + "\x00" + r.Secret
}
func (f *feed) count() int {
n := len(f.events)
for _, o := range f.overrides {
n += len(o)
}
return n
}
// ---- Stored events -------------------------------------------------------------
// item is one occurrence as stored. Timed events have UTC instants;
// all-day ones dates at 00:00 UTC (end exclusive).
type item struct {
key, title, location, url string
allDay bool
start, end time.Time
}
// hash tells a changed occurrence from an unchanged one.
func (it item) hash() string {
h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%s\x00%t\x00%d\x00%d", it.title, it.location, it.url, it.allDay, it.start.Unix(), it.end.Unix())))
return hex.EncodeToString(h[:12])
}
type eventRecord struct {
ID string `json:"id"`
Account string `json:"account"`
Key string `json:"key"`
Hash string `json:"hash"`
Title string `json:"title"`
Location string `json:"location"`
URL string `json:"url"`
AllDay bool `json:"all_day"`
StartAt string `json:"start_at"`
EndAt string `json:"end_at"`
}
// window is the stretch of time stored for each account.
func window(now time.Time) (time.Time, time.Time) {
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
return day.AddDate(0, 0, -windowBack), day.AddDate(0, 0, windowAhead)
}
// collect reads an account's source: its occurrences in the window, and how
// many events it holds (repeating ones once).
func (s *Service) collect(ctx context.Context, r record) ([]item, int, error) {
ctx, cancel := context.WithTimeout(ctx, 2*fetchTimeout)
defer cancel()
from, to := window(time.Now())
if r.Kind == KindGoogle {
return s.googleItems(ctx, r, from, to)
}
password, err := s.open(r.Secret)
if err != nil {
return nil, 0, err
}
data, err := fetch(ctx, s.client, source{kind: r.Kind, url: r.URL, username: r.Username, password: password})
if err != nil {
return nil, 0, err
}
// All-day dates are read at 00:00 UTC, so they stay the same date
// whatever zone a journal is read in.
f, err := parseFeed(bytes.NewReader(data), time.UTC)
if err != nil {
return nil, 0, err
}
occ := f.between(from, to)
items := make([]item, 0, len(occ))
for _, o := range occ {
items = append(items, item{
key: eventID(o.def.uid, o.start), title: o.def.title, location: o.def.location,
url: safeLink(o.def.link), allDay: o.def.allDay, start: o.start.UTC(), end: o.end.UTC(),
})
}
return items, f.count(), nil
}
// Sync reads an account and stores its events. A failed read keeps the
// stored events and records why on the account.
func (s *Service) Sync(ctx context.Context, r record) error {
s.mu.Lock()
if s.syncing[r.ID] {
s.mu.Unlock()
return nil
}
s.syncing[r.ID] = true
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.syncing, r.ID)
s.mu.Unlock()
}()
items, count, err := s.collect(ctx, r)
patch := map[string]any{"last_sync": pbTime(time.Now()), "last_error": ""}
if err != nil {
msg := err.Error()
if len(msg) > 500 {
msg = msg[:500]
}
patch["last_error"] = msg
} else {
patch["events"] = count
err = s.store(ctx, r, items)
}
if _, uerr := pocketbase.Update[record](context.WithoutCancel(ctx), s.pb, "calendar_accounts", r.ID, patch); uerr != nil {
slog.Debug("calendar status not saved", "calendar", r.ID, "err", uerr)
}
return err
}
// storeLater stores a first read in the background, so adding a large
// calendar does not wait on thousands of writes.
func (s *Service) storeLater(r record, items []item) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if err := s.store(ctx, r, items); err != nil {
slog.Warn("calendar events not stored", "calendar", r.ID, "err", err)
}
}()
}
// store makes the account's stored events match items.
func (s *Service) store(ctx context.Context, r record, items []item) error {
if len(items) > maxStored {
items = items[:maxStored]
}
var have []eventRecord
for page := 1; ; page++ {
res, err := pocketbase.List[eventRecord](ctx, s.pb, "calendar_events", pocketbase.ListOptions{
Page: page, PerPage: 1000, Filter: fmt.Sprintf("account = '%s'", r.ID), Fields: "id,key,hash",
})
if err != nil {
return err
}
have = append(have, res.Items...)
if page >= res.TotalPages || len(res.Items) == 0 {
break
}
}
old := make(map[string]eventRecord, len(have))
for _, e := range have {
if _, dup := old[e.Key]; dup {
_ = s.pb.Delete(ctx, "calendar_events", e.ID)
continue
}
old[e.Key] = e
}
seen := make(map[string]bool, len(items))
for _, it := range items {
if seen[it.key] {
continue
}
seen[it.key] = true
hash := it.hash()
prev, ok := old[it.key]
if ok && prev.Hash == hash {
continue
}
body := map[string]any{
"hash": hash, "title": clip(it.title, 1000), "location": clip(it.location, 1000), "url": clip(it.url, 2000),
"all_day": it.allDay, "start_at": pbTime(it.start), "end_at": pbTime(it.end),
}
if ok {
if _, err := pocketbase.Update[eventRecord](ctx, s.pb, "calendar_events", prev.ID, body); err != nil {
return err
}
continue
}
body["account"], body["user"], body["key"] = r.ID, r.User, it.key
if _, err := pocketbase.Create[eventRecord](ctx, s.pb, "calendar_events", body); err != nil {
return err
}
}
for key, e := range old {
if !seen[key] {
if err := s.pb.Delete(ctx, "calendar_events", e.ID); err != nil && !pocketbase.IsNotFound(err) {
return err
}
}
}
return nil
}
func clip(v string, n int) string {
if len(v) <= n {
return v
}
return strings.ToValidUTF8(v[:n], "")
}
// SyncDue syncs every enabled account not read for a while (the
// calendars.sync job).
func (s *Service) SyncDue(ctx context.Context) error {
cutoff := pbTime(time.Now().Add(-s.ttl))
var due []record
for page := 1; ; page++ {
res, err := pocketbase.List[record](ctx, s.pb, "calendar_accounts", pocketbase.ListOptions{
Page: page, PerPage: 500, Filter: fmt.Sprintf("enabled = true && (last_sync = '' || last_sync < '%s')", cutoff),
Sort: "last_sync",
})
if err != nil {
return err
}
due = append(due, res.Items...)
if page >= res.TotalPages || len(res.Items) == 0 {
break
}
}
failed := 0
for _, r := range due {
if ctx.Err() != nil {
return ctx.Err()
}
if err := s.Sync(ctx, r); err != nil {
failed++
}
}
if failed > 0 {
slog.Info("calendars synced", "accounts", len(due), "failed", failed)
}
return nil
}
// ---- Events --------------------------------------------------------------------
// Event is one occurrence of an event in one of the caller's calendars.
type Event struct {
ID string `json:"id"`
Calendar string `json:"calendar"`
Title string `json:"title"`
Location string `json:"location"`
URL string `json:"url"`
// Start and End are RFC 3339 times, or for all-day events dates
// (YYYY-MM-DD, End exclusive).
Start string `json:"start"`
End string `json:"end"`
AllDay bool `json:"allDay"`
Color string `json:"color"`
}
func parsePB(v string) (time.Time, error) {
return time.Parse("2006-01-02 15:04:05.000Z", v)
}
// Events lists the caller's stored events from day from to day to (both
// YYYY-MM-DD, inclusive) in zone tz (an IANA name; "" is UTC), from their
// enabled calendars.
func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz string) ([]Event, error) {
if err := signedIn(c); err != nil {
return nil, err
}
loc := time.UTC
if tz != "" {
l, err := time.LoadLocation(tz)
if err != nil {
return nil, apperr.InvalidFields(map[string]string{"tz": "Unknown time zone."})
}
loc = l
}
day1, err1 := time.Parse(time.DateOnly, from)
day2, err2 := time.Parse(time.DateOnly, to)
if err1 != nil || err2 != nil {
return nil, apperr.InvalidFields(map[string]string{"from": "Dates look like 2026-11-16."})
}
day2 = day2.AddDate(0, 0, 1)
if !day2.After(day1) || day2.Sub(day1) > maxRange*24*time.Hour {
return nil, apperr.InvalidFields(map[string]string{"to": fmt.Sprintf("Ask for at most %d days, ending after they start.", maxRange)})
}
// Timed events: the instants the days cover in loc. All-day events: the
// dates themselves, stored at 00:00 UTC.
start := time.Date(day1.Year(), day1.Month(), day1.Day(), 0, 0, 0, 0, loc)
end := time.Date(day2.Year(), day2.Month(), day2.Day(), 0, 0, 0, 0, loc)
rows, err := s.records(ctx, c.ID)
if err != nil {
return nil, err
}
color := map[string]string{}
var ids []string
for _, r := range rows {
if r.Enabled {
color[r.ID] = r.Color
ids = append(ids, fmt.Sprintf("account = '%s'", r.ID))
}
}
out := []Event{}
if len(ids) == 0 {
return out, nil
}
filter := fmt.Sprintf("user = '%s' && (%s) && ((all_day = false && start_at < '%s' && end_at > '%s') || (all_day = true && start_at < '%s' && end_at > '%s'))",
c.ID, strings.Join(ids, " || "), pbTime(end), pbTime(start), pbTime(day2), pbTime(day1))
for page := 1; ; page++ {
res, err := pocketbase.List[eventRecord](ctx, s.pb, "calendar_events", pocketbase.ListOptions{
Page: page, PerPage: 500, Filter: filter, Sort: "start_at",
})
if err != nil {
return nil, err
}
for _, e := range res.Items {
st, err1 := parsePB(e.StartAt)
en, err2 := parsePB(e.EndAt)
if err1 != nil || err2 != nil {
continue
}
ev := Event{
ID: e.Key, Calendar: e.Account, Title: e.Title, Location: e.Location, URL: e.URL,
AllDay: e.AllDay, Color: color[e.Account],
}
if ev.Title == "" {
ev.Title = "(no title)"
}
if e.AllDay {
ev.Start, ev.End = st.Format(time.DateOnly), en.Format(time.DateOnly)
} else {
ev.Start, ev.End = st.UTC().Format(time.RFC3339), en.UTC().Format(time.RFC3339)
}
out = append(out, ev)
}
if page >= res.TotalPages || len(res.Items) == 0 || len(out) >= 2000 {
break
}
}
slices.SortStableFunc(out, func(a, b Event) int {
if a.AllDay != b.AllDay {
if a.AllDay {
return -1
}
return 1
}
return strings.Compare(a.Start, b.Start)
})
return out, nil
}
func eventID(uid string, start time.Time) string {
h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%d", uid, start.Unix())))
return hex.EncodeToString(h[:8])
}
// safeLink keeps only web links from a calendar.
func safeLink(v string) string {
if strings.HasPrefix(v, "https://") || strings.HasPrefix(v, "http://") {
return v
}
return ""
}