forked from arran4/golang-ical
-
Notifications
You must be signed in to change notification settings - Fork 0
/
components.go
709 lines (606 loc) · 17.6 KB
/
components.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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
package ics
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"time"
)
type Component interface {
UnknownPropertiesIANAProperties() []IANAProperty
SubComponents() []Component
serialize(b io.Writer)
}
type ComponentBase struct {
Properties []IANAProperty
Components []Component
}
func (cb *ComponentBase) UnknownPropertiesIANAProperties() []IANAProperty {
return cb.Properties
}
func (cb *ComponentBase) SubComponents() []Component {
return cb.Components
}
func (base ComponentBase) serializeThis(writer io.Writer, componentType string) {
fmt.Fprint(writer, "BEGIN:"+componentType, "\r\n")
for _, p := range base.Properties {
p.serialize(writer)
}
for _, c := range base.Components {
c.serialize(writer)
}
fmt.Fprint(writer, "END:"+componentType, "\r\n")
}
func (cb *ComponentBase) GetProperty(componentProperty ComponentProperty) *IANAProperty {
for i := range cb.Properties {
if cb.Properties[i].IANAToken == string(componentProperty) {
return &cb.Properties[i]
}
}
return nil
}
func (cb *ComponentBase) SetProperty(property ComponentProperty, value string, props ...PropertyParameter) {
for i := range cb.Properties {
if cb.Properties[i].IANAToken == string(property) {
cb.Properties[i].Value = value
cb.Properties[i].ICalParameters = map[string][]string{}
for _, p := range props {
k, v := p.KeyValue()
cb.Properties[i].ICalParameters[k] = v
}
return
}
}
cb.AddProperty(property, value, props...)
}
func (cb *ComponentBase) AddProperty(property ComponentProperty, value string, props ...PropertyParameter) {
r := IANAProperty{
BaseProperty{
IANAToken: string(property),
Value: value,
ICalParameters: map[string][]string{},
},
}
for _, p := range props {
k, v := p.KeyValue()
r.ICalParameters[k] = v
}
cb.Properties = append(cb.Properties, r)
}
type VEvent struct {
ComponentBase
Timezones map[string]*time.Location
}
func (c *VEvent) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "VEVENT")
}
func (c *VEvent) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "VEVENT")
return b.String()
}
const (
icalTimestampFormatUtc = "20060102T150405Z"
icalTimestampFormatLocal = "20060102T150405"
icalDateFormatUtc = "20060102Z"
icalDateFormatLocal = "20060102"
)
var (
timeStampVariations = regexp.MustCompile("^([0-9]{8})?([TZ])?([0-9]{6})?(Z)?$")
)
func (event *VEvent) SetCreatedTime(t time.Time, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyCreated, t.UTC().Format(icalTimestampFormatUtc), props...)
}
func (event *VEvent) SetDtStampTime(t time.Time, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyDtstamp, t.UTC().Format(icalTimestampFormatUtc), props...)
}
func (event *VEvent) SetModifiedAt(t time.Time, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyLastModified, t.UTC().Format(icalTimestampFormatUtc), props...)
}
func (event *VEvent) SetSequence(seq int, props ...PropertyParameter) {
event.SetProperty(ComponentPropertySequence, strconv.Itoa(seq), props...)
}
func (event *VEvent) SetStartAt(t time.Time, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyDtStart, t.UTC().Format(icalTimestampFormatUtc), props...)
}
func (event *VEvent) SetAllDayStartAt(t time.Time, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyDtStart, t.UTC().Format(icalDateFormatUtc), props...)
}
func (event *VEvent) SetEndAt(t time.Time, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyDtEnd, t.UTC().Format(icalTimestampFormatUtc), props...)
}
func (event *VEvent) SetAllDayEndAt(t time.Time, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyDtEnd, t.UTC().Format(icalDateFormatUtc), props...)
}
// SetDuration updates the duration of an event.
// This function will set either the end or start time of an event depending what is already given.
// The duration defines the length of a event relative to start or end time.
//
// Notice: It will not set the DURATION key of the ics - only DTSTART and DTEND will be affected.
func (event *VEvent) SetDuration(d time.Duration) error {
t, err := event.GetStartAt()
if err == nil {
event.SetEndAt(t.Add(d))
return nil
} else {
t, err = event.GetEndAt()
if err == nil {
event.SetStartAt(t.Add(-d))
return nil
}
}
return errors.New("start or end not yet defined")
}
func (event *VEvent) getTimeProp(componentProperty ComponentProperty, expectAllDay bool) (time.Time, error) {
timeProp := event.GetProperty(componentProperty)
if timeProp == nil {
return time.Time{}, errors.New("property not found")
}
return GetTimeFromProp(timeProp, event.Timezones, expectAllDay)
}
func GetTimeFromProp(prop *IANAProperty, timezones map[string]*time.Location, expectAllDay bool) (time.Time, error) {
timeVal := prop.BaseProperty.Value
matched := timeStampVariations.FindStringSubmatch(timeVal)
if matched == nil {
return time.Time{}, fmt.Errorf("time value not matched, got '%s'", timeVal)
}
tOrZGrp := matched[2]
zGrp := matched[4]
grp1len := len(matched[1])
grp3len := len(matched[3])
tzId, tzIdOk := prop.ICalParameters["TZID"]
var propLoc *time.Location
if tzIdOk {
if len(tzId) != 1 {
return time.Time{}, errors.New("expected only one TZID")
}
timezoneID := tzId[0]
// Check if this is a custom timezone
for name, loc := range timezones {
if name == timezoneID {
propLoc = loc
break
}
}
var tzErr error
if propLoc == nil {
// Not found in custom timezones, try to parse directly
propLoc, tzErr = time.LoadLocation(timezoneID)
if tzErr != nil {
return time.Time{}, tzErr
}
}
}
dateStr := matched[1]
if expectAllDay {
if grp1len > 0 {
if tOrZGrp == "Z" || zGrp == "Z" {
return time.ParseInLocation(icalDateFormatUtc, dateStr+"Z", time.UTC)
} else {
if propLoc == nil {
return time.ParseInLocation(icalDateFormatLocal, dateStr, time.Local)
} else {
return time.ParseInLocation(icalDateFormatLocal, dateStr, propLoc)
}
}
}
return time.Time{}, fmt.Errorf("time value matched but unsupported all-day timestamp, got '%s'", timeVal)
}
if grp1len > 0 && grp3len > 0 && tOrZGrp == "T" && zGrp == "Z" {
return time.ParseInLocation(icalTimestampFormatUtc, timeVal, time.UTC)
} else if grp1len > 0 && grp3len > 0 && tOrZGrp == "T" && zGrp == "" {
if propLoc == nil {
return time.ParseInLocation(icalTimestampFormatLocal, timeVal, time.Local)
} else {
return time.ParseInLocation(icalTimestampFormatLocal, timeVal, propLoc)
}
} else if grp1len > 0 && grp3len == 0 && tOrZGrp == "Z" && zGrp == "" {
return time.ParseInLocation(icalDateFormatUtc, dateStr+"Z", time.UTC)
} else if grp1len > 0 && grp3len == 0 && tOrZGrp == "" && zGrp == "" {
if propLoc == nil {
return time.ParseInLocation(icalDateFormatLocal, dateStr, time.Local)
} else {
return time.ParseInLocation(icalDateFormatLocal, dateStr, propLoc)
}
}
return time.Time{}, fmt.Errorf("time value matched but not supported, got '%s'", timeVal)
}
func (event *VEvent) GetStartAt() (time.Time, error) {
return event.getTimeProp(ComponentPropertyDtStart, false)
}
func (event *VEvent) GetEndAt() (time.Time, error) {
return event.getTimeProp(ComponentPropertyDtEnd, false)
}
func (event *VEvent) GetAllDayStartAt() (time.Time, error) {
return event.getTimeProp(ComponentPropertyDtStart, true)
}
func (event *VEvent) GetAllDayEndAt() (time.Time, error) {
return event.getTimeProp(ComponentPropertyDtEnd, true)
}
func (event *VEvent) GetRecurringIDAt() (time.Time, error) {
return event.getTimeProp(ComponentPropertyRecurrenceId, false)
}
type TimeTransparency string
const (
TransparencyOpaque TimeTransparency = "OPAQUE" // default
TransparencyTransparent TimeTransparency = "TRANSPARENT"
)
func (event *VEvent) SetTimeTransparency(v TimeTransparency, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyTransp, string(v), props...)
}
func (event *VEvent) SetSummary(s string, props ...PropertyParameter) {
event.SetProperty(ComponentPropertySummary, ToText(s), props...)
}
func (event *VEvent) SetStatus(s ObjectStatus, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyStatus, ToText(string(s)), props...)
}
func (event *VEvent) SetDescription(s string, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyDescription, ToText(s), props...)
}
func (event *VEvent) SetLocation(s string, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyLocation, ToText(s), props...)
}
func (event *VEvent) SetGeo(lat interface{}, lng interface{}, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyGeo, fmt.Sprintf("%v;%v", lat, lng), props...)
}
func (event *VEvent) SetURL(s string, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyUrl, s, props...)
}
func (event *VEvent) SetOrganizer(s string, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyOrganizer, s, props...)
}
func (event *VEvent) SetColor(s string, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyColor, s, props...)
}
func (event *VEvent) SetClass(c Classification, props ...PropertyParameter) {
event.SetProperty(ComponentPropertyClass, string(c), props...)
}
func (event *VEvent) AddAttendee(s string, props ...PropertyParameter) {
event.AddProperty(ComponentPropertyAttendee, "mailto:"+s, props...)
}
func (event *VEvent) AddExdate(s string, props ...PropertyParameter) {
event.AddProperty(ComponentPropertyExdate, s, props...)
}
func (event *VEvent) AddExrule(s string, props ...PropertyParameter) {
event.AddProperty(ComponentPropertyExrule, s, props...)
}
func (event *VEvent) AddRdate(s string, props ...PropertyParameter) {
event.AddProperty(ComponentPropertyRdate, s, props...)
}
func (event *VEvent) AddRrule(s string, props ...PropertyParameter) {
event.AddProperty(ComponentPropertyRrule, s, props...)
}
func (event *VEvent) AddAttachment(s string, props ...PropertyParameter) {
event.AddProperty(ComponentPropertyAttach, s, props...)
}
func (event *VEvent) AddAttachmentURL(uri string, contentType string) {
event.AddAttachment(uri, WithFmtType(contentType))
}
func (event *VEvent) AddAttachmentBinary(binary []byte, contentType string) {
event.AddAttachment(base64.StdEncoding.EncodeToString(binary),
WithFmtType(contentType), WithEncoding("base64"), WithValue("binary"),
)
}
type Attendee struct {
IANAProperty
}
func (attendee *Attendee) Email() string {
if strings.HasPrefix(attendee.Value, "mailto:") {
return attendee.Value[len("mailto:"):]
}
return attendee.Value
}
func (attendee *Attendee) ParticipationStatus() ParticipationStatus {
return ParticipationStatus(attendee.getPropertyFirst(ParameterParticipationStatus))
}
func (attendee *Attendee) getPropertyFirst(parameter Parameter) string {
vs := attendee.getProperty(parameter)
if len(vs) > 0 {
return vs[0]
}
return ""
}
func (attendee *Attendee) getProperty(parameter Parameter) []string {
if vs, ok := attendee.ICalParameters[string(parameter)]; ok {
return vs
}
return nil
}
func (event *VEvent) Attendees() (r []*Attendee) {
r = []*Attendee{}
for i := range event.Properties {
switch event.Properties[i].IANAToken {
case string(ComponentPropertyAttendee):
a := &Attendee{
event.Properties[i],
}
r = append(r, a)
}
}
return
}
func (event *VEvent) Id() string {
p := event.GetProperty(ComponentPropertyUniqueId)
if p != nil {
return FromText(p.Value)
}
return ""
}
func (event *VEvent) AddAlarm() *VAlarm {
a := &VAlarm{
ComponentBase: ComponentBase{},
}
event.Components = append(event.Components, a)
return a
}
func (event *VEvent) Alarms() (r []*VAlarm) {
r = []*VAlarm{}
for i := range event.Components {
switch alarm := event.Components[i].(type) {
case *VAlarm:
r = append(r, alarm)
}
}
return
}
type VTodo struct {
ComponentBase
}
func (c *VTodo) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "VTODO")
}
func (c *VTodo) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "VTODO")
return b.String()
}
type VJournal struct {
ComponentBase
}
func (c *VJournal) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "VJOURNAL")
}
func (c *VJournal) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "VJOURNAL")
return b.String()
}
type VBusy struct {
ComponentBase
}
func (c *VBusy) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "VBUSY")
return b.String()
}
func (c *VBusy) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "VBUSY")
}
type VTimezone struct {
ComponentBase
}
func (c *VTimezone) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "VTIMEZONE")
return b.String()
}
func (c *VTimezone) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "VTIMEZONE")
}
type VAlarm struct {
ComponentBase
}
func (c *VAlarm) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "VALARM")
return b.String()
}
func (c *VAlarm) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "VALARM")
}
func (alarm *VAlarm) SetAction(a Action, props ...PropertyParameter) {
alarm.SetProperty(ComponentPropertyAction, string(a), props...)
}
func (alarm *VAlarm) SetTrigger(s string, props ...PropertyParameter) {
alarm.SetProperty(ComponentPropertyTrigger, s, props...)
}
type Standard struct {
ComponentBase
}
func (c *Standard) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "STANDARD")
return b.String()
}
func (c *Standard) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "STANDARD")
}
type Daylight struct {
ComponentBase
}
func (c *Daylight) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, "DAYLIGHT")
return b.String()
}
func (c *Daylight) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, "DAYLIGHT")
}
type GeneralComponent struct {
ComponentBase
Token string
}
func (c *GeneralComponent) Serialize() string {
b := &bytes.Buffer{}
c.ComponentBase.serializeThis(b, c.Token)
return b.String()
}
func (c *GeneralComponent) serialize(w io.Writer) {
c.ComponentBase.serializeThis(w, c.Token)
}
func GeneralParseComponent(cs *CalendarStream, startLine *BaseProperty) (Component, error) {
var co Component
switch startLine.Value {
case "VCALENDAR":
return nil, errors.New("malformed calendar; vcalendar not where expected")
case "VEVENT":
co = ParseVEvent(cs, startLine)
case "VTODO":
co = ParseVTodo(cs, startLine)
case "VJOURNAL":
co = ParseVJournal(cs, startLine)
case "VFREEBUSY":
co = ParseVBusy(cs, startLine)
case "VTIMEZONE":
co = ParseVTimezone(cs, startLine)
case "VALARM":
co = ParseVAlarm(cs, startLine)
case "STANDARD":
co = ParseStandard(cs, startLine)
case "DAYLIGHT":
co = ParseDaylight(cs, startLine)
default:
co = ParseGeneralComponent(cs, startLine)
}
return co, nil
}
func ParseVEvent(cs *CalendarStream, startLine *BaseProperty) *VEvent {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &VEvent{
ComponentBase: r,
}
return rr
}
func ParseVTodo(cs *CalendarStream, startLine *BaseProperty) *VTodo {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &VTodo{
ComponentBase: r,
}
return rr
}
func ParseVJournal(cs *CalendarStream, startLine *BaseProperty) *VJournal {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &VJournal{
ComponentBase: r,
}
return rr
}
func ParseVBusy(cs *CalendarStream, startLine *BaseProperty) *VBusy {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &VBusy{
ComponentBase: r,
}
return rr
}
func ParseVTimezone(cs *CalendarStream, startLine *BaseProperty) *VTimezone {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &VTimezone{
ComponentBase: r,
}
return rr
}
func ParseVAlarm(cs *CalendarStream, startLine *BaseProperty) *VAlarm {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &VAlarm{
ComponentBase: r,
}
return rr
}
func ParseStandard(cs *CalendarStream, startLine *BaseProperty) *Standard {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &Standard{
ComponentBase: r,
}
return rr
}
func ParseDaylight(cs *CalendarStream, startLine *BaseProperty) *Daylight {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &Daylight{
ComponentBase: r,
}
return rr
}
func ParseGeneralComponent(cs *CalendarStream, startLine *BaseProperty) *GeneralComponent {
r, err := ParseComponent(cs, startLine)
if err != nil {
return nil
}
rr := &GeneralComponent{
ComponentBase: r,
Token: startLine.Value,
}
return rr
}
func ParseComponent(cs *CalendarStream, startLine *BaseProperty) (ComponentBase, error) {
cb := ComponentBase{}
cont := true
for ln := 0; cont; ln++ {
l, err := cs.ReadLine()
if err != nil {
switch err {
case io.EOF:
cont = false
default:
return cb, err
}
}
if l == nil || len(*l) == 0 {
continue
}
line, err := ParseProperty(*l)
if err != nil {
return cb, fmt.Errorf("parsing component property %d: %w", ln, err)
}
if line == nil {
return cb, errors.New("parsing component line")
}
switch line.IANAToken {
case "END":
switch line.Value {
case startLine.Value:
return cb, nil
default:
return cb, errors.New("unbalanced end")
}
case "BEGIN":
co, err := GeneralParseComponent(cs, line)
if err != nil {
return cb, err
}
if co != nil {
cb.Components = append(cb.Components, co)
}
default: // TODO put in all the supported types for type switching etc.
cb.Properties = append(cb.Properties, IANAProperty{*line})
}
}
return cb, errors.New("ran out of lines")
}