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

611 lines
18 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package calendar
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/emersion/go-ical"
"github.com/emersion/go-webdav"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Writing events (ADR-19) -----------------------------------------------------
//
// A change goes to the source at once: a CalDAV PUT or DELETE, or a Google
// Calendar API call, with If-Match set to the ETag the last sync read. When
// the event changed elsewhere since, the source refuses (412), Docwell keeps
// what is there, reads the account again and tells the person. Only single
// events are changed; occurrences of repeating events are left to the
// calendar's own app. The stored copy is updated straight after a write, so
// the journal shows the change without waiting for the next sync.
var (
// errStale: the event changed at the source since it was read.
errStale = errors.New("calendar: event changed at the source")
// errGone: the event is no longer at the source.
errGone = errors.New("calendar: event no longer at the source")
)
const (
maxTitle = 500
maxLocation = 500
// maxSpan caps how long one event may last.
maxSpan = 366 * 24 * time.Hour
)
// EventInput adds an event (Calendar, Title and Start required) or changes
// the fields that are set. Start and End are RFC 3339 times, or dates
// (YYYY-MM-DD, End exclusive) when AllDay is set. A missing End is an hour
// after Start, or the next day for all-day events.
type EventInput struct {
Calendar *string `json:"calendar"`
Title *string `json:"title"`
Location *string `json:"location"`
Start *string `json:"start"`
End *string `json:"end"`
AllDay *bool `json:"allDay"`
}
var (
errStaleMsg = apperr.Conflict("This event was changed in its calendar after Docwell last read it. The journal now shows it as it is; make your change again.")
errGoneMsg = apperr.NotFound("This event is no longer in its calendar.")
)
// apply checks in and writes it over it (the event as it is, zero for a new one).
func (in EventInput) apply(it *item) error {
if in.Title != nil {
t := strings.TrimSpace(*in.Title)
if t == "" || utf8.RuneCountInString(t) > maxTitle {
return apperr.InvalidFields(map[string]string{"title": fmt.Sprintf("Give the event a title of at most %d characters.", maxTitle)})
}
it.title = t
}
if in.Location != nil {
l := strings.TrimSpace(*in.Location)
if utf8.RuneCountInString(l) > maxLocation {
return apperr.InvalidFields(map[string]string{"location": fmt.Sprintf("The place can have at most %d characters.", maxLocation)})
}
it.location = l
}
if in.AllDay == nil && in.Start == nil && in.End == nil {
return nil
}
allDay := it.allDay
if in.AllDay != nil {
allDay = *in.AllDay
}
if in.Start == nil && allDay != it.allDay {
return apperr.InvalidFields(map[string]string{"start": "Give the start when switching between all-day and timed."})
}
start, end := it.start, it.end
parse := func(v string) (time.Time, error) {
if allDay {
return time.Parse(time.DateOnly, v)
}
t, err := time.Parse(time.RFC3339, v)
return t.UTC(), err
}
if in.Start != nil {
t, err := parse(*in.Start)
if err != nil {
if allDay {
return apperr.InvalidFields(map[string]string{"start": "All-day events start on a date like 2026-11-17."})
}
return apperr.InvalidFields(map[string]string{"start": "Give the start as a time like 2026-11-17T09:00:00+01:00."})
}
// A moved start keeps the event's length unless End is given too.
length := end.Sub(start)
start = t
if in.End == nil {
if length <= 0 || in.AllDay != nil && *in.AllDay != it.allDay {
length = time.Hour
if allDay {
length = 24 * time.Hour
}
}
end = start.Add(length)
}
}
if in.End != nil {
t, err := parse(*in.End)
if err != nil {
return apperr.InvalidFields(map[string]string{"end": "The end is written like the start."})
}
end = t
}
if !end.After(start) {
return apperr.InvalidFields(map[string]string{"end": "The event has to end after it starts."})
}
if end.Sub(start) > maxSpan {
return apperr.InvalidFields(map[string]string{"end": "An event can last at most a year."})
}
it.start, it.end, it.allDay = start, end, allDay
return nil
}
// findEvent is the caller's stored event id with its account.
func (s *Service) findEvent(ctx context.Context, c access.Caller, id string) (eventRecord, record, error) {
if err := signedIn(c); err != nil {
return eventRecord{}, record{}, err
}
if _, err := hex.DecodeString(id); err != nil || len(id) != 16 {
return eventRecord{}, record{}, apperr.NotFound("event not found")
}
res, err := pocketbase.List[eventRecord](ctx, s.pb, "calendar_events", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("user = '%s' && key = '%s'", c.ID, id),
})
if err != nil {
return eventRecord{}, record{}, err
}
if len(res.Items) == 0 {
return eventRecord{}, record{}, apperr.NotFound("event not found")
}
e := res.Items[0]
acc, err := s.get(ctx, c, e.Account)
if err != nil {
return eventRecord{}, record{}, err
}
return e, acc, nil
}
// cannotWrite says why events of acc cannot be added or changed.
func cannotWrite(acc record) error {
switch {
case acc.Kind == KindICS:
return apperr.Invalid("Events of a subscribed feed are changed where the feed comes from.")
case acc.Kind == KindGoogle && !acc.CanWrite:
return apperr.Invalid("Connect the Google account again and allow Docwell to manage events, then try again.")
case !acc.Enabled:
return apperr.Invalid("Turn the calendar on first.")
default:
return apperr.Invalid("This calendar cannot be written to.")
}
}
// stored reads back an event record as an item.
func (e eventRecord) item() item {
st, _ := parsePB(e.StartAt)
en, _ := parsePB(e.EndAt)
return item{
key: e.Key, title: e.Title, location: e.Location, url: e.URL, allDay: e.AllDay, start: st, end: en,
cal: e.Cal, ref: e.Ref, etag: e.ETag, recurring: e.Recurring,
}
}
func (it item) event(acc record) Event {
e := eventRecord{
Key: it.key, Account: acc.ID, Title: it.title, Location: it.location, URL: it.url, AllDay: it.allDay,
Ref: it.ref, Recurring: it.recurring,
}
return e.view(acc.Color, acc.writable(), it.start, it.end)
}
// resync reads acc again in the background, after the source surprised us.
func (s *Service) resync(acc record) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
if err := s.Sync(ctx, acc); err != nil {
slog.Debug("calendar resync failed", "calendar", acc.ID, "err", err)
}
}()
}
// writeError turns a source's refusal into what the person is told.
func (s *Service) writeError(acc record, e *eventRecord, err error) error {
switch {
case errors.Is(err, errStale):
s.resync(acc)
return errStaleMsg
case errors.Is(err, errGone):
if e != nil {
_ = s.pb.Delete(context.Background(), "calendar_events", e.ID)
}
s.resync(acc)
return errGoneMsg
}
return apperr.Invalid(err.Error())
}
// CreateEvent adds an event to one of the caller's calendars (the
// account's chosen calendar within it).
func (s *Service) CreateEvent(ctx context.Context, c access.Caller, in EventInput) (Event, error) {
if err := signedIn(c); err != nil {
return Event{}, err
}
if in.Calendar == nil || in.Title == nil || in.Start == nil {
return Event{}, apperr.InvalidFields(map[string]string{"title": "Calendar, title and start are required."})
}
acc, err := s.get(ctx, c, *in.Calendar)
if err != nil {
return Event{}, err
}
if !acc.writable() {
return Event{}, cannotWrite(acc)
}
var it item
if err := in.apply(&it); err != nil {
return Event{}, err
}
it.cal = acc.target()
if acc.Kind == KindGoogle {
err = s.googleCreate(ctx, acc, &it)
} else {
err = s.davCreate(ctx, acc, &it)
}
if err != nil {
return Event{}, s.writeError(acc, nil, err)
}
body := it.body()
body["account"], body["user"], body["key"] = acc.ID, acc.User, it.key
if _, err := pocketbase.Create[eventRecord](ctx, s.pb, "calendar_events", body); err != nil {
// It is in the calendar; the next sync stores it.
slog.Warn("new calendar event not stored", "calendar", acc.ID, "err", err)
}
return it.event(acc), nil
}
// UpdateEvent changes a single event at its source.
func (s *Service) UpdateEvent(ctx context.Context, c access.Caller, id string, in EventInput) (Event, error) {
e, acc, err := s.findEvent(ctx, c, id)
if err != nil {
return Event{}, err
}
if in.Calendar != nil && *in.Calendar != acc.ID {
return Event{}, apperr.InvalidFields(map[string]string{"calendar": "An event cannot move to another calendar account."})
}
if !acc.writable() || e.Ref == "" {
return Event{}, cannotWrite(acc)
}
if e.Recurring {
return Event{}, apperr.Invalid("Repeating events are changed in their own calendar app.")
}
it := e.item()
if err := in.apply(&it); err != nil {
return Event{}, err
}
if acc.Kind == KindGoogle {
err = s.googleUpdate(ctx, acc, &it)
} else {
err = s.davUpdate(ctx, acc, &it)
}
if err != nil {
return Event{}, s.writeError(acc, &e, err)
}
body := it.body()
body["key"] = it.key
if _, err := pocketbase.Update[eventRecord](ctx, s.pb, "calendar_events", e.ID, body); err != nil {
slog.Warn("changed calendar event not stored", "calendar", acc.ID, "err", err)
s.resync(acc)
}
return it.event(acc), nil
}
// DeleteEvent removes a single event from its source.
func (s *Service) DeleteEvent(ctx context.Context, c access.Caller, id string) error {
e, acc, err := s.findEvent(ctx, c, id)
if err != nil {
return err
}
if !acc.writable() || e.Ref == "" {
return cannotWrite(acc)
}
if e.Recurring {
return apperr.Invalid("Repeating events are changed in their own calendar app.")
}
it := e.item()
if acc.Kind == KindGoogle {
err = s.googleDelete(ctx, acc, it)
} else {
err = s.davDelete(ctx, acc, it)
}
if err != nil && !errors.Is(err, errGone) {
return s.writeError(acc, &e, err)
}
if err := s.pb.Delete(ctx, "calendar_events", e.ID); err != nil && !pocketbase.IsNotFound(err) {
return err
}
return nil
}
// ---- CalDAV -----------------------------------------------------------------------
func (s *Service) davBase(acc record) (webdav.HTTPClient, *url.URL, error) {
password, err := s.open(acc.Secret)
if err != nil {
return nil, nil, err
}
u, err := feedURL(acc.URL)
if err != nil {
return nil, nil, err
}
return davClient(s.client, source{kind: acc.Kind, url: acc.URL, username: acc.Username, password: password}), u, nil
}
// davURL resolves a path on the account's server.
func davURL(base *url.URL, path string) string {
return base.ResolveReference(&url.URL{Path: path}).String()
}
// quoteETag writes an ETag as a header wants it; unquoteETag reads one back.
func quoteETag(etag string) string { return strconv.Quote(etag) }
func unquoteETag(h string) string {
h = strings.TrimPrefix(strings.TrimSpace(h), "W/")
if v, err := strconv.Unquote(h); err == nil {
return v
}
return h
}
// davSend sends one request; status 412 is errStale, 404 and 410 errGone.
func davSend(ctx context.Context, hc webdav.HTTPClient, method, u string, body []byte, headers map[string]string) (*http.Response, error) {
var r io.Reader
if body != nil {
r = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, u, r)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
res, err := hc.Do(req)
if err != nil {
return nil, friendly(err)
}
switch {
case res.StatusCode == http.StatusPreconditionFailed:
_ = res.Body.Close()
return nil, errStale
case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusGone:
_ = res.Body.Close()
return nil, errGone
case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden:
_ = res.Body.Close()
return nil, errors.New("the calendar did not let Docwell change it")
case res.StatusCode >= 300:
_ = res.Body.Close()
return nil, fmt.Errorf("the calendar answered %s", res.Status)
}
return res, nil
}
// davPut stores cal at u under the given condition and returns the new ETag
// (read back with a GET when the server does not send it).
func davPut(ctx context.Context, hc webdav.HTTPClient, u string, cal *ical.Calendar, condition map[string]string) (string, error) {
var buf bytes.Buffer
if err := ical.NewEncoder(&buf).Encode(cal); err != nil {
return "", err
}
headers := map[string]string{"Content-Type": ical.MIMEType + "; charset=utf-8"}
for k, v := range condition {
headers[k] = v
}
res, err := davSend(ctx, hc, http.MethodPut, u, buf.Bytes(), headers)
if err != nil {
return "", err
}
_ = res.Body.Close()
if etag := res.Header.Get("ETag"); etag != "" {
return unquoteETag(etag), nil
}
_, etag, err := davGet(ctx, hc, u)
return etag, err
}
// davGet reads one calendar object and its ETag.
func davGet(ctx context.Context, hc webdav.HTTPClient, u string) (*ical.Calendar, string, error) {
res, err := davSend(ctx, hc, http.MethodGet, u, nil, map[string]string{"Accept": ical.MIMEType})
if err != nil {
return nil, "", err
}
defer func() { _ = res.Body.Close() }()
cal, err := ical.NewDecoder(res.Body).Decode()
if err != nil {
return nil, "", fmt.Errorf("the calendar sent an event Docwell cannot read: %w", err)
}
return cal, unquoteETag(res.Header.Get("ETag")), nil
}
// setTimes writes it's times and texts onto a VEVENT.
func setTimes(ev *ical.Component, it item) {
ev.Props.SetText(ical.PropSummary, it.title)
if it.location != "" {
ev.Props.SetText(ical.PropLocation, it.location)
} else {
ev.Props.Del(ical.PropLocation)
}
ev.Props.Del(ical.PropDuration)
if it.allDay {
ev.Props.SetDate(ical.PropDateTimeStart, it.start)
ev.Props.SetDate(ical.PropDateTimeEnd, it.end)
} else {
ev.Props.SetDateTime(ical.PropDateTimeStart, it.start.UTC())
ev.Props.SetDateTime(ical.PropDateTimeEnd, it.end.UTC())
}
now := time.Now().UTC()
ev.Props.SetDateTime(ical.PropDateTimeStamp, now)
ev.Props.SetDateTime(ical.PropLastModified, now)
}
func newUID() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
return hex.EncodeToString(b) + "@docwell"
}
func (s *Service) davCreate(ctx context.Context, acc record, it *item) error {
hc, base, err := s.davBase(acc)
if err != nil {
return err
}
uid := newUID()
ev := ical.NewEvent()
ev.Props.SetText(ical.PropUID, uid)
setTimes(ev.Component, *it)
cal := ical.NewCalendar()
cal.Props.SetText(ical.PropVersion, "2.0")
cal.Props.SetText(ical.PropProductID, "-//Docwell//Calendar//EN")
cal.Children = append(cal.Children, ev.Component)
path := strings.TrimSuffix(it.cal, "/") + "/" + uid + ".ics"
etag, err := davPut(ctx, hc, davURL(base, path), cal, map[string]string{"If-None-Match": "*"})
if err != nil {
if errors.Is(err, errGone) {
return errors.New("the calendar Docwell writes to is gone; pick another in account settings")
}
return err
}
it.ref, it.etag, it.key = path, etag, eventID(uid, it.start)
return nil
}
// davEvent is the one VEVENT of a single event's object.
func davEvent(cal *ical.Calendar) (*ical.Component, error) {
var found *ical.Component
for _, c := range cal.Children {
if c.Name != ical.CompEvent {
continue
}
if found != nil || c.Props.Get(ical.PropRecurrenceID) != nil || c.Props.Get(ical.PropRecurrenceRule) != nil ||
c.Props.Get(ical.PropRecurrenceDates) != nil {
return nil, errors.New("this is a repeating event; change it in its own calendar app")
}
found = c
}
if found == nil {
return nil, errGone
}
return found, nil
}
func (s *Service) davUpdate(ctx context.Context, acc record, it *item) error {
hc, base, err := s.davBase(acc)
if err != nil {
return err
}
u := davURL(base, it.ref)
cal, _, err := davGet(ctx, hc, u)
if err != nil {
return err
}
ev, err := davEvent(cal)
if err != nil {
return err
}
setTimes(ev, *it)
seq := 0
if p := ev.Props.Get(ical.PropSequence); p != nil {
seq, _ = p.Int()
}
sp := ical.NewProp(ical.PropSequence)
sp.Value = strconv.Itoa(seq + 1)
ev.Props.Set(sp)
// The ETag of the last sync, not of the GET: a change made since then
// is refused even if it came in between.
etag, err := davPut(ctx, hc, u, cal, map[string]string{"If-Match": quoteETag(it.etag)})
if err != nil {
return err
}
it.etag = etag
it.key = eventID(propText(ev, ical.PropUID), it.start)
return nil
}
func (s *Service) davDelete(ctx context.Context, acc record, it item) error {
hc, base, err := s.davBase(acc)
if err != nil {
return err
}
res, err := davSend(ctx, hc, http.MethodDelete, davURL(base, it.ref), nil, map[string]string{"If-Match": quoteETag(it.etag)})
if err != nil {
return err
}
return res.Body.Close()
}
// ---- Google -----------------------------------------------------------------------
// googleBody is it as the Calendar API takes it.
func googleBody(it item) map[string]any {
when := func(t time.Time) googleTime {
if it.allDay {
return googleTime{Date: t.Format(time.DateOnly)}
}
return googleTime{DateTime: t.UTC().Format(time.RFC3339)}
}
return map[string]any{
"summary": it.title, "location": it.location, "start": when(it.start), "end": when(it.end),
}
}
func googleEventPath(cal, id string) string {
p := "/calendar/v3/calendars/" + url.PathEscape(cal) + "/events"
if id != "" {
p += "/" + url.PathEscape(id)
}
return p
}
// fromGoogle copies what Google stored back into it.
func fromGoogle(it *item, cal string, e googleEvent) {
if got, ok := e.item(cal); ok {
*it = got
}
}
func (s *Service) googleCreate(ctx context.Context, acc record, it *item) error {
access, err := s.googleAccess(ctx, acc)
if err != nil {
return err
}
var e googleEvent
if err := s.googleDo(ctx, http.MethodPost, access, googleEventPath(it.cal, ""), nil, googleBody(*it), "", &e); err != nil {
if errors.Is(err, errGone) {
return errors.New("the calendar Docwell writes to is gone; pick another in account settings")
}
return err
}
fromGoogle(it, it.cal, e)
return nil
}
func (s *Service) googleUpdate(ctx context.Context, acc record, it *item) error {
access, err := s.googleAccess(ctx, acc)
if err != nil {
return err
}
var e googleEvent
if err := s.googleDo(ctx, http.MethodPatch, access, googleEventPath(it.cal, it.ref), nil, googleBody(*it), it.etag, &e); err != nil {
return err
}
fromGoogle(it, it.cal, e)
return nil
}
func (s *Service) googleDelete(ctx context.Context, acc record, it item) error {
access, err := s.googleAccess(ctx, acc)
if err != nil {
return err
}
return s.googleDo(ctx, http.MethodDelete, access, googleEventPath(it.cal, it.ref), nil, nil, it.etag, nil)
}