Files
Docwell/Server/internal/calendar/ics.go
T
tajniak81andClaude Opus 5.5 3d1cf362d7 Add calendars, a web clipper, more importers and workspace snapshots
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>
2026-11-16 11:56:03 +01:00

342 lines
10 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package calendar
import (
"errors"
"fmt"
"io"
"sort"
"strings"
"time"
_ "time/tzdata" // Calendars name IANA zones; Windows hosts have no zone files.
"github.com/emersion/go-ical"
"github.com/teambition/rrule-go"
)
// ---- iCalendar: events and their repeats ------------------------------------
// maxPerEvent caps the occurrences one repeating event adds to one query.
const maxPerEvent = 500
// eventDef is one VEVENT: a single event, a repeating one, or a changed
// occurrence of a repeating one (recurrenceID set).
type eventDef struct {
uid, title, location, link string
start time.Time
dur time.Duration
allDay bool
cancelled bool
set *rrule.Set // nil for an event that does not repeat
recurrenceID time.Time
}
// feed is a parsed calendar: its events by UID, with each repeating event's
// changed occurrences.
type feed struct {
events []*eventDef
overrides map[string]map[int64]*eventDef // uid -> original start (unix) -> changed occurrence
}
// zones resolves TZIDs: IANA names, Windows names (Outlook), or a calendar's
// own VTIMEZONE as a fixed offset when nothing else is known.
type zones struct {
defs map[string]*ical.Component
seen map[string]*time.Location
}
func (z *zones) location(tzid string, fallback *time.Location) *time.Location {
if tzid == "" {
return fallback
}
if loc, ok := z.seen[tzid]; ok {
return loc
}
name := strings.Trim(tzid, `"`)
if alias, ok := windowsZones[name]; ok {
name = alias
}
loc, err := time.LoadLocation(name)
if err != nil {
loc = z.fixed(tzid, fallback)
}
z.seen[tzid] = loc
return loc
}
// fixed reads a VTIMEZONE's standard offset ("+0100").
func (z *zones) fixed(tzid string, fallback *time.Location) *time.Location {
tz := z.defs[tzid]
if tz == nil {
return fallback
}
for _, child := range tz.Children {
if child.Name != "STANDARD" && len(tz.Children) > 1 {
continue
}
if p := child.Props.Get("TZOFFSETTO"); p != nil {
if off, ok := parseOffset(p.Value); ok {
return time.FixedZone(tzid, off)
}
}
}
return fallback
}
func parseOffset(v string) (int, bool) {
v = strings.TrimSpace(v)
if len(v) != 5 && len(v) != 7 {
return 0, false
}
sign := 1
switch v[0] {
case '-':
sign = -1
case '+':
default:
return 0, false
}
n := 0
for _, r := range v[1:] {
if r < '0' || r > '9' {
return 0, false
}
n = n*10 + int(r-'0')
}
h, m, s := n/100, n%100, 0
if len(v) == 7 {
h, m, s = n/10000, n/100%100, n%100
}
return sign * (h*3600 + m*60 + s), true
}
// parseFeed reads every VCALENDAR in r. Times without a zone ("floating")
// and all-day dates are read in loc.
func parseFeed(r io.Reader, loc *time.Location) (*feed, error) {
var cals []*ical.Calendar
dec := ical.NewDecoder(r)
for {
cal, err := dec.Decode()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
if len(cals) > 0 {
break // Keep what was read before a broken tail.
}
return nil, fmt.Errorf("not an iCalendar file: %w", err)
}
cals = append(cals, cal)
}
f := &feed{overrides: map[string]map[int64]*eventDef{}}
for _, cal := range cals {
if err := f.add(cal, loc); err != nil {
return nil, err
}
}
return f, nil
}
func (f *feed) add(cal *ical.Calendar, loc *time.Location) error {
z := &zones{defs: map[string]*ical.Component{}, seen: map[string]*time.Location{}}
for _, c := range cal.Children {
if c.Name == ical.CompTimezone {
if id := c.Props.Get(ical.PropTimezoneID); id != nil {
z.defs[id.Value] = c
}
}
}
for _, c := range cal.Children {
if c.Name != ical.CompEvent {
continue
}
e, err := readEvent(c, z, loc)
if err != nil {
continue // One broken event does not hide the rest.
}
if !e.recurrenceID.IsZero() {
if f.overrides[e.uid] == nil {
f.overrides[e.uid] = map[int64]*eventDef{}
}
f.overrides[e.uid][e.recurrenceID.Unix()] = e
continue
}
f.events = append(f.events, e)
}
return nil
}
func propText(c *ical.Component, name string) string {
p := c.Props.Get(name)
if p == nil {
return ""
}
return strings.TrimSpace(p.Value)
}
// dateTime reads a DTSTART-like property: its time, and whether it is a date.
func dateTime(p *ical.Prop, z *zones, loc *time.Location) (time.Time, bool, error) {
value := strings.TrimSpace(p.Value)
isDate := p.ValueType() == ical.ValueDate || (p.ValueType() == ical.ValueDefault && len(value) == 8)
if isDate {
t, err := time.ParseInLocation("20060102", value, loc)
return t, true, err
}
if strings.HasSuffix(value, "Z") {
t, err := time.Parse("20060102T150405Z", value)
return t, false, err
}
t, err := time.ParseInLocation("20060102T150405", value, z.location(p.Params.Get(ical.PropTimezoneID), loc))
return t, false, err
}
func readEvent(c *ical.Component, z *zones, loc *time.Location) (*eventDef, error) {
sp := c.Props.Get(ical.PropDateTimeStart)
if sp == nil {
return nil, fmt.Errorf("event without a start")
}
start, allDay, err := dateTime(sp, z, loc)
if err != nil {
return nil, err
}
e := &eventDef{
uid: propText(c, ical.PropUID), title: unescape(propText(c, ical.PropSummary)),
location: unescape(propText(c, ical.PropLocation)), link: propText(c, ical.PropURL),
start: start, allDay: allDay, cancelled: strings.EqualFold(propText(c, ical.PropStatus), "CANCELLED"),
}
if e.uid == "" {
e.uid = fmt.Sprintf("%s@%d", e.title, start.Unix())
}
switch {
case c.Props.Get(ical.PropDateTimeEnd) != nil:
end, _, err := dateTime(c.Props.Get(ical.PropDateTimeEnd), z, loc)
if err == nil && end.After(start) {
e.dur = end.Sub(start)
}
case c.Props.Get(ical.PropDuration) != nil:
if d, err := c.Props.Get(ical.PropDuration).Duration(); err == nil && d > 0 {
e.dur = d
}
}
if e.dur == 0 && allDay {
e.dur = 24 * time.Hour
}
if rp := c.Props.Get(ical.PropRecurrenceID); rp != nil {
if e.recurrenceID, _, err = dateTime(rp, z, loc); err != nil {
return nil, err
}
}
rules := c.Props.Values(ical.PropRecurrenceRule)
rdates := c.Props.Values(ical.PropRecurrenceDates)
if len(rules) == 0 && len(rdates) == 0 {
return e, nil
}
set := &rrule.Set{}
set.DTStart(start)
for _, rp := range rules {
opt, err := rrule.StrToROptionInLocation(rp.Value, start.Location())
if err != nil {
return nil, err
}
opt.Dtstart = start
r, err := rrule.NewRRule(*opt)
if err != nil {
return nil, err
}
set.RRule(r)
}
each := func(props []ical.Prop, fn func(time.Time)) {
for _, p := range props {
for _, v := range strings.Split(p.Value, ",") {
one := p
one.Value = v
if t, _, err := dateTime(&one, z, start.Location()); err == nil {
fn(t)
}
}
}
}
each(rdates, set.RDate)
each(c.Props.Values(ical.PropExceptionDates), set.ExDate)
e.set = set
return e, nil
}
// unescape undoes the escapes of iCalendar TEXT values.
func unescape(s string) string {
return strings.NewReplacer(`\n`, "\n", `\N`, "\n", `\,`, ",", `\;`, ";", `\\`, `\`).Replace(s)
}
// occurrence is one time an event happens.
type occurrence struct {
def *eventDef
start, end time.Time
}
// between lists the occurrences that overlap [from, to), in time order.
func (f *feed) between(from, to time.Time) []occurrence {
var out []occurrence
overlaps := func(start, end time.Time) bool {
if !end.After(start) {
end = start.Add(time.Second) // A moment, like a reminder.
}
return start.Before(to) && end.After(from)
}
for _, e := range f.events {
changed := f.overrides[e.uid]
if e.set == nil {
if !e.cancelled && overlaps(e.start, e.start.Add(e.dur)) {
out = append(out, occurrence{e, e.start, e.start.Add(e.dur)})
}
continue
}
times := e.set.Between(from.Add(-e.dur), to, true)
if len(times) > maxPerEvent {
times = times[:maxPerEvent]
}
for _, t := range times {
if _, moved := changed[t.Unix()]; moved || e.cancelled {
continue
}
if overlaps(t, t.Add(e.dur)) {
out = append(out, occurrence{e, t, t.Add(e.dur)})
}
}
}
// Changed occurrences stand on their own: they may have moved into or out
// of the range, or been cancelled.
for _, byTime := range f.overrides {
for _, o := range byTime {
if !o.cancelled && overlaps(o.start, o.start.Add(o.dur)) {
out = append(out, occurrence{o, o.start, o.start.Add(o.dur)})
}
}
}
sort.SliceStable(out, func(i, j int) bool {
if !out[i].start.Equal(out[j].start) {
return out[i].start.Before(out[j].start)
}
return out[i].def.title < out[j].def.title
})
return out
}
// windowsZones maps the Windows zone names Outlook and Exchange write to IANA.
var windowsZones = map[string]string{
"UTC": "UTC", "GMT Standard Time": "Europe/London", "Greenwich Standard Time": "Atlantic/Reykjavik",
"W. Europe Standard Time": "Europe/Berlin", "Central Europe Standard Time": "Europe/Budapest",
"Central European Standard Time": "Europe/Warsaw", "Romance Standard Time": "Europe/Paris",
"E. Europe Standard Time": "Europe/Chisinau", "FLE Standard Time": "Europe/Kiev", "GTB Standard Time": "Europe/Bucharest",
"Russian Standard Time": "Europe/Moscow", "Turkey Standard Time": "Europe/Istanbul", "Israel Standard Time": "Asia/Jerusalem",
"South Africa Standard Time": "Africa/Johannesburg", "Arabian Standard Time": "Asia/Dubai", "India Standard Time": "Asia/Kolkata",
"China Standard Time": "Asia/Shanghai", "Tokyo Standard Time": "Asia/Tokyo", "Korea Standard Time": "Asia/Seoul",
"Singapore Standard Time": "Asia/Singapore", "AUS Eastern Standard Time": "Australia/Sydney",
"New Zealand Standard Time": "Pacific/Auckland", "Eastern Standard Time": "America/New_York",
"Central Standard Time": "America/Chicago", "Mountain Standard Time": "America/Denver", "US Mountain Standard Time": "America/Phoenix",
"Pacific Standard Time": "America/Los_Angeles", "Alaskan Standard Time": "America/Anchorage", "Hawaiian Standard Time": "Pacific/Honolulu",
"Atlantic Standard Time": "America/Halifax", "E. South America Standard Time": "America/Sao_Paulo",
"Argentina Standard Time": "America/Buenos_Aires", "Mexico Standard Time": "America/Mexico_City",
"Central America Standard Time": "America/Guatemala", "SA Pacific Standard Time": "America/Bogota",
}