-
Notifications
You must be signed in to change notification settings - Fork 24
/
gocal.go
389 lines (351 loc) · 10.1 KB
/
gocal.go
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package gocal
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
"time"
"github.com/apognu/gocal/parser"
)
func NewParser(r io.Reader) *Gocal {
return &Gocal{
scanner: bufio.NewScanner(r),
Events: make([]Event, 0),
Strict: StrictParams{
Mode: StrictModeFailFeed,
},
Duplicate: DuplicateParams{
Mode: DuplicateModeFailStrict,
},
SkipBounds: false,
AllDayEventsTZ: time.UTC,
}
}
func (gc *Gocal) Parse() error {
if gc.Start == nil {
start := time.Now().Add(-1 * 24 * time.Hour)
gc.Start = &start
}
if gc.End == nil {
end := time.Now().Add(3 * 30 * 24 * time.Hour)
gc.End = &end
}
gc.scanner.Scan()
rInstances := make([]Event, 0)
ctx := &Context{Value: ContextRoot}
for {
l, err, done := gc.parseLine()
if err != nil {
if done {
break
}
continue
}
if l.IsValue("VCALENDAR") {
continue
}
if ctx.Value == ContextRoot && l.Is("BEGIN", "VEVENT") {
ctx = ctx.Nest(ContextEvent)
gc.buffer = &Event{Valid: true, delayed: make([]*Line, 0)}
} else if ctx.Value == ContextRoot && l.IsKey("METHOD") {
gc.Method = l.Value
} else if ctx.Value == ContextEvent && l.Is("END", "VEVENT") {
if ctx.Previous == nil {
return fmt.Errorf("got an END:* without matching BEGIN:*")
}
ctx = ctx.Previous
for _, d := range gc.buffer.delayed {
gc.parseEvent(d)
}
// Some tools return single full day events as inclusive (same DTSTART
// and DTEND) which goes against RFC. Standard tools still handle those
// as events spanning 24 hours.
if gc.buffer.RawStart.Value == gc.buffer.RawEnd.Value {
if value, ok := gc.buffer.RawEnd.Params["VALUE"]; ok && value == "DATE" {
gc.buffer.End, err = parser.ParseTime(gc.buffer.RawEnd.Value, gc.buffer.RawEnd.Params, parser.TimeEnd, true, gc.AllDayEventsTZ)
}
}
// If an event has a VALUE=DATE start date and no end date, event lasts a day
if gc.buffer.End == nil && gc.buffer.RawStart.Params["VALUE"] == "DATE" {
d := (*gc.buffer.Start).Add(24 * time.Hour)
gc.buffer.End = &d
}
if err := gc.checkEvent(); err != nil {
switch gc.Strict.Mode {
case StrictModeFailFeed:
return fmt.Errorf("gocal error: %s", err)
case StrictModeFailEvent:
continue
}
}
if gc.buffer.Start == nil || gc.buffer.End == nil {
continue
}
if gc.buffer.IsRecurring {
rInstances = append(rInstances, gc.ExpandRecurringEvent(gc.buffer)...)
} else {
if gc.buffer.End == nil || gc.buffer.Start == nil {
continue
}
if !gc.SkipBounds && !gc.IsInRange(*gc.buffer) {
continue
}
if gc.Strict.Mode == StrictModeFailEvent && !gc.buffer.Valid {
continue
}
gc.Events = append(gc.Events, *gc.buffer)
}
} else if l.IsKey("BEGIN") {
ctx = ctx.Nest(ContextUnknown)
} else if l.IsKey("END") {
if ctx.Previous == nil {
return fmt.Errorf("got an END:%s without matching BEGIN:%s", l.Value, l.Value)
}
ctx = ctx.Previous
} else if ctx.Value == ContextEvent {
if err := gc.parseEvent(l); err != nil {
if _, ok := err.(DuplicateAttributeError); ok {
switch gc.Duplicate.Mode {
case DuplicateModeFailStrict:
switch gc.Strict.Mode {
case StrictModeFailFeed:
return fmt.Errorf("gocal error: %s", err)
case StrictModeFailEvent:
gc.buffer.Valid = false
continue
case StrictModeFailAttribute:
gc.buffer.Valid = false
continue
}
}
}
return fmt.Errorf(fmt.Sprintf("gocal error: %s", err))
}
} else {
continue
}
if done {
break
}
}
for _, i := range rInstances {
if !gc.IsRecurringInstanceOverriden(&i) && gc.IsInRange(i) {
gc.Events = append(gc.Events, i)
}
}
return nil
}
func (gc *Gocal) parseLine() (*Line, error, bool) {
// Get initial current line and check if that was the last one
l := gc.scanner.Text()
done := !gc.scanner.Scan()
// If not, try and figure out if value is continued on next line
if !done {
for strings.HasPrefix(gc.scanner.Text(), " ") {
l = l + strings.TrimPrefix(gc.scanner.Text(), " ")
if done = !gc.scanner.Scan(); done {
break
}
}
}
tokens := splitLineTokens(l)
if len(tokens) < 2 {
return nil, fmt.Errorf("could not parse item: %s", l), done
}
attr, params := parser.ParseParameters(tokens[0])
return &Line{Key: attr, Params: params, Value: parser.UnescapeString(strings.TrimPrefix(tokens[1], " "))}, nil, done
}
// splitLineTokens assures that property parameters that are quoted due to containing special
// characters (like COLON, SEMICOLON, COMMA) are not split.
// See RFC5545, 3.1.1.
func splitLineTokens(line string) []string {
// go's Split is highly optimized -> use, unless we cannot
if idxQuote := strings.Index(line, `"`); idxQuote == -1 {
return strings.SplitN(line, ":", 2)
} else if idxColon := strings.Index(line, ":"); idxQuote > idxColon {
return []string{line[0:idxColon], line[idxColon+1:]}
}
// otherwise, we need to do it ourselves, let's keep it simple at least:
quoted := false
size := len(line)
for idx, char := range []byte(line) {
if char == '"' {
quoted = !quoted
} else if char == ':' && !quoted && idx+1 < size {
return []string{line[0:idx], line[idx+1:]}
}
}
return []string{line}
}
func (gc *Gocal) parseEvent(l *Line) error {
// If this is nil, that means we did not get a BEGIN:VEVENT
if gc.buffer == nil {
return nil
}
switch l.Key {
case "UID":
if err := resolve(gc, l, &gc.buffer.Uid, resolveString, nil); err != nil {
return err
}
case "SUMMARY":
if err := resolve(gc, l, &gc.buffer.Summary, resolveString, nil); err != nil {
return err
}
case "DESCRIPTION":
if err := resolve(gc, l, &gc.buffer.Description, resolveString, nil); err != nil {
return err
}
case "DTSTART":
if err := resolve(gc, l, &gc.buffer.Start, resolveDate, func(gc *Gocal, out *time.Time) {
gc.buffer.RawStart = RawDate{Value: l.Value, Params: l.Params}
}); err != nil {
return err
}
case "DTEND":
if err := resolve(gc, l, &gc.buffer.End, resolveDateEnd, func(gc *Gocal, out *time.Time) {
gc.buffer.RawEnd = RawDate{Value: l.Value, Params: l.Params}
}); err != nil {
return err
}
case "DURATION":
// The DURATION attribute should imply DTEND as DTSTART+DURATION.
// If we have not processed DTSTART yet, add this to the delayed attributes to be processed later.
if gc.buffer.Start == nil {
gc.buffer.delayed = append(gc.buffer.delayed, l)
return nil
}
if err := resolve(gc, l, &gc.buffer.Duration, resolveDuration, func(gc *Gocal, out *time.Duration) {
if out != nil {
gc.buffer.Duration = out
end := gc.buffer.Start.Add(*out)
gc.buffer.End = &end
}
}); err != nil {
return err
}
case "DTSTAMP":
if err := resolve(gc, l, &gc.buffer.Stamp, resolveDate, nil); err != nil {
return err
}
case "CREATED":
if err := resolve(gc, l, &gc.buffer.Created, resolveDate, nil); err != nil {
return err
}
case "LAST-MODIFIED":
if err := resolve(gc, l, &gc.buffer.LastModified, resolveDate, nil); err != nil {
return err
}
case "RRULE":
if len(gc.buffer.RecurrenceRule) != 0 {
return NewDuplicateAttribute(l.Key, l.Value)
}
if gc.buffer.RecurrenceRule == nil || gc.Duplicate.Mode == DuplicateModeKeepLast {
var err error
gc.buffer.IsRecurring = true
if gc.buffer.RecurrenceRule, err = parser.ParseRecurrenceRule(l.Value); err != nil {
return err
}
}
case "RECURRENCE-ID":
if err := resolve(gc, l, &gc.buffer.RecurrenceID, resolveString, nil); err != nil {
return err
}
case "EXDATE":
/*
Reference: https://icalendar.org/iCalendar-RFC-5545/3-8-5-1-exception-date-times.html
Several parameters are allowed. We should pass parameters we have
*/
d, err := parser.ParseTime(l.Value, l.Params, parser.TimeStart, false, gc.AllDayEventsTZ)
if err == nil {
gc.buffer.ExcludeDates = append(gc.buffer.ExcludeDates, *d)
}
case "SEQUENCE":
gc.buffer.Sequence, _ = strconv.Atoi(l.Value)
case "LOCATION":
if err := resolve(gc, l, &gc.buffer.Location, resolveString, nil); err != nil {
return err
}
case "STATUS":
if err := resolve(gc, l, &gc.buffer.Status, resolveString, nil); err != nil {
return err
}
case "ORGANIZER":
if err := resolve(gc, l, &gc.buffer.Organizer, resolveOrganizer, nil); err != nil {
return err
}
case "ATTENDEE":
attendee := Attendee{
Value: l.Value,
}
for key, val := range l.Params {
key := strings.ToUpper(key)
switch key {
case "CN":
attendee.Cn = val
case "DIR":
attendee.DirectoryDn = val
case "PARTSTAT":
attendee.Status = val
default:
if strings.HasPrefix(key, "X-") {
if attendee.CustomAttributes == nil {
attendee.CustomAttributes = make(map[string]string)
}
attendee.CustomAttributes[key] = val
}
}
}
gc.buffer.Attendees = append(gc.buffer.Attendees, attendee)
case "ATTACH":
gc.buffer.Attachments = append(gc.buffer.Attachments, Attachment{
Type: l.Params["VALUE"],
Encoding: l.Params["ENCODING"],
Mime: l.Params["FMTTYPE"],
Filename: l.Params["FILENAME"],
Value: l.Value,
})
case "GEO":
if err := resolve(gc, l, &gc.buffer.Geo, resolveGeo, nil); err != nil {
return err
}
case "CATEGORIES":
gc.buffer.Categories = strings.Split(l.Value, ",")
case "URL":
gc.buffer.URL = l.Value
case "COMMENT":
gc.buffer.Comment = l.Value
case "CLASS":
gc.buffer.Class = l.Value
default:
key := strings.ToUpper(l.Key)
if strings.HasPrefix(key, "X-") {
if gc.buffer.CustomAttributes == nil {
gc.buffer.CustomAttributes = make(map[string]string)
}
gc.buffer.CustomAttributes[key] = l.Value
}
}
return nil
}
func (gc *Gocal) checkEvent() error {
if gc.buffer.Uid == "" {
gc.buffer.Valid = false
return fmt.Errorf("could not parse event without UID")
}
if gc.buffer.Start == nil {
gc.buffer.Valid = false
return fmt.Errorf("could not parse event without DTSTART")
}
if gc.buffer.Stamp == nil {
gc.buffer.Valid = false
return fmt.Errorf("could not parse event without DTSTAMP")
}
if gc.buffer.RawEnd.Value != "" && gc.buffer.Duration != nil {
return fmt.Errorf("only one of DTEND and DURATION must be provided")
}
return nil
}
func SetTZMapper(cb func(s string) (*time.Location, error)) {
parser.TZMapper = cb
}