-
Notifications
You must be signed in to change notification settings - Fork 10
/
parse.go
548 lines (439 loc) · 11 KB
/
parse.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package ical
import (
"errors"
"fmt"
"io"
"io/ioutil"
"strings"
"time"
)
// A Calendar represents the whole iCalendar
type Calendar struct {
Properties []*Property
Events []*Event
Prodid string
Version string
Calscale string
Method string
}
// An Event represent a VEVENT component in an iCalendar
type Event struct {
Properties []*Property
Alarms []*Alarm
UID string
Timestamp time.Time
StartDate time.Time
EndDate time.Time
Summary string
Description string
}
// An Alarm represent a VALARM component in an iCalendar
type Alarm struct {
Properties []*Property
Action string
Trigger string
}
// A Property represent an unparsed property in an iCalendar component
type Property struct {
Name string
Params map[string]*Param
Value string
}
// A Param represent a list of param for a property
type Param struct {
Values []string
}
type parser struct {
lex *lexer
token [2]item
peekCount int
scope int
c *Calendar
v *Event
a *Alarm
location *time.Location
}
// Parse transforms the raw iCalendar into a Calendar struct
// It's up to the caller to close the io.Reader
// if the time.Location parameter is not set, it will default to the system location
func Parse(r io.Reader, l *time.Location) (*Calendar, error) {
p := &parser{}
p.c = NewCalendar()
p.scope = scopeCalendar
bytes, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
if l == nil {
l = time.Local
}
p.location = l
text := unfold(string(bytes))
p.lex = lex(text)
return p.parse()
}
// NewCalendar creates an empty Calendar
func NewCalendar() *Calendar {
c := &Calendar{
Calscale: "GREGORIAN",
}
c.Properties = make([]*Property, 0)
c.Events = make([]*Event, 0)
return c
}
// NewProperty creates an empty Property
func NewProperty() *Property {
p := &Property{}
p.Params = make(map[string]*Param)
return p
}
// NewEvent creates an empty Event
func NewEvent() *Event {
v := &Event{}
v.Properties = make([]*Property, 0)
v.Alarms = make([]*Alarm, 0)
return v
}
// NewAlarm creates an empty Alarm
func NewAlarm() *Alarm {
a := &Alarm{}
a.Properties = make([]*Property, 0)
return a
}
// NewParam creates an empty Param
func NewParam() *Param {
p := &Param{}
p.Values = make([]string, 0)
return p
}
// unfold convert multiple line value to one line
func unfold(text string) string {
return strings.Replace(text, "\r\n ", "", -1)
}
// next returns the next token.
func (p *parser) next() item {
if p.peekCount > 0 {
p.peekCount--
} else {
p.token[0] = p.lex.nextItem()
}
return p.token[p.peekCount]
}
// backup backs the input stream up one token.
func (p *parser) backup() {
p.peekCount++
}
// enterScope switch scope between Calendar, Event and Alarm
func (p *parser) enterScope() {
p.scope++
}
// leaveScope returns to previous scope
func (p *parser) leaveScope() {
p.scope--
}
// parse
const (
scopeCalendar int = iota
scopeEvent
scopeAlarm
)
const (
dateLayout = "20060102"
dateTimeLayoutUTC = "20060102T150405Z"
dateTimeLayoutLocalized = "20060102T150405"
)
var errorDone = errors.New("done")
func (p *parser) parse() (*Calendar, error) {
if item := p.next(); item.typ != itemBeginVCalendar {
return nil, fmt.Errorf("found %s, expected BEGIN:VCALENDAR", item)
}
if item := p.next(); item.typ != itemLineEnd {
return nil, fmt.Errorf("found %s, expected CRLF", item)
}
for {
err := p.scanContentLine()
if err == errorDone {
break
}
if err != nil {
return nil, err
}
}
return p.c, nil
}
// scanDelimiter switch scope and validate related component
func (p *parser) scanDelimiter(delim item) error {
if delim.typ == itemBeginVEvent {
if err := p.validateCalendar(p.c); err != nil {
return err
}
p.v = NewEvent()
p.enterScope()
if item := p.next(); item.typ != itemLineEnd {
return fmt.Errorf("found %s, expected CRLF", item)
}
}
if delim.typ == itemEndVEvent {
if p.scope > scopeEvent {
return fmt.Errorf("found %s, expeced END:VALARM", delim)
}
if err := p.validateEvent(p.v); err != nil {
return err
}
p.c.Events = append(p.c.Events, p.v)
p.leaveScope()
if item := p.next(); item.typ != itemLineEnd {
return fmt.Errorf("found %s, expected CRLF", item)
}
}
if delim.typ == itemBeginVAlarm {
p.a = NewAlarm()
p.enterScope()
if item := p.next(); item.typ != itemLineEnd {
return fmt.Errorf("found %s, expected CRLF", item)
}
}
if delim.typ == itemEndVAlarm {
if err := p.validateAlarm(p.a); err != nil {
return err
}
p.v.Alarms = append(p.v.Alarms, p.a)
p.leaveScope()
if item := p.next(); item.typ != itemLineEnd {
return fmt.Errorf("found %s, expected CRLF", item)
}
}
if delim.typ == itemEndVCalendar {
if p.scope > scopeCalendar {
return fmt.Errorf("found %s, expeced END:VEVENT", delim)
}
return errorDone
}
return nil
}
// scanContentLine parses a content-line of a calendar
func (p *parser) scanContentLine() error {
name := p.next()
if name.typ > itemKeyword {
if err := p.scanDelimiter(name); err != nil {
return err
}
return p.scanContentLine()
}
if !isItemName(name) {
return fmt.Errorf("found %s, expected a \"name\" token", name)
}
prop := NewProperty()
prop.Name = name.val
if err := p.scanParams(prop); err != nil {
return err
}
if item := p.next(); item.typ != itemColon {
return fmt.Errorf("found %s, expected \":\"", item)
}
value := p.next()
if value.typ != itemValue {
return fmt.Errorf("found %s, expected a value", value)
}
prop.Value = value.val
if item := p.next(); item.typ != itemLineEnd {
return fmt.Errorf("found %s, expected CRLF", name)
}
if p.scope == scopeCalendar {
p.c.Properties = append(p.c.Properties, prop)
} else if p.scope == scopeEvent {
p.v.Properties = append(p.v.Properties, prop)
} else if p.scope == scopeAlarm {
p.a.Properties = append(p.a.Properties, prop)
}
return nil
}
// scanParams parses a list of param inside a content-line
func (p *parser) scanParams(prop *Property) error {
for {
item := p.next()
if item.typ != itemSemiColon {
p.backup()
return nil
}
paramName := p.next()
if paramName.typ != itemParamName {
return fmt.Errorf("found %s, expected a param-name", paramName)
}
param := NewParam()
if item := p.next(); item.typ != itemEqual {
return fmt.Errorf("found %s, expected =", item)
}
if err := p.scanValues(param); err != nil {
return err
}
prop.Params[paramName.val] = param
}
}
// scanValues parses a list of at least one value for a param
func (p *parser) scanValues(param *Param) error {
paramValue := p.next()
if paramValue.typ != itemParamValue {
return fmt.Errorf("found %s, expected a param-value", paramValue)
}
param.Values = append(param.Values, paramValue.val)
for {
item := p.next()
if item.typ != itemComma {
p.backup()
return nil
}
paramValue := p.next()
if paramValue.typ != itemParamValue {
return fmt.Errorf("found %s, expected a param-value", paramValue)
}
param.Values = append(param.Values, paramValue.val)
}
}
// validateCalendar validate calendar props
func (p *parser) validateCalendar(c *Calendar) error {
requiredCount := 0
for _, prop := range c.Properties {
if prop.Name == "PRODID" {
c.Prodid = prop.Value
requiredCount++
}
if prop.Name == "VERSION" {
c.Version = prop.Value
requiredCount++
}
if prop.Name == "CALSCALE" {
c.Calscale = prop.Value
}
if prop.Name == "METHOD" {
c.Method = prop.Value
}
}
if requiredCount != 2 {
return fmt.Errorf("missing either required property \"prodid / version /\"")
}
return nil
}
// validateEvent validate event props
func (p *parser) validateEvent(v *Event) error {
uniqueCount := make(map[string]int)
for _, prop := range v.Properties {
if prop.Name == "UID" {
v.UID = prop.Value
uniqueCount["UID"]++
}
if prop.Name == "DTSTAMP" {
v.Timestamp, _ = parseDate(prop, p.location)
uniqueCount["DTSTAMP"]++
}
if prop.Name == "DTSTART" {
v.StartDate, _ = parseDate(prop, p.location)
uniqueCount["DTSTART"]++
}
if prop.Name == "DTEND" {
if hasProperty("DURATION", v.Properties) {
return fmt.Errorf("Either \"dtend\" or \"duration\" MAY appear")
}
v.EndDate, _ = parseDate(prop, p.location)
uniqueCount["DTEND"]++
}
if prop.Name == "DURATION" {
if hasProperty("DTEND", v.Properties) {
return fmt.Errorf("Either \"dtend\" or \"duration\" MAY appear")
}
uniqueCount["DURATION"]++
}
if prop.Name == "SUMMARY" {
v.Summary = prop.Value
uniqueCount["SUMMARY"]++
}
if prop.Name == "DESCRIPTION" {
v.Description = prop.Value
uniqueCount["DESCRIPTION"]++
}
}
if p.c.Method == "" && v.Timestamp.IsZero() {
return fmt.Errorf("missing required property \"dtstamp\"")
}
if v.UID == "" {
return fmt.Errorf("missing required property \"uid\"")
}
if v.StartDate.IsZero() {
return fmt.Errorf("missing required property \"dtstart\"")
}
for key, value := range uniqueCount {
if value > 1 {
return fmt.Errorf("\"%s\" property must not occur more than once", key)
}
}
if !hasProperty("DTEND", v.Properties) {
v.EndDate = v.StartDate.Add(time.Hour * 24) // add one day to start date
}
return nil
}
// validateAlarm validate alarm props
func (p *parser) validateAlarm(a *Alarm) error {
requiredCount := 0
uniqueCount := make(map[string]int)
for _, prop := range a.Properties {
if prop.Name == "ACTION" {
a.Action = prop.Value
requiredCount++
uniqueCount["ACTION"]++
}
if prop.Name == "TRIGGER" {
a.Trigger = prop.Value
requiredCount++
uniqueCount["TRIGGER"]++
}
}
if requiredCount != 2 {
return fmt.Errorf("missing either required property \"action / trigger /\"")
}
for key, value := range uniqueCount {
if value > 1 {
return fmt.Errorf("\"%s\" property must not occur more than once", key)
}
}
return nil
}
// hasProperty checks if a given component has a certain property
func hasProperty(name string, properties []*Property) bool {
for _, prop := range properties {
if name == prop.Name {
return true
}
}
return false
}
// parseDate transform an ical date property into a time.Time
func parseDate(prop *Property, l *time.Location) (time.Time, error) {
if strings.HasSuffix(prop.Value, "Z") {
return time.Parse(dateTimeLayoutUTC, prop.Value)
}
if tz, ok := prop.Params["TZID"]; ok {
loc, err := time.LoadLocation(tz.Values[0])
// In case we are not able to load TZID location we default to UTC
if err != nil {
loc = time.UTC
}
return time.ParseInLocation(dateTimeLayoutLocalized, prop.Value, loc)
}
if len(prop.Value) == 8 {
return time.ParseInLocation(dateLayout, prop.Value, l)
}
layout := dateTimeLayoutLocalized
if val, ok := prop.Params["VALUE"]; ok {
switch val.Values[0] {
case "DATE":
layout = dateLayout
// Handle malformed DATE entries that use DATE-TIME format
if len(prop.Value) == len(dateTimeLayoutLocalized) {
layout = dateTimeLayoutLocalized
}
case "DATE-TIME":
layout = dateTimeLayoutLocalized
}
}
return time.ParseInLocation(layout, prop.Value, l)
}