package calendar import ( "context" "fmt" "io" "os" "path/filepath" "sort" "strings" "time" ical "github.com/emersion/go-ical" ) const MaxFeed = 8 << 20 type Source struct { Kind string `json:"kind"` Credential string `json:"credential,omitempty"` HasCredential bool `json:"has_credential"` Resources map[string]RemoteResource `json:"resources,omitempty"` URL string `json:"url"` IntervalSeconds int64 `json:"interval_seconds"` Enabled bool `json:"enabled"` ETag string `json:"etag,omitempty"` Modified string `json:"last_modified,omitempty"` Next int64 `json:"next_at_ms"` Checked int64 `json:"checked_at_ms"` Success int64 `json:"success_at_ms"` Error string `json:"error,omitempty"` } type RemoteResource struct { UID string `json:"uid"` ETag string `json:"etag"` } func (r *Repository) SourceCalendar(domain, id string) (Calendar, error) { dir, e := r.dir(domain, id) if e != nil { return Calendar{}, e } c, e := readMeta(dir) if e != nil { return c, e } if c.Source == nil { return c, ErrMissing } return c, nil } func ParseFeed(data []byte) ([]Event, error) { if len(data) > MaxFeed { return nil, ErrLimit } dec := ical.NewDecoder(strings.NewReader(string(data))) cal, e := dec.Decode() if e != nil { return nil, fmt.Errorf("%w: malformed VCALENDAR", ErrInvalid) } if _, e = dec.Decode(); e != io.EOF { return nil, ErrInvalid } version, _ := cal.Props.Text("VERSION") product, _ := cal.Props.Text("PRODID") if len(cal.Props["VERSION"]) != 1 || version != "2.0" || len(cal.Props["PRODID"]) != 1 || product == "" || cal.Props.Get("METHOD") != nil { return nil, ErrInvalid } if scale := cal.Props.Get("CALSCALE"); scale != nil && (len(cal.Props["CALSCALE"]) != 1 || !strings.EqualFold(scale.Value, "GREGORIAN")) { return nil, ErrInvalid } result := []Event{} seen := map[string]bool{} for _, child := range cal.Children { if child.Name != "VEVENT" { return nil, fmt.Errorf("%w: source contains unsupported %s", ErrInvalid, child.Name) } payload, e := encode(envelope(child)) if e != nil { return nil, ErrInvalid } event, e := Parse(payload) if e != nil { return nil, e } if seen[event.UID] { return nil, fmt.Errorf("%w: duplicate UID or recurrence exception", ErrInvalid) } seen[event.UID] = true result = append(result, event) if len(result) > 5000 { return nil, ErrLimit } } return result, nil } func (r *Repository) SetSource(ctx context.Context, domain, id, actor, version string, source Source) (Calendar, error) { dir, e := r.dir(domain, id) if e != nil { return Calendar{}, e } unlock, e := lock(ctx, dir) if e != nil { return Calendar{}, e } defer unlock() c, e := readMeta(dir) if e != nil { return c, e } if actor == "" || c.Owner != actor { return c, ErrForbidden } if c.Version != version { return c, ErrConflict } if source.IntervalSeconds < 60 || source.IntervalSeconds > 604800 || source.URL == "" { return c, ErrInvalid } if source.Kind == "" { source.Kind = "ics" } if source.Kind != "ics" && source.Kind != "caldav" { return c, ErrInvalid } if c.Source == nil && len(c.Months) > 0 { return c, fmt.Errorf("%w: use an empty calendar for an external source", ErrInvalid) } if c.Source != nil && c.Source.URL == source.URL && c.Source.Kind == source.Kind && c.Source.Credential == source.Credential { previous := *c.Source previous.IntervalSeconds = source.IntervalSeconds previous.Enabled = source.Enabled previous.Next = 0 source = previous } c.Source = &source c.ReadOnly = true e = saveMeta(dir, &c) return c, e } func (r *Repository) Sources(domain string) ([]Calendar, error) { if !validID(domain) { return nil, ErrMissing } entries, e := os.ReadDir(filepath.Join(r.Root, domain)) if os.IsNotExist(e) { return []Calendar{}, nil } if e != nil { return nil, e } out := []Calendar{} for _, entry := range entries { if !entry.IsDir() || !validID(entry.Name()) { continue } c, e := readMeta(filepath.Join(r.Root, domain, entry.Name())) if e != nil { continue } if c.Source != nil { out = append(out, c) } } return out, nil } // A complete, validated source response replaces the imported snapshot in a // single manifest commit. Transport/validation failures never erase events. func (r *Repository) ApplySource(ctx context.Context, domain string, before Calendar, events []Event, etag, modified string, notModified bool, syncErr error, resources ...map[string]RemoteResource) error { dir, e := r.dir(domain, before.ID) if e != nil { return e } unlock, e := lock(ctx, dir) if e != nil { return e } defer unlock() c, e := readMeta(dir) if e != nil { return e } if c.Source == nil || c.Version != before.Version { return ErrConflict } if syncErr == nil && !notModified { // Provider response ordering must not rewrite unchanged monthly files. events = append([]Event(nil), events...) sort.Slice(events, func(i, j int) bool { return events[i].UID < events[j].UID }) months := map[string][]*ical.Component{} for _, event := range events { child, e := component(event.Data) if e != nil { return e } month := event.Start.Format("2006-01") months[month] = append(months[month], child) } hashes := map[string]string{} for month, children := range months { if len(children) > 5000 { return ErrLimit } cal := envelope(children...) cal.Props.SetText("NAME", c.PrettyName) data, e := encode(cal) if e != nil { return e } if len(data) > 16<<20 { return ErrLimit } hash := digest([]byte(data)) if c.Months[month] != hash { if e = atomicFile(filepath.Join(dir, month+"."+hash+".ics"), []byte(data)); e != nil { return e } } hashes[month] = hash } c.Months = hashes c.Source.ETag = etag c.Source.Modified = modified if len(resources) > 0 { c.Source.Resources = resources[0] } } now := time.Now() c.Source.Checked = now.UnixMilli() c.Source.Next = now.Add(time.Duration(c.Source.IntervalSeconds) * time.Second).UnixMilli() if syncErr != nil { c.Source.Error = syncErr.Error() } else { c.Source.Error = "" c.Source.Success = now.UnixMilli() } if e = saveMeta(dir, &c); e != nil { return e } pruneSnapshots(dir, c) return nil }