Files
Docwell/Server/internal/calendar/google.go
T
tajniak81andClaude Opus 5.5 29465e4617 Add, change and delete calendar events from journal pages
CalDAV and Google calendars can now be written to from the journal on
the web and in the phone app. Each change goes to the source at once
with If-Match set to the ETag the last sync read, so a change made
elsewhere is refused (409) instead of overwritten; the account is then
read again. Repeating events, iCal feeds and read-only Google calendars
stay read-only.

- calendar_events keep each event's calendar, object/event id, ETag and
  whether it repeats; accounts keep their writable calendars and the
  one new events go to (migration 1764800000_calendar_writes).
- Google sign-in asks for calendar.events; older read-only accounts are
  offered "Connect again".
- New API: POST /calendar/events, PATCH and DELETE /calendar/events/{id}.
- Translations, Docs-Site guides and changelog updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:17:28 +01:00

341 lines
11 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package calendar
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"slices"
"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: the read-only calendar scope
// to list calendars and read events, and the events scope to add and change
// them. 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). Accounts
// connected before Docwell wrote to calendars have only the read-only scope
// (can_write false) until they are connected again.
// PurposeGoogle names the OAuth state of a Google Calendar sign-in.
const PurposeGoogle = "google-calendar"
const googleEventsScope = "https://www.googleapis.com/auth/calendar.events"
var googleScopes = []string{"openid", "email", "https://www.googleapis.com/auth/calendar.readonly", googleEventsScope}
// grantsEvents reports whether a token's scopes include writing events.
func grantsEvents(scope string) bool {
return slices.Contains(strings.Fields(scope), googleEventsScope)
}
// 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)
// People can leave the events box unticked on Google's consent screen;
// the account then stays read-only.
canWrite := grantsEvents(tok.Scope)
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": "", "can_write": canWrite,
})
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, CanWrite: canWrite}
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, "can_write": canWrite,
}
_, 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 {
return s.googleDo(ctx, http.MethodGet, access, path, q, nil, "", out)
}
// googleDo sends one Calendar API request with body in (nil for none) and
// reads the answer into out (nil to drop it). ifMatch, when set, is the ETag
// the change is meant for. For changes, a 412 answer is errStale, 404 and
// 410 errGone.
func (s *Service) googleDo(ctx context.Context, method, access, path string, q url.Values, in any, ifMatch string, out any) error {
u := s.googleAPI + path
if len(q) > 0 {
u += "?" + q.Encode()
}
var reqBody io.Reader
if in != nil {
raw, err := json.Marshal(in)
if err != nil {
return err
}
reqBody = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, u, reqBody)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+access)
req.Header.Set("Accept", "application/json")
if in != nil {
req.Header.Set("Content-Type", "application/json")
}
if ifMatch != "" {
req.Header.Set("If-Match", ifMatch)
}
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 method != http.MethodGet {
switch res.StatusCode {
case http.StatusPreconditionFailed:
return errStale
case http.StatusNotFound, http.StatusGone:
return errGone
}
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
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)
}
if out == nil || len(body) == 0 {
return nil
}
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,omitempty"`
DateTime string `json:"dateTime,omitempty"`
}
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
}
// googleAccess is a fresh access token for a Google account.
func (s *Service) googleAccess(ctx context.Context, r record) (string, error) {
refresh, err := s.open(r.Secret)
if err != nil {
return "", err
}
if refresh == "" {
return "", oauth.ErrRevoked
}
tok, err := s.google.Refresh(ctx, s.client, refresh, nil)
if err != nil {
return "", err
}
return tok.AccessToken, nil
}
// googleEvent is an event as the Calendar API has it.
type googleEvent struct {
ID string `json:"id"`
ETag string `json:"etag"`
Status string `json:"status"`
Summary string `json:"summary"`
Location string `json:"location"`
HTMLLink string `json:"htmlLink"`
RecurringEventID string `json:"recurringEventId"`
Start googleTime `json:"start"`
End googleTime `json:"end"`
}
// item is e as stored, from calendar cal; false for a cancelled or
// unreadable event.
func (e googleEvent) item(cal string) (item, bool) {
if e.Status == "cancelled" {
return item{}, false
}
start, allDay, err1 := e.Start.parse()
end, _, err2 := e.End.parse()
if err1 != nil || err2 != nil {
return item{}, false
}
return item{
key: eventID(cal+"\x00"+e.ID, start), title: e.Summary, location: e.Location,
url: safeLink(e.HTMLLink), allDay: allDay, start: start, end: end,
cal: cal, ref: e.ID, etag: e.ETag, recurring: e.RecurringEventID != "",
}, true
}
// googleItems reads the occurrences of every calendar the person shows in
// Google Calendar, and lists the ones they may add events to (their primary
// calendar first).
func (s *Service) googleItems(ctx context.Context, r record, from, to time.Time) (reading, error) {
access, err := s.googleAccess(ctx, r)
if err != nil {
return reading{}, err
}
var list struct {
Items []struct {
ID string `json:"id"`
Summary string `json:"summary"`
Selected bool `json:"selected"`
Primary bool `json:"primary"`
Hidden bool `json:"hidden"`
AccessRole string `json:"accessRole"`
} `json:"items"`
}
if err := s.googleGet(ctx, access, "/calendar/v3/users/me/calendarList", url.Values{"minAccessRole": {"reader"}, "maxResults": {"250"}}, &list); err != nil {
return reading{}, err
}
var items []item
var targets []Target
for _, cal := range list.Items {
if cal.Hidden || (!cal.Selected && !cal.Primary) {
continue
}
writer := cal.AccessRole == "owner" || cal.AccessRole == "writer"
if writer {
t := Target{ID: cal.ID, Name: cal.Summary}
if cal.Primary {
targets = append([]Target{t}, targets...)
} else {
targets = append(targets, t)
}
}
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 []googleEvent `json:"items"`
NextPageToken string `json:"nextPageToken"`
}
if err := s.googleGet(ctx, access, "/calendar/v3/calendars/"+url.PathEscape(cal.ID)+"/events", q, &res); err != nil {
return reading{}, err
}
for _, e := range res.Items {
it, ok := e.item(cal.ID)
if !ok {
continue
}
if !writer {
it.ref = "" // Someone else's calendar, shown read-only.
}
items = append(items, it)
}
if res.NextPageToken == "" || len(items) >= maxStored {
break
}
q.Set("pageToken", res.NextPageToken)
}
}
return reading{items: items, count: len(items), targets: targets}, nil
}