Phase F of the AFFiNE plan (ADR-16): - Calendars: people subscribe to iCal feeds (webcal, Google's secret address, Outlook) or CalDAV accounts in account settings; their events show at the top of journal pages in the reader's time zone. Repeats, moved and cancelled occurrences, IANA and Windows zones are handled. Events are read on demand and kept in memory for 15 minutes; passwords are sealed with DOCWELL_SECRET_KEY; sources follow the webhook address rules. New calendar_accounts collection. - Importers: zips of Markdown (Obsidian vaults, Bear TextBundles and .bear2bk, Readwise's Markdown, Docwell's own space export) keep folders as pages, resolve [[wikilinks]] and embeds by name, and turn front matter and #tags into properties and tags. OneNote .mht exports, Readwise CSV, and any other CSV as a database page. - Exports: PNG of a page drawn in the browser, print styles that print only the page in the light theme, and workspace snapshots (records, Yjs states, JSON and files in one zip) that restore as a new workspace. Old ids are swapped byte for byte inside the Yjs updates, so links point at the restored pages and comments stay anchored. - Web-Clipper/: a Manifest V3 extension for Chrome, Edge and Firefox that saves the article or the selection as Markdown through the import API with a personal API token. - OpenAPI, generated clients, translations and user docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
205 lines
5.9 KiB
Go
205 lines
5.9 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-ical"
|
|
"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 the source as iCalendar data (CalDAV objects are joined into
|
|
// one stream of VCALENDARs).
|
|
func fetch(ctx context.Context, client *http.Client, src source) ([]byte, error) {
|
|
u, err := feedURL(src.url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if src.kind == KindCalDAV {
|
|
return fetchCalDAV(ctx, client, u, src)
|
|
}
|
|
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
|
|
}
|
|
|
|
// fetchCalDAV reads the events of the calendar at u, or of every calendar of
|
|
// the account when u is the server or the account's home: a year back and
|
|
// two years ahead.
|
|
func fetchCalDAV(ctx context.Context, client *http.Client, u *url.URL, src source) ([]byte, error) {
|
|
var hc webdav.HTTPClient = &limitedClient{c: client}
|
|
if src.username != "" || src.password != "" {
|
|
hc = webdav.HTTPClientWithBasicAuth(hc, src.username, src.password)
|
|
}
|
|
c, err := caldav.NewClient(hc, u.String())
|
|
if err != nil {
|
|
return 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)},
|
|
}},
|
|
}
|
|
objects, err := c.QueryCalendar(ctx, u.Path, query)
|
|
if err != nil {
|
|
// Not a calendar itself: find the account's calendars.
|
|
paths, err := discover(ctx, c, u)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
objects = nil
|
|
for _, p := range paths {
|
|
got, err := c.QueryCalendar(ctx, p, query)
|
|
if err != nil {
|
|
return nil, friendly(err)
|
|
}
|
|
objects = append(objects, got...)
|
|
}
|
|
}
|
|
var buf bytes.Buffer
|
|
enc := ical.NewEncoder(&buf)
|
|
for _, o := range objects {
|
|
if o.Data == nil {
|
|
continue
|
|
}
|
|
if err := enc.Encode(o.Data); err != nil {
|
|
continue
|
|
}
|
|
if buf.Len() > maxFeed {
|
|
return nil, errors.New("the calendars hold more than 20 MB of events")
|
|
}
|
|
}
|
|
return buf.Bytes(), nil
|
|
}
|
|
|
|
func discover(ctx context.Context, c *caldav.Client, u *url.URL) ([]string, 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 paths []string
|
|
for _, cal := range cals {
|
|
events := len(cal.SupportedComponentSet) == 0
|
|
for _, comp := range cal.SupportedComponentSet {
|
|
events = events || comp == "VEVENT"
|
|
}
|
|
if events {
|
|
paths = append(paths, cal.Path)
|
|
}
|
|
}
|
|
if len(paths) == 0 {
|
|
return nil, errors.New("the CalDAV account has no event calendars")
|
|
}
|
|
return paths, 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)
|
|
}
|