Files
Docwell/Server/internal/calendar/google.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

250 lines
7.7 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package calendar
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/oauth"
"docwell/server/internal/store/pocketbase"
)
// ---- Google Calendar -------------------------------------------------------------
//
// People connect a Google account with OAuth (read-only calendar scope). The
// account's secret is its sealed refresh token; every calendar shown in the
// person's Google Calendar list is read through the Calendar API, with
// repeating events expanded by Google (singleEvents).
// PurposeGoogle names the OAuth state of a Google Calendar sign-in.
const PurposeGoogle = "google-calendar"
var googleScopes = []string{"openid", "email", "https://www.googleapis.com/auth/calendar.readonly"}
// GoogleEnabled reports whether the server has a Google OAuth app.
func (s *Service) GoogleEnabled() bool { return s.google.Enabled() }
func (s *Service) googleRedirect() string { return s.publicURL + "/api/v1/oauth/google/callback" }
// GoogleConnectURL is where the caller signs in to Google to add their
// calendars.
func (s *Service) GoogleConnectURL(ctx context.Context, c access.Caller) (string, error) {
if err := signedIn(c); err != nil {
return "", err
}
if !s.google.Enabled() {
return "", apperr.NotFound("Google sign-in is not set up on this server")
}
rows, err := s.records(ctx, c.ID)
if err != nil {
return "", err
}
if len(rows) >= maxAccounts {
return "", apperr.Invalid(fmt.Sprintf("you can add at most %d calendars", maxAccounts))
}
state := s.states.Sign(oauth.State{User: c.ID, Purpose: PurposeGoogle})
return s.google.AuthCodeURL(state, s.googleRedirect(), googleScopes), nil
}
// GoogleCallback finishes a sign-in: it stores the account (or replaces the
// token of the same Google account) and returns where the browser goes next.
func (s *Service) GoogleCallback(ctx context.Context, st oauth.State, code, providerErr string) string {
done := func(err error) string {
q := url.Values{"calendar": {"connected"}}
if err != nil {
q = url.Values{"calendarError": {err.Error()}}
}
return s.webURL + "/settings/account?" + q.Encode()
}
if providerErr != "" {
return done(fmt.Errorf("the Google account was not connected (%s)", providerErr))
}
tok, err := s.google.Exchange(ctx, s.client, code, s.googleRedirect())
if err != nil {
return done(err)
}
if tok.RefreshToken == "" {
return done(errors.New("no lasting access came from Google; remove Docwell from your Google account's third-party access and connect again"))
}
email, err := s.googleEmail(ctx, tok.AccessToken)
if err != nil {
return done(err)
}
rows, err := s.records(ctx, st.User)
if err != nil {
return done(err)
}
sealed := s.seal(tok.RefreshToken)
for _, r := range rows {
if r.Kind == KindGoogle && strings.EqualFold(r.Username, email) {
rec, err := pocketbase.Update[record](ctx, s.pb, "calendar_accounts", r.ID, map[string]any{"secret": sealed, "last_error": ""})
if err != nil {
return done(err)
}
go func() { //nolint:gosec // the sync outlives the sign-in request on purpose
if err := s.Sync(context.Background(), rec); err != nil {
slog.Warn("google calendar sync failed", "calendar", rec.ID, "err", err)
}
}()
return done(nil)
}
}
if len(rows) >= maxAccounts {
return done(fmt.Errorf("you can add at most %d calendars", maxAccounts))
}
next := record{Kind: KindGoogle, URL: "https://calendar.google.com", Username: email, Secret: sealed}
body := map[string]any{
"name": "Google · " + email, "kind": KindGoogle, "url": next.URL, "username": email, "secret": sealed,
"color": colors[(len(rows)+6)%len(colors)], "enabled": true,
}
_, err = s.add(ctx, st.User, body, next)
return done(err)
}
// googleGet reads one Calendar API answer into out.
func (s *Service) googleGet(ctx context.Context, access, path string, q url.Values, out any) error {
u := s.googleAPI + path
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+access)
req.Header.Set("Accept", "application/json")
res, err := s.client.Do(req)
if err != nil {
return friendly(err)
}
defer func() { _ = res.Body.Close() }()
body, err := io.ReadAll(io.LimitReader(res.Body, maxFeed))
if err != nil {
return friendly(err)
}
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
_ = json.Unmarshal(body, &e)
if e.Error.Message == "" {
e.Error.Message = res.Status
}
return fmt.Errorf("the Google Calendar API answered: %s", e.Error.Message)
}
return json.Unmarshal(body, out)
}
func (s *Service) googleEmail(ctx context.Context, access string) (string, error) {
var info struct {
Email string `json:"email"`
}
if err := s.googleGet(ctx, access, "/oauth2/v3/userinfo", nil, &info); err != nil {
return "", err
}
if info.Email == "" {
return "", errors.New("the Google sign-in did not say which account it was")
}
return info.Email, nil
}
type googleTime struct {
Date string `json:"date"`
DateTime string `json:"dateTime"`
}
func (t googleTime) parse() (time.Time, bool, error) {
if t.Date != "" {
d, err := time.Parse(time.DateOnly, t.Date)
return d, true, err
}
d, err := time.Parse(time.RFC3339, t.DateTime)
return d.UTC(), false, err
}
// googleItems reads the occurrences of every calendar the person shows in
// Google Calendar.
func (s *Service) googleItems(ctx context.Context, r record, from, to time.Time) ([]item, int, error) {
refresh, err := s.open(r.Secret)
if err != nil {
return nil, 0, err
}
if refresh == "" {
return nil, 0, oauth.ErrRevoked
}
tok, err := s.google.Refresh(ctx, s.client, refresh, nil)
if err != nil {
return nil, 0, err
}
var list struct {
Items []struct {
ID string `json:"id"`
Selected bool `json:"selected"`
Primary bool `json:"primary"`
Hidden bool `json:"hidden"`
} `json:"items"`
}
if err := s.googleGet(ctx, tok.AccessToken, "/calendar/v3/users/me/calendarList", url.Values{"minAccessRole": {"reader"}, "maxResults": {"250"}}, &list); err != nil {
return nil, 0, err
}
var items []item
for _, cal := range list.Items {
if cal.Hidden || (!cal.Selected && !cal.Primary) {
continue
}
q := url.Values{
"singleEvents": {"true"}, "timeMin": {from.Format(time.RFC3339)}, "timeMax": {to.Format(time.RFC3339)},
"maxResults": {"2500"}, "showDeleted": {"false"},
}
for pages := 0; pages < 20; pages++ {
var res struct {
Items []struct {
ID string `json:"id"`
Status string `json:"status"`
Summary string `json:"summary"`
Location string `json:"location"`
HTMLLink string `json:"htmlLink"`
Start googleTime `json:"start"`
End googleTime `json:"end"`
} `json:"items"`
NextPageToken string `json:"nextPageToken"`
}
if err := s.googleGet(ctx, tok.AccessToken, "/calendar/v3/calendars/"+url.PathEscape(cal.ID)+"/events", q, &res); err != nil {
return nil, 0, err
}
for _, e := range res.Items {
if e.Status == "cancelled" {
continue
}
start, allDay, err1 := e.Start.parse()
end, _, err2 := e.End.parse()
if err1 != nil || err2 != nil {
continue
}
items = append(items, item{
key: eventID(cal.ID+"\x00"+e.ID, start), title: e.Summary, location: e.Location,
url: safeLink(e.HTMLLink), allDay: allDay, start: start, end: end,
})
}
if res.NextPageToken == "" || len(items) >= maxStored {
break
}
q.Set("pageToken", res.NextPageToken)
}
}
return items, len(items), nil
}