summaryrefslogtreecommitdiff
path: root/pim/lib/cal/ical.go
blob: 5477030053d49ca22861f2d25dfda25d51af983a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package cal

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"
	_ "time/tzdata" // TZID= resolution; 9front has no zoneinfo

	"github.com/emersion/go-ical"
	"github.com/teambition/rrule-go"
)

// Event is one VEVENT, with its recurrence set resolved but not expanded.
type Event struct {
	UID         string
	Summary     string
	Location    string
	Description string
	Start       time.Time
	End         time.Time
	AllDay      bool
	RRule       string
	Alarms      []time.Duration // relative to start; negative means before
	Raw         string
	RecurID     time.Time // set when this event overrides one instance
	Cancelled   bool
	Organizer   string
	Attendees   []Attendee
	master      *Event           // set on an override: the series it belongs to
	set         *rrule.Set       // nil when the event does not recur
	overrides   map[int64]*Event // by RECURRENCE-ID, unix seconds
}

// Attendee is one ATTENDEE line, reduced to what a person wants to see.
type Attendee struct {
	Name     string // CN
	Email    string // the mailto: value, stripped
	Partstat string // NEEDS-ACTION, ACCEPTED, DECLINED, TENTATIVE
	Role     string
}

// Instance is one occurrence of an Event at a concrete time.
type Instance struct {
	Ev    *Event
	Start time.Time
	End   time.Time
}

// Duration of a single occurrence.
func (e *Event) dur() time.Duration {
	if e.End.IsZero() || !e.End.After(e.Start) {
		return time.Hour
	}
	return e.End.Sub(e.Start)
}

// Instances returns every occurrence starting within [t0, t1).
//
// An overridden occurrence is emitted from the override, not from the
// recurrence rule, because the override may have moved it into or out of
// the window, or cancelled it outright.
func (e *Event) Instances(t0, t1 time.Time) []Instance {
	var out []Instance
	in := func(t time.Time) bool { return !t.Before(t0) && t.Before(t1) }

	if e.set == nil {
		if in(e.Start) {
			out = append(out, Instance{e, e.Start, e.Start.Add(e.dur())})
		}
	} else {
		for _, t := range e.set.Between(t0, t1, true) {
			if _, ok := e.overrides[t.Unix()]; ok {
				continue // the override speaks for this occurrence
			}
			out = append(out, Instance{e, t, t.Add(e.dur())})
		}
	}
	for _, ov := range e.overrides {
		if ov.Cancelled || !in(ov.Start) {
			continue
		}
		out = append(out, Instance{ov, ov.Start, ov.Start.Add(ov.dur())})
	}
	return out
}

// loadDir reads every .ics file in dir and returns the events it contains.
// LoadDir reads every .ics file in dir.
func LoadDir(dir string) ([]*Event, error) {
	names, err := filepath.Glob(filepath.Join(dir, "*.ics"))
	if err != nil {
		return nil, err
	}
	sort.Strings(names)
	var cals []*ical.Calendar
	for _, name := range names {
		f, err := os.Open(name)
		if err != nil {
			Warnf("%s: %v", name, err)
			continue
		}
		c, err := ical.NewDecoder(f).Decode()
		f.Close()
		if err != nil {
			Warnf("%s: %v", name, err)
			continue
		}
		cals = append(cals, c)
	}
	return FromCalendars(cals), nil
}

// FromCalendars turns decoded iCalendar objects into events, with
// RECURRENCE-ID overrides attached to the series they belong to.
//
// A backend that already holds parsed calendars -- CalDAV hands them
// straight back from a REPORT -- comes through here rather than writing
// them to disk first.
func FromCalendars(cals []*ical.Calendar) []*Event {
	var evs []*Event
	for _, c := range cals {
		for _, e := range c.Events() {
			ev, err := newEvent(&e)
			if err != nil {
				Warnf("%v", err)
				continue
			}
			evs = append(evs, ev)
		}
	}
	return link(evs)
}

// link attaches RECURRENCE-ID events to the series they override.
// An override with no matching series is kept as an event of its own.
func link(evs []*Event) []*Event {
	masters := make(map[string]*Event, len(evs))
	for _, e := range evs {
		if e.RecurID.IsZero() {
			masters[e.UID] = e
		}
	}
	out := make([]*Event, 0, len(masters))
	for _, e := range evs {
		if e.RecurID.IsZero() {
			out = append(out, e)
			continue
		}
		m, ok := masters[e.UID]
		if !ok {
			out = append(out, e) // orphan; stands alone
			continue
		}
		e.master = m
		if m.overrides == nil {
			m.overrides = make(map[int64]*Event)
		}
		m.overrides[e.RecurID.Unix()] = e
	}
	return out
}

func newEvent(ev *ical.Event) (*Event, error) {
	e := &Event{}
	e.UID, _ = ev.Props.Text(ical.PropUID)
	if e.UID == "" {
		return nil, fmt.Errorf("event with no UID")
	}
	e.Summary, _ = ev.Props.Text(ical.PropSummary)
	e.Location, _ = ev.Props.Text(ical.PropLocation)
	e.Description, _ = ev.Props.Text(ical.PropDescription)

	start, err := ev.DateTimeStart(time.Local)
	if err != nil {
		return nil, fmt.Errorf("%s: bad DTSTART: %v", e.UID, err)
	}
	e.Start = start
	if end, err := ev.DateTimeEnd(time.Local); err == nil {
		e.End = end
	}
	if p := ev.Props.Get(ical.PropDateTimeStart); p != nil {
		e.AllDay = p.ValueType() == ical.ValueDate
	}
	if p := ev.Props.Get(ical.PropRecurrenceRule); p != nil {
		e.RRule = p.Value
	}
	if p := ev.Props.Get(ical.PropRecurrenceID); p != nil {
		if t, err := parseICSTime(p.Value, time.Local); err == nil {
			e.RecurID = t
		} else if t, err := ev.Props.DateTime(ical.PropRecurrenceID, time.Local); err == nil {
			e.RecurID = t
		}
	}
	if st, err := ev.Props.Text(ical.PropStatus); err == nil {
		e.Cancelled = strings.EqualFold(st, "CANCELLED")
	}
	if p := ev.Props.Get(ical.PropOrganizer); p != nil {
		e.Organizer = person(p)
	}
	for _, p := range ev.Props.Values(ical.PropAttendee) {
		e.Attendees = append(e.Attendees, Attendee{
			Name:     p.Params.Get(ical.ParamCommonName),
			Email:    strings.TrimPrefix(p.Value, "mailto:"),
			Partstat: p.Params.Get(ical.ParamParticipationStatus),
			Role:     p.Params.Get(ical.ParamRole),
		})
	}
	e.Raw = rawOf(ev.Component)
	e.Alarms = alarmsOf(ev.Component)

	if err := e.buildSet(ev); err != nil {
		Warnf("%s: %v", e.UID, err)
	}
	return e, nil
}

// buildSet assembles the recurrence set from RRULE, EXDATE and RDATE.
func (e *Event) buildSet(ev *ical.Event) error {
	opt, err := ev.Props.RecurrenceRule()
	if err != nil {
		return fmt.Errorf("bad RRULE: %v", err)
	}
	exd := ev.Props.Values(ical.PropExceptionDates)
	rdt := ev.Props.Values(ical.PropRecurrenceDates)
	if opt == nil && len(exd) == 0 && len(rdt) == 0 {
		return nil
	}
	set := &rrule.Set{}
	set.DTStart(e.Start)
	if opt != nil {
		opt.Dtstart = e.Start
		r, err := rrule.NewRRule(*opt)
		if err != nil {
			return fmt.Errorf("bad RRULE: %v", err)
		}
		set.RRule(r)
	}
	for _, p := range exd {
		for _, t := range dateList(p, e.Start.Location()) {
			set.ExDate(t)
		}
	}
	for _, p := range rdt {
		for _, t := range dateList(p, e.Start.Location()) {
			set.RDate(t)
		}
	}
	e.set = set
	return nil
}

// dateList parses the comma-separated date list in EXDATE/RDATE.
func dateList(p ical.Prop, loc *time.Location) []time.Time {
	var out []time.Time
	for _, s := range strings.Split(p.Value, ",") {
		s = strings.TrimSpace(s)
		if s == "" {
			continue
		}
		t, err := parseICSTime(s, loc)
		if err != nil {
			Warnf("bad %s %q: %v", p.Name, s, err)
			continue
		}
		out = append(out, t)
	}
	return out
}

func parseICSTime(s string, loc *time.Location) (time.Time, error) {
	for _, f := range []string{"20060102T150405Z", "20060102T150405", "20060102"} {
		l := loc
		if strings.HasSuffix(f, "Z") {
			l = time.UTC
		}
		if t, err := time.ParseInLocation(f, s, l); err == nil {
			return t, nil
		}
	}
	return time.Time{}, fmt.Errorf("unrecognised time")
}

// alarmsOf returns the relative triggers of every VALARM child.
// Absolute triggers are ignored for now; see doc/design.md.
func alarmsOf(c *ical.Component) []time.Duration {
	var out []time.Duration
	for _, child := range c.Children {
		if child.Name != ical.CompAlarm {
			continue
		}
		p := child.Props.Get(ical.PropTrigger)
		if p == nil {
			continue
		}
		d, err := parseDuration(p.Value)
		if err != nil {
			continue
		}
		out = append(out, d)
	}
	return out
}

func rawOf(c *ical.Component) string {
	var b strings.Builder
	fmt.Fprintf(&b, "BEGIN:%s\n", c.Name)
	var names []string
	for name := range c.Props {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		for _, p := range c.Props[name] {
			fmt.Fprintf(&b, "%s:%s\n", p.Name, p.Value)
		}
	}
	fmt.Fprintf(&b, "END:%s\n", c.Name)
	return b.String()
}

// person renders ORGANIZER as a name, falling back to the address.
func person(p *ical.Prop) string {
	addr := strings.TrimPrefix(p.Value, "mailto:")
	if cn := p.Params.Get(ical.ParamCommonName); cn != "" && cn != addr {
		return cn + " <" + addr + ">"
	}
	return addr
}