Files
pages/internal/calendar/external_feed.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

720 lines
25 KiB
Go

package calendar
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"sort"
"strconv"
"strings"
"time"
_ "time/tzdata"
"unicode/utf8"
ical "github.com/emersion/go-ical"
"github.com/teambition/rrule-go"
)
type feedTransition struct {
wall time.Time
offset int
}
type feedZone struct {
id string
location *time.Location
transitions []feedTransition
fallback int
}
func validateExternalRule(option *rrule.ROption, timezone bool) error {
if timezone && option.Freq != rrule.YEARLY {
return fmt.Errorf("%w: VTIMEZONE recurrence must be yearly", ErrInvalid)
}
if option.Freq > rrule.DAILY || len(option.Byhour) > 0 || len(option.Byminute) > 0 || len(option.Bysecond) > 0 {
return fmt.Errorf("%w: sub-daily or expanded-time RRULE is not supported", ErrInvalid)
}
return nil
}
var windowsZones = map[string]string{
"UTC": "UTC", "Tokyo Standard Time": "Asia/Tokyo",
"Korea Standard Time": "Asia/Seoul", "China Standard Time": "Asia/Shanghai",
"Singapore Standard Time": "Asia/Singapore", "India Standard Time": "Asia/Kolkata",
"GMT Standard Time": "Europe/London", "W. Europe Standard Time": "Europe/Berlin",
"Central Europe Standard Time": "Europe/Budapest", "Romance Standard Time": "Europe/Paris",
"Eastern Standard Time": "America/New_York", "Central Standard Time": "America/Chicago",
"Mountain Standard Time": "America/Denver", "Pacific Standard Time": "America/Los_Angeles",
"AUS Eastern Standard Time": "Australia/Sydney", "New Zealand Standard Time": "Pacific/Auckland",
}
func parseWall(value string) (time.Time, error) {
value = strings.TrimSuffix(value, "Z")
layout := "20060102T150405"
if len(value) == 8 {
layout = "20060102"
}
return time.ParseInLocation(layout, value, time.UTC)
}
func parseUTCOffset(raw string) (int, error) {
if len(raw) != 5 && len(raw) != 7 || raw[0] != '+' && raw[0] != '-' {
return 0, fmt.Errorf("%w: invalid TZOFFSET", ErrInvalid)
}
h, e1 := strconv.Atoi(raw[1:3])
m, e2 := strconv.Atoi(raw[3:5])
s := 0
var e3 error
if len(raw) == 7 {
s, e3 = strconv.Atoi(raw[5:7])
}
if e1 != nil || e2 != nil || e3 != nil || h > 23 || m > 59 || s > 59 {
return 0, fmt.Errorf("%w: invalid TZOFFSET", ErrInvalid)
}
seconds := h*3600 + m*60 + s
if raw[0] == '-' {
seconds = -seconds
}
return seconds, nil
}
func zoneName(raw string) string { return strings.Trim(strings.TrimSpace(raw), `"`) }
func buildFeedZones(cal *ical.Calendar, from, to time.Time) (map[string]*feedZone, error) {
zones := map[string]*feedZone{}
for _, child := range cal.Children {
if child.Name != "VTIMEZONE" {
continue
}
id, e := child.Props.Text("TZID")
id = zoneName(id)
if e != nil || id == "" || len(id) > 256 || zones[id] != nil {
return nil, fmt.Errorf("%w: invalid or duplicate VTIMEZONE TZID", ErrInvalid)
}
zone := &feedZone{id: id}
iana := id
if mapped := windowsZones[id]; mapped != "" {
iana = mapped
}
if loc, err := time.LoadLocation(iana); err == nil {
zone.location = loc
zones[id] = zone
continue
}
for _, observance := range child.Children {
if observance.Name != "STANDARD" && observance.Name != "DAYLIGHT" {
return nil, fmt.Errorf("%w: unsupported VTIMEZONE component %s", ErrInvalid, observance.Name)
}
startProp, offsetProp := observance.Props.Get("DTSTART"), observance.Props.Get("TZOFFSETTO")
if startProp == nil || offsetProp == nil {
return nil, fmt.Errorf("%w: incomplete VTIMEZONE observance", ErrInvalid)
}
base, err := parseWall(startProp.Value)
if err != nil {
return nil, fmt.Errorf("%w: invalid VTIMEZONE DTSTART", ErrInvalid)
}
offset, err := parseUTCOffset(offsetProp.Value)
if err != nil {
return nil, err
}
if len(zone.transitions) == 0 || base.Before(zone.transitions[0].wall) {
zone.fallback = offset
}
if observance.Props.Get("RDATE") != nil {
return nil, fmt.Errorf("%w: VTIMEZONE RDATE is not yet supported", ErrInvalid)
}
if rule := observance.Props.Get("RRULE"); rule != nil {
option, err := rrule.StrToROption(rule.Value)
if err != nil {
return nil, fmt.Errorf("%w: invalid VTIMEZONE RRULE", ErrInvalid)
}
if err = validateExternalRule(option, true); err != nil {
return nil, err
}
option.Dtstart = base
r, err := rrule.NewRRule(*option)
if err != nil {
return nil, fmt.Errorf("%w: invalid VTIMEZONE RRULE", ErrInvalid)
}
for _, occurrence := range r.Between(from.AddDate(-2, 0, 0), to.AddDate(2, 0, 0), true) {
zone.transitions = append(zone.transitions, feedTransition{wall: occurrence, offset: offset})
}
} else {
zone.transitions = append(zone.transitions, feedTransition{wall: base, offset: offset})
}
}
if len(zone.transitions) == 0 {
return nil, fmt.Errorf("%w: empty VTIMEZONE", ErrInvalid)
}
sort.Slice(zone.transitions, func(i, j int) bool { return zone.transitions[i].wall.Before(zone.transitions[j].wall) })
zones[id] = zone
}
return zones, nil
}
func (z *feedZone) resolve(wall time.Time) time.Time {
if z.location != nil {
return time.Date(wall.Year(), wall.Month(), wall.Day(), wall.Hour(), wall.Minute(), wall.Second(), wall.Nanosecond(), z.location)
}
offset := z.fallback
for _, transition := range z.transitions {
if transition.wall.After(wall) {
break
}
offset = transition.offset
}
return time.Date(wall.Year(), wall.Month(), wall.Day(), wall.Hour(), wall.Minute(), wall.Second(), wall.Nanosecond(), time.FixedZone(z.id, offset))
}
func feedTime(prop *ical.Prop, zones map[string]*feedZone) (time.Time, time.Time, bool, error) {
if prop == nil {
return time.Time{}, time.Time{}, false, fmt.Errorf("%w: missing date property", ErrInvalid)
}
wall, err := parseWall(prop.Value)
if err != nil {
return time.Time{}, time.Time{}, false, fmt.Errorf("%w: invalid %s", ErrInvalid, prop.Name)
}
allDay := prop.ValueType() == ical.ValueDate
if allDay {
return wall, wall, true, nil
}
if strings.HasSuffix(prop.Value, "Z") {
return wall, wall, false, nil
}
tzid := zoneName(prop.Params.Get("TZID"))
if tzid == "" {
return time.Time{}, time.Time{}, false, fmt.Errorf("%w: floating %s has no TZID", ErrInvalid, prop.Name)
}
zone := zones[tzid]
if zone == nil {
iana := tzid
if mapped := windowsZones[tzid]; mapped != "" {
iana = mapped
}
loc, e := time.LoadLocation(iana)
if e != nil {
return time.Time{}, time.Time{}, false, fmt.Errorf("%w: unknown TZID %q", ErrInvalid, tzid)
}
zone = &feedZone{id: tzid, location: loc}
zones[tzid] = zone
}
return zone.resolve(wall).UTC(), wall, false, nil
}
func sanitizeExternalPropertyValue(value string) (string, bool) {
changed := false
var cleaned strings.Builder
for _, r := range value {
if r < 32 && r != '\t' || r == 127 || r >= 0x80 && r <= 0x9f {
changed = true
continue
}
cleaned.WriteRune(r)
}
return cleaned.String(), changed
}
func cloneExternalEvent(source *ical.Component) (*ical.Component, bool) {
dst := ical.NewComponent("VEVENT")
sanitized := false
for name, values := range source.Props {
for _, value := range values {
p := ical.NewProp(name)
cleaned, changed := sanitizeExternalPropertyValue(value.Value)
p.Value = cleaned
sanitized = sanitized || changed
for key, params := range value.Params {
for _, param := range params {
cleaned, changed := sanitizeExternalPropertyValue(param)
sanitized = sanitized || changed
p.Params.Add(key, cleaned)
}
}
dst.Props.Add(p)
}
}
return dst, sanitized
}
func occurrenceUID(uid string, wall time.Time) string {
suffix := "#" + wall.Format("20060102T150405")
if len(uid)+len(suffix) <= 512 {
return uid + suffix
}
sum := sha256.Sum256([]byte(uid + suffix))
return "recurrence-" + hex.EncodeToString(sum[:])
}
func materializeExternal(source *ical.Component, uid string, start, end time.Time, allDay, recurring bool, wall time.Time, zones map[string]*feedZone) (Event, error) {
dst, sanitized := cloneExternalEvent(source)
for _, name := range []string{"RRULE", "RDATE", "EXDATE", "RECURRENCE-ID", "DURATION"} {
dst.Props.Del(name)
}
if recurring {
dst.Props.SetText("X-PAGESWIKI-SOURCE-UID", uid)
uid = occurrenceUID(uid, wall)
}
dst.Props.SetText("UID", uid)
if sanitized {
dst.Props.SetText("X-PAGESWIKI-SANITIZED", "CONTROL-CHARACTER")
}
for _, pair := range []struct {
name string
time time.Time
}{{"DTSTART", start}, {"DTEND", end}} {
if pair.name == "DTEND" && !end.After(start) {
dst.Props.Del("DTEND")
continue
}
p := ical.NewProp(pair.name)
if allDay {
p.SetDate(pair.time.UTC())
} else {
p.SetDateTime(pair.time.UTC())
}
dst.Props.Set(p)
}
for _, name := range []string{"DTSTAMP", "CREATED", "LAST-MODIFIED"} {
p := dst.Props.Get(name)
if p == nil {
continue
}
value, _, date, err := feedTime(p, zones)
if err != nil || date {
return Event{}, fmt.Errorf("%w: invalid %s", ErrInvalid, name)
}
p = ical.NewProp(name)
p.SetDateTime(value.UTC())
dst.Props.Set(p)
}
data, err := encode(envelope(dst))
if err != nil {
return Event{}, err
}
return Parse(data)
}
type externalEventTimes struct {
start, end time.Time
startWall, endWall time.Time
allDay bool
}
func externalTimes(child *ical.Component, zones map[string]*feedZone) (externalEventTimes, error) {
start, startWall, allDay, err := feedTime(child.Props.Get("DTSTART"), zones)
if err != nil {
return externalEventTimes{}, err
}
microsoftAllDay := false
if prop := child.Props.Get("X-MICROSOFT-CDO-ALLDAYEVENT"); prop != nil {
microsoftAllDay = strings.EqualFold(strings.TrimSpace(prop.Value), "TRUE")
}
if microsoftAllDay && !allDay {
if startWall.Hour() != 0 || startWall.Minute() != 0 || startWall.Second() != 0 {
return externalEventTimes{}, fmt.Errorf("%w: Microsoft all-day DTSTART is not midnight", ErrInvalid)
}
allDay, start = true, startWall
}
end, endWall := start, startWall
if p := child.Props.Get("DTEND"); p != nil {
var endAllDay bool
end, endWall, endAllDay, err = feedTime(p, zones)
if err != nil {
return externalEventTimes{}, err
}
if microsoftAllDay && !endAllDay {
if endWall.Hour() != 0 || endWall.Minute() != 0 || endWall.Second() != 0 {
return externalEventTimes{}, fmt.Errorf("%w: Microsoft all-day DTEND is not midnight", ErrInvalid)
}
endAllDay, end = true, endWall
}
if endAllDay != allDay {
return externalEventTimes{}, fmt.Errorf("%w: invalid DTEND (value type differs from DTSTART)", ErrInvalid)
}
// RFC 5545 defines DTEND as an exclusive boundary. Outlook feeds in
// the wild nevertheless emit DTSTART == DTEND for zero-duration timed
// appointments and, occasionally, for a one-day Microsoft all-day
// appointment. Preserve the former as an instantaneous event (the
// canonical encoder omits DTEND) and normalize only the latter to the
// required exclusive next-day boundary.
if end.Equal(start) && allDay {
end, endWall = start.AddDate(0, 0, 1), startWall.AddDate(0, 0, 1)
} else if end.Before(start) {
return externalEventTimes{}, fmt.Errorf("%w: invalid DTEND (precedes DTSTART)", ErrInvalid)
}
} else if allDay {
end, endWall = start.AddDate(0, 0, 1), startWall.AddDate(0, 0, 1)
}
return externalEventTimes{start: start, end: end, startWall: startWall, endWall: endWall, allDay: allDay}, nil
}
func occurrenceKey(value time.Time, allDay bool) string {
if allDay {
return "D:" + value.Format("20060102")
}
return "T:" + value.UTC().Format("20060102T150405Z")
}
type externalDateValue struct {
instant time.Time
wall time.Time
}
func externalDateList(props []ical.Prop, reference *ical.Prop, zones map[string]*feedZone, allDay bool, property string) ([]externalDateValue, error) {
result := []externalDateValue{}
for _, original := range props {
if original.ValueType() == ical.ValuePeriod || strings.Contains(original.Value, "/") {
return nil, fmt.Errorf("%w: %s PERIOD is not supported", ErrInvalid, property)
}
for _, value := range strings.Split(original.Value, ",") {
p := ical.NewProp(property)
p.Value = strings.TrimSpace(value)
for key, values := range original.Params {
for _, value := range values {
p.Params.Add(key, value)
}
}
if p.Params.Get("TZID") == "" && !strings.HasSuffix(p.Value, "Z") && len(p.Value) != 8 && reference != nil && reference.Params.Get("TZID") != "" {
p.Params.Set("TZID", reference.Params.Get("TZID"))
}
if len(p.Value) == 8 {
p.SetValueType(ical.ValueDate)
}
instant, wall, date, err := feedTime(p, zones)
if err != nil || date != allDay {
return nil, fmt.Errorf("%w: invalid %s", ErrInvalid, property)
}
result = append(result, externalDateValue{instant: instant, wall: wall})
}
}
return result, nil
}
func externalOccurrenceBounds(child *ical.Component, base externalEventTimes, wall time.Time, zones map[string]*feedZone) (time.Time, time.Time, error) {
startProp := child.Props.Get("DTSTART")
start := wall.UTC()
if !base.allDay && !strings.HasSuffix(startProp.Value, "Z") {
zone := zones[zoneName(startProp.Params.Get("TZID"))]
if zone == nil {
return time.Time{}, time.Time{}, fmt.Errorf("%w: unresolved recurrence TZID", ErrInvalid)
}
start = zone.resolve(wall).UTC()
}
duration := base.endWall.Sub(base.startWall)
if duration == 0 {
return start, start, nil
}
endWall := wall.Add(duration)
endProp := child.Props.Get("DTEND")
if base.allDay || endProp != nil && strings.HasSuffix(endProp.Value, "Z") {
return start, endWall.UTC(), nil
}
if endProp == nil {
return time.Time{}, time.Time{}, fmt.Errorf("%w: recurring duration is not supported", ErrInvalid)
}
zone := zones[zoneName(endProp.Params.Get("TZID"))]
if zone == nil {
return time.Time{}, time.Time{}, fmt.Errorf("%w: unresolved recurrence DTEND TZID", ErrInvalid)
}
return start, zone.resolve(endWall).UTC(), nil
}
func externalCancelled(child *ical.Component) bool {
status, _ := child.Props.Text("STATUS")
return strings.EqualFold(status, "CANCELLED")
}
type externalException struct {
component *ical.Component
wall time.Time
allDay bool
}
type externalOccurrence struct {
wall time.Time
direct *time.Time
}
type externalGroup struct {
uid string
master *ical.Component
exceptions map[string]externalException
}
// ParseExternalFeed converts a bounded subscription projection into the
// strict UTC/DATE representation used by the canonical calendar store.
func ParseExternalFeed(data []byte, from, to time.Time) ([]Event, error) {
if len(data) > MaxFeed || !to.After(from) || to.Sub(from) > 370*24*time.Hour {
return nil, ErrLimit
}
if !utf8.Valid(data) || strings.ContainsRune(string(data), 0) {
return nil, fmt.Errorf("%w: invalid subscription encoding", ErrInvalid)
}
dec := ical.NewDecoder(strings.NewReader(string(data)))
cal, err := dec.Decode()
if err != nil {
return nil, fmt.Errorf("%w: malformed VCALENDAR", ErrInvalid)
}
if _, err = dec.Decode(); err != io.EOF {
return nil, fmt.Errorf("%w: one VCALENDAR required", ErrInvalid)
}
version, _ := cal.Props.Text("VERSION")
product, _ := cal.Props.Text("PRODID")
method, _ := cal.Props.Text("METHOD")
if len(cal.Props["VERSION"]) != 1 || version != "2.0" || len(cal.Props["PRODID"]) != 1 || product == "" || len(cal.Props["METHOD"]) > 1 || method != "" && !strings.EqualFold(method, "PUBLISH") {
return nil, fmt.Errorf("%w: invalid subscription envelope", ErrInvalid)
}
if scale := cal.Props.Get("CALSCALE"); scale != nil && !strings.EqualFold(scale.Value, "GREGORIAN") {
return nil, fmt.Errorf("%w: unsupported calendar scale", ErrInvalid)
}
zones, err := buildFeedZones(cal, from, to)
if err != nil {
return nil, err
}
groups := map[string]*externalGroup{}
groupOrder := []string{}
for index, child := range cal.Children {
if child.Name == "VTIMEZONE" {
continue
}
if child.Name != "VEVENT" {
return nil, fmt.Errorf("%w: unsupported subscription component %s", ErrInvalid, child.Name)
}
if len(child.Children) > 0 {
return nil, fmt.Errorf("%w: VEVENT %d subcomponents are not yet supported", ErrInvalid, index+1)
}
cancelled := externalCancelled(child)
for _, name := range []string{"UID", "DTSTAMP"} {
if len(child.Props[name]) != 1 {
return nil, fmt.Errorf("%w: VEVENT %d %s must occur exactly once", ErrInvalid, index+1, name)
}
}
if len(child.Props["DTSTART"]) != 1 && !(cancelled && len(child.Props["RECURRENCE-ID"]) == 1) {
return nil, fmt.Errorf("%w: VEVENT %d DTSTART must occur exactly once", ErrInvalid, index+1)
}
if len(child.Props["DTEND"]) > 1 || len(child.Props["RRULE"]) > 1 || child.Props.Get("DURATION") != nil {
return nil, fmt.Errorf("%w: VEVENT %d unsupported or duplicate event duration", ErrInvalid, index+1)
}
uid, err := child.Props.Text("UID")
if err != nil || uid == "" || len(uid) > 512 {
return nil, fmt.Errorf("%w: VEVENT %d invalid UID", ErrInvalid, index+1)
}
if cleaned, changed := sanitizeExternalPropertyValue(uid); changed || cleaned != uid {
return nil, fmt.Errorf("%w: VEVENT %d invalid UID", ErrInvalid, index+1)
}
group := groups[uid]
if group == nil {
group = &externalGroup{uid: uid, exceptions: map[string]externalException{}}
groups[uid] = group
groupOrder = append(groupOrder, uid)
}
recurrenceID := child.Props.Get("RECURRENCE-ID")
if recurrenceID == nil {
if group.master != nil {
return nil, fmt.Errorf("%w: duplicate master VEVENT", ErrInvalid)
}
group.master = child
continue
}
if len(child.Props["RECURRENCE-ID"]) != 1 || recurrenceID.Params.Get("RANGE") != "" || child.Props.Get("RRULE") != nil || child.Props.Get("RDATE") != nil || child.Props.Get("EXDATE") != nil {
return nil, fmt.Errorf("%w: unsupported RECURRENCE-ID form", ErrInvalid)
}
instant, wall, date, err := feedTime(recurrenceID, zones)
if err != nil {
return nil, fmt.Errorf("%w: invalid RECURRENCE-ID", ErrInvalid)
}
key := occurrenceKey(instant, date)
if _, exists := group.exceptions[key]; exists {
return nil, fmt.Errorf("%w: duplicate RECURRENCE-ID", ErrInvalid)
}
group.exceptions[key] = externalException{component: child, wall: wall, allDay: date}
}
result := []Event{}
seen := map[string]bool{}
totalMaterialized := 0
appendEvent := func(event Event) error {
if seen[event.UID] {
return fmt.Errorf("%w: duplicate materialized UID", ErrInvalid)
}
seen[event.UID] = true
totalMaterialized += len(event.Data)
if totalMaterialized > MaxFeed || len(result) >= 5000 {
return ErrLimit
}
result = append(result, event)
return nil
}
for groupIndex, uid := range groupOrder {
group := groups[uid]
if group.master == nil {
// Some subscription projections (notably Outlook published ICS)
// contain only modified instances and omit the series master. A
// non-cancelled exception is still a complete VEVENT when it has
// DTSTART; project it as a stable single occurrence. Without the
// master an omitted DTEND cannot inherit a duration and therefore
// remains a zero-duration event.
keys := make([]string, 0, len(group.exceptions))
for key := range group.exceptions {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
exception := group.exceptions[key]
if externalCancelled(exception.component) {
continue
}
times, e := externalTimes(exception.component, zones)
if e != nil {
return nil, fmt.Errorf("VEVENT group %d orphan recurrence exception timing validation failed: %w", groupIndex+1, e)
}
if exception.allDay != times.allDay {
return nil, fmt.Errorf("%w: orphan RECURRENCE-ID value type differs from DTSTART", ErrInvalid)
}
if !(times.start.Before(to) && (times.end.After(from) || times.end.Equal(times.start) && !times.start.Before(from))) {
continue
}
event, e := materializeExternal(exception.component, uid, times.start, times.end, times.allDay, true, exception.wall, zones)
if e != nil {
return nil, e
}
if e = appendEvent(event); e != nil {
return nil, e
}
}
continue
}
if externalCancelled(group.master) {
continue
}
base, err := externalTimes(group.master, zones)
if err != nil {
return nil, fmt.Errorf("VEVENT group %d master timing validation failed: %w", groupIndex+1, err)
}
duration := base.endWall.Sub(base.startWall)
rule := group.master.Props.Get("RRULE")
recurring := rule != nil || len(group.master.Props["RDATE"]) > 0 || len(group.exceptions) > 0
occurrences := []externalOccurrence{{wall: base.startWall}}
if rule != nil {
option, e := rrule.StrToROption(rule.Value)
if e != nil {
return nil, fmt.Errorf("%w: invalid RRULE", ErrInvalid)
}
if e = validateExternalRule(option, false); e != nil {
return nil, e
}
option.Dtstart = base.startWall
r, e := rrule.NewRRule(*option)
if e != nil {
return nil, fmt.Errorf("%w: invalid RRULE", ErrInvalid)
}
walls := r.Between(from.Add(-duration-48*time.Hour), to.Add(48*time.Hour), true)
occurrences = make([]externalOccurrence, 0, len(walls))
for _, wall := range walls {
occurrences = append(occurrences, externalOccurrence{wall: wall})
}
}
rdates, err := externalDateList(group.master.Props["RDATE"], group.master.Props.Get("DTSTART"), zones, base.allDay, "RDATE")
if err != nil {
return nil, err
}
for _, value := range rdates {
start := value.instant
occurrences = append(occurrences, externalOccurrence{wall: value.wall, direct: &start})
}
exdates, err := externalDateList(group.master.Props["EXDATE"], group.master.Props.Get("DTSTART"), zones, base.allDay, "EXDATE")
if err != nil {
return nil, err
}
excluded := map[string]bool{}
for _, value := range exdates {
excluded[occurrenceKey(value.instant, base.allDay)] = true
}
sort.Slice(occurrences, func(i, j int) bool {
left, right := occurrences[i].wall, occurrences[j].wall
if occurrences[i].direct != nil {
left = *occurrences[i].direct
}
if occurrences[j].direct != nil {
right = *occurrences[j].direct
}
return left.Before(right)
})
used := map[string]bool{}
previous := ""
for _, occurrence := range occurrences {
occurrenceWall := occurrence.wall
occurrenceStart, occurrenceEnd, err := externalOccurrenceBounds(group.master, base, occurrenceWall, zones)
if occurrence.direct != nil {
occurrenceStart = *occurrence.direct
occurrenceEnd = occurrenceStart.Add(base.end.Sub(base.start))
}
if err != nil {
return nil, err
}
key := occurrenceKey(occurrenceStart, base.allDay)
if key == previous {
continue
}
previous = key
exception, hasException := group.exceptions[key]
if excluded[key] && !hasException {
continue
}
source, allDay := group.master, base.allDay
if hasException {
used[key] = true
if exception.allDay != base.allDay {
return nil, fmt.Errorf("%w: RECURRENCE-ID value type differs from master", ErrInvalid)
}
if externalCancelled(exception.component) {
continue
}
times, e := externalTimes(exception.component, zones)
if e != nil {
return nil, fmt.Errorf("VEVENT group %d recurrence exception timing validation failed: %w", groupIndex+1, e)
}
if exception.component.Props.Get("DTEND") == nil && base.end.After(base.start) {
times.end = times.start.Add(base.end.Sub(base.start))
}
source, allDay, occurrenceStart, occurrenceEnd = exception.component, times.allDay, times.start, times.end
}
if !(occurrenceStart.Before(to) && (occurrenceEnd.After(from) || occurrenceEnd.Equal(occurrenceStart) && !occurrenceStart.Before(from))) {
continue
}
event, e := materializeExternal(source, uid, occurrenceStart, occurrenceEnd, allDay, recurring, occurrenceWall, zones)
if e != nil {
return nil, e
}
if e = appendEvent(event); e != nil {
return nil, e
}
}
// A moved exception can enter the synchronization window even when its
// original occurrence is just outside it.
for key, exception := range group.exceptions {
if used[key] || externalCancelled(exception.component) {
continue
}
times, e := externalTimes(exception.component, zones)
if e != nil {
return nil, fmt.Errorf("VEVENT group %d detached recurrence exception timing validation failed: %w", groupIndex+1, e)
}
if exception.component.Props.Get("DTEND") == nil && base.end.After(base.start) {
times.end = times.start.Add(base.end.Sub(base.start))
}
if !(times.start.Before(to) && (times.end.After(from) || times.end.Equal(times.start) && !times.start.Before(from))) {
continue
}
event, e := materializeExternal(exception.component, uid, times.start, times.end, times.allDay, true, exception.wall, zones)
if e != nil {
return nil, e
}
if e = appendEvent(event); e != nil {
return nil, e
}
}
}
sort.Slice(result, func(i, j int) bool {
if result[i].Start.Equal(result[j].Start) {
return result[i].UID < result[j].UID
}
return result[i].Start.Before(result[j].Start)
})
return result, nil
}