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>
228 lines
6.7 KiB
Go
228 lines
6.7 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package calendar
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/emersion/go-webdav"
|
|
"github.com/emersion/go-webdav/caldav"
|
|
)
|
|
|
|
// maxFeed caps what one account's source may send.
|
|
const maxFeed = 20 << 20
|
|
|
|
// source is where an account's events come from.
|
|
type source struct {
|
|
kind, url, username, password string
|
|
}
|
|
|
|
// feedURL turns webcal:// (how calendar apps share feeds) into https://.
|
|
func feedURL(raw string) (*url.URL, error) {
|
|
raw = strings.TrimSpace(raw)
|
|
if rest, ok := strings.CutPrefix(raw, "webcal://"); ok {
|
|
raw = "https://" + rest
|
|
} else if rest, ok := strings.CutPrefix(raw, "webcals://"); ok {
|
|
raw = "https://" + rest
|
|
}
|
|
u, err := url.Parse(raw)
|
|
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
|
return nil, errors.New("enter an http, https or webcal address")
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
// fetch reads an iCalendar feed.
|
|
func fetch(ctx context.Context, client *http.Client, src source) ([]byte, error) {
|
|
u, err := feedURL(src.url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Accept", "text/calendar, */*;q=0.5")
|
|
req.Header.Set("User-Agent", "Docwell calendar")
|
|
if src.username != "" || src.password != "" {
|
|
req.SetBasicAuth(src.username, src.password)
|
|
}
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, friendly(err)
|
|
}
|
|
defer func() { _ = res.Body.Close() }()
|
|
switch {
|
|
case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden:
|
|
return nil, errors.New("the calendar refused the user name or password")
|
|
case res.StatusCode == http.StatusNotFound:
|
|
return nil, errors.New("no calendar at this address (404)")
|
|
case res.StatusCode >= 300:
|
|
return nil, fmt.Errorf("the calendar answered %s", res.Status)
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(res.Body, maxFeed+1))
|
|
if err != nil {
|
|
return nil, friendly(err)
|
|
}
|
|
if len(data) > maxFeed {
|
|
return nil, errors.New("the calendar is larger than 20 MB")
|
|
}
|
|
if !bytes.Contains(data[:min(len(data), 4096)], []byte("BEGIN:VCALENDAR")) {
|
|
return nil, errors.New("the address does not serve an iCalendar (.ics) file")
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
// davClient is an HTTP client for a CalDAV account: answers capped, signed
|
|
// in with the account's user name and password.
|
|
func davClient(client *http.Client, src source) webdav.HTTPClient {
|
|
var hc webdav.HTTPClient = &limitedClient{c: client}
|
|
if src.username != "" || src.password != "" {
|
|
hc = webdav.HTTPClientWithBasicAuth(hc, src.username, src.password)
|
|
}
|
|
return hc
|
|
}
|
|
|
|
// davObject is one CalDAV object and the calendar collection it is in.
|
|
type davObject struct {
|
|
cal string
|
|
obj caldav.CalendarObject
|
|
}
|
|
|
|
// fetchCalDAV reads the events of the calendar at src.url, or of every
|
|
// calendar of the account when it is the server or the account's home: a
|
|
// year back and two years ahead. It also lists the calendars, the ones new
|
|
// events can go to.
|
|
func fetchCalDAV(ctx context.Context, client *http.Client, src source) ([]davObject, []Target, error) {
|
|
u, err := feedURL(src.url)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
c, err := caldav.NewClient(davClient(client, src), u.String())
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
now := time.Now()
|
|
query := &caldav.CalendarQuery{
|
|
CompRequest: caldav.CalendarCompRequest{Name: "VCALENDAR", AllProps: true, AllComps: true},
|
|
CompFilter: caldav.CompFilter{Name: "VCALENDAR", Comps: []caldav.CompFilter{
|
|
{Name: "VEVENT", Start: now.AddDate(-1, 0, 0), End: now.AddDate(2, 0, 0)},
|
|
}},
|
|
}
|
|
// Each answer is capped at 20 MB (limitedClient).
|
|
var out []davObject
|
|
keep := func(cal string, objects []caldav.CalendarObject) error {
|
|
for _, o := range objects {
|
|
if o.Data == nil {
|
|
continue
|
|
}
|
|
if len(out) >= 4*maxStored {
|
|
return errors.New("the calendars hold too many events")
|
|
}
|
|
out = append(out, davObject{cal: cal, obj: o})
|
|
}
|
|
return nil
|
|
}
|
|
collection := strings.TrimSuffix(u.Path, "/") + "/"
|
|
objects, err := c.QueryCalendar(ctx, u.Path, query)
|
|
if err == nil {
|
|
return out, []Target{{ID: collection, Name: ""}}, keep(collection, objects)
|
|
}
|
|
// Not a calendar itself: find the account's calendars.
|
|
cals, err := discover(ctx, c, u)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
var targets []Target
|
|
for _, cal := range cals {
|
|
path := strings.TrimSuffix(cal.Path, "/") + "/"
|
|
got, err := c.QueryCalendar(ctx, cal.Path, query)
|
|
if err != nil {
|
|
return nil, nil, friendly(err)
|
|
}
|
|
if err := keep(path, got); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
name := strings.TrimSpace(cal.Name)
|
|
if name == "" {
|
|
name = path
|
|
}
|
|
targets = append(targets, Target{ID: path, Name: name})
|
|
}
|
|
return out, targets, nil
|
|
}
|
|
|
|
func discover(ctx context.Context, c *caldav.Client, u *url.URL) ([]caldav.Calendar, error) {
|
|
principal, err := c.FindCurrentUserPrincipal(ctx)
|
|
if err != nil {
|
|
return nil, friendly(fmt.Errorf("no CalDAV account at this address: %w", err))
|
|
}
|
|
home, err := c.FindCalendarHomeSet(ctx, principal)
|
|
if err != nil {
|
|
return nil, friendly(fmt.Errorf("the CalDAV account lists no calendars: %w", err))
|
|
}
|
|
cals, err := c.FindCalendars(ctx, home)
|
|
if err != nil {
|
|
return nil, friendly(err)
|
|
}
|
|
var out []caldav.Calendar
|
|
for _, cal := range cals {
|
|
events := len(cal.SupportedComponentSet) == 0
|
|
for _, comp := range cal.SupportedComponentSet {
|
|
events = events || comp == "VEVENT"
|
|
}
|
|
if events {
|
|
out = append(out, cal)
|
|
}
|
|
}
|
|
if len(out) == 0 {
|
|
return nil, errors.New("the CalDAV account has no event calendars")
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// limitedClient caps every CalDAV answer.
|
|
type limitedClient struct{ c *http.Client }
|
|
|
|
func (l *limitedClient) Do(req *http.Request) (*http.Response, error) {
|
|
req.Header.Set("User-Agent", "Docwell calendar")
|
|
// The address is the person's own calendar; the dialer refuses loopback and
|
|
// link-local addresses (webhooks.Guard).
|
|
res, err := l.c.Do(req) //nolint:gosec // see above
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
res.Body = struct {
|
|
io.Reader
|
|
io.Closer
|
|
}{io.LimitReader(res.Body, maxFeed+1), res.Body}
|
|
return res, nil
|
|
}
|
|
|
|
// friendly shortens network errors for people.
|
|
func friendly(err error) error {
|
|
msg := err.Error()
|
|
switch {
|
|
case strings.Contains(msg, "address not allowed"):
|
|
return errors.New("this server may not reach that address")
|
|
case strings.Contains(msg, "no such host"):
|
|
return errors.New("the calendar's server name is unknown")
|
|
case strings.Contains(msg, "deadline exceeded") || strings.Contains(msg, "Timeout"):
|
|
return errors.New("the calendar did not answer in time")
|
|
case strings.Contains(msg, "401"):
|
|
return errors.New("the calendar refused the user name or password")
|
|
}
|
|
if len(msg) > 300 {
|
|
msg = msg[:300]
|
|
}
|
|
return errors.New(msg)
|
|
}
|