~psic4t/qcal

ref: 25fece6e89e37881e36f386c5436ebda68172e34 qcal/parse.go -rw-r--r-- 7.1 KiB
25fece6epsic4t fix description newlines 3 months ago
                                                                                
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
package main

import (
	//"encoding/json"
	"fmt"
	// 	"log"
	duration "github.com/channelmeter/iso8601duration"
	"regexp"
	"strings"
	"time"
)

var (
	eventRRuleRegex      = regexp.MustCompile(`RRULE:.*?\n`)
	freqRegex            = regexp.MustCompile(`FREQ=.*?;`)
	eventSummaryRegex    = regexp.MustCompile(`SUMMARY:.*?\n`)
	eventFreqWeeklyRegex = regexp.MustCompile(`RRULE:FREQ=WEEKLY\n`)
	eventFreqYearlyRegex = regexp.MustCompile(`RRULE:FREQ=YEARLY\n`)
)

//  unixtimestamp
const (
	uts = "1136239445"
	//ics date time format
	// Y-m-d H:i:S time format
	YmdHis = "2006-01-02 15:04:05"
)

func trimField(field, cutset string) string {
	re, _ := regexp.Compile(cutset)
	cutsetRem := re.ReplaceAllString(field, "")
	return strings.TrimRight(cutsetRem, "\r\n")
}

func explodeEvent(eventData *string) (string, string) {
	reEvent, _ := regexp.Compile(`(BEGIN:VEVENT(.*\n)*?END:VEVENT\r?\n)`)
	Event := reEvent.FindString(*eventData)
	calInfo := reEvent.ReplaceAllString(*eventData, "")
	return Event, calInfo
}
func splitIcal(ical string) []string {
	splits := regexp.MustCompile(`(BEGIN:VEVENT(.*\n)*?END:VEVENT\r?\n)`)
	//reEvent, _ := regexp.Compile(`(BEGIN:VEVENT(.*\n)*?END:VEVENT\r?\n)`)
	Events := splits.FindAllString(ical, -1)
	/*for i := range Events {
		//fmt.Println(eventData)
		fmt.Println(i)
		fmt.Println(Events[i])
	}*/
	//fmt.Println(splits[21])
	//os.Exit(1)
	return Events
}

func parseIcalName(eventData string) string {
	re, _ := regexp.Compile(`X-WR-CALNAME:.*?\n`)
	result := re.FindString(eventData)
	return trimField(result, "X-WR-CALNAME:")
}

func parseTimeField(fieldName string, eventData string) (time.Time, string) {
	reWholeDay, _ := regexp.Compile(fmt.Sprintf(`%s;VALUE=DATE:.*?\n`, fieldName))
	//re, _ := regexp.Compile(fmt.Sprintf(`%s(;TZID=(.*?))?(;VALUE=DATE-TIME)?:(.*?)\n`, fieldName))
	// correct regex: .+:(.+)$
	re, _ := regexp.Compile(fmt.Sprintf(`%s(;TZID=(.+))?(;VALUE=DATE-TIME)?:(.+?)\n`, fieldName))
	//re, _ := regexp.Compile(fmt.Sprintf(`%s(;TZID=(.*?))(;VALUE=DATE-TIME)?:(.*?)\n`, fieldName))

	resultWholeDay := reWholeDay.FindString(eventData)
	var t time.Time
	var thisTime time.Time
	//var thisTime time.Time
	//var datetime time.Time
	var tzID string
	var format string

	if resultWholeDay != "" {
		// whole day event
		modified := trimField(resultWholeDay, fmt.Sprintf("%s;VALUE=DATE:", fieldName))
		t, _ = time.Parse(IcsFormatWholeDay, modified)
	} else {
		// event that has start hour and minute
		result := re.FindStringSubmatch(eventData)

		if result == nil || len(result) < 4 {
			return t, tzID
		}

		tzID = result[2]
		dt := strings.Trim(result[4], "\r") // trim that newlines!

		if strings.HasSuffix(dt, "Z") {
			// If string ends in 'Z', timezone is UTC
			format = "20060102T150405Z"
			thisTime, _ := time.Parse(format, dt)
			//fmt.Println(thisTime)
			t = thisTime.Local()
		} else if tzID != "" {
			format = "20060102T150405"
			location, err := time.LoadLocation(tzID)
			// if tzID not readable use configured timezone
			if err != nil {
				location, _ = time.LoadLocation(config.Timezone)
				// timezone from defines gives CEST, which is not working with parseinlocation:
				//location, _ = time.LoadLocation(timezone)
			}
			// set foreign timezone
			thisTime, _ = time.ParseInLocation(format, dt, location)
			// convert to local timezone
			//t = time.In(myLocation)
			t = thisTime.Local()
		} else {
			// Else, consider the timezone is local the parser
			format = "20060102T150405"
			t, _ = time.Parse(format, dt)
			//fmt.Println(t)
		}

	}

	return t, tzID
}

func parseEventStart(eventData *string) (time.Time, string) {
	return parseTimeField("DTSTART", *eventData)
}

func parseEventEnd(eventData *string) (time.Time, string) {
	return parseTimeField("DTEND", *eventData)
}

func parseEventDuration(eventData *string) time.Duration {
	reDuration, _ := regexp.Compile(`DURATION:.*?\n`)
	result := reDuration.FindString(*eventData)
	trimmed := trimField(result, "DURATION:")
	parsedDuration, err := duration.FromString(trimmed)
	var output time.Duration

	if err == nil {
		output = parsedDuration.ToDuration()
	}

	return output
}

func parseEventSummary(eventData *string) string {
	re, _ := regexp.Compile(`SUMMARY(?:;LANGUAGE=[a-zA-Z\-]+)?.*?\n`)
	result := re.FindString(*eventData)
	return trimField(result, `SUMMARY(?:;LANGUAGE=[a-zA-Z\-]+)?:`)
}

func parseEventDescription(eventData *string) string {
	re, _ := regexp.Compile(`DESCRIPTION:.*?\n(?:\s+.*?\n)*`)

	resultA := re.FindAllString(*eventData, -1)
	result := strings.Join(resultA, ", ")
	result = strings.Replace(result, "\n", "", -1)

	result = strings.Replace(result, "\\N", "\n", -1)
	//better := strings.Replace(re.FindString(result), "\n ", "", -1)
	//better = strings.Replace(better, "\\n", " ", -1)
	//better = strings.Replace(better, "\\", "", -1)

	//return trimField(better, "DESCRIPTION:")
	//return trimField(result, "DESCRIPTION:")
	return trimField(strings.Replace(result, "\r\n ", "", -1), "DESCRIPTION:")
}

func parseEventLocation(eventData *string) string {
	re, _ := regexp.Compile(`LOCATION:.*?\n`)
	result := re.FindString(*eventData)
	return trimField(result, "LOCATION:")
}

func parseEventRRule(eventData *string) string {
	re, _ := regexp.Compile(`RRULE:.*?\n`)
	result := re.FindString(*eventData)
	return trimField(result, "RRULE:")
}

func parseEventFreq(eventData *string) string {
	re, _ := regexp.Compile(`FREQ=[^;]*(;){0,1}`)
	result := re.FindString(parseEventRRule(eventData))
	return trimField(result, `(FREQ=|;)`)
}

func parseICalTimezone(eventData *string) time.Location {
	re, _ := regexp.Compile(`X-WR-TIMEZONE:.*?\n`)
	result := re.FindString(*eventData)

	// parse the timezone result to time.Location
	timezone := trimField(result, "X-WR-TIMEZONE:")
	// create location instance
	loc, err := time.LoadLocation(timezone)

	// if fails with the timezone => go Local
	if err != nil {
		loc, _ = time.LoadLocation("UTC")
	}
	return *loc
}

func parseMain(eventData *string, elementsP *[]Event, href, color string) {
	eventStart, tzId := parseEventStart(eventData)
	eventEnd, tzId := parseEventEnd(eventData)
	eventDuration := parseEventDuration(eventData)
	freq := parseEventFreq(eventData)

	if eventEnd.Before(eventStart) {
		eventEnd = eventStart.Add(eventDuration)
	}

	start, _ := time.Parse(IcsFormat, startDate)
	end, _ := time.Parse(IcsFormat, endDate)
	//fmt.Println(eventStart)

	var years, days, months int
	switch freq {
	case "DAILY":
		days = 1
		months = 0
		years = 0
		break
	case "WEEKLY":
		days = 7
		months = 0
		years = 0
		break
	case "MONTHLY":
		days = 0
		months = 1
		years = 0
		break
	case "YEARLY":
		days = 0
		months = 0
		years = 1
		break
	}
	//fmt.Println(eventStart)

	for {
		if inTimeSpan(start, end, eventStart) {
			data := Event{
				Href:        href,
				Color:       color,
				Start:       eventStart,
				End:         eventEnd,
				TZID:        tzId,
				Summary:     parseEventSummary(eventData),
				Description: parseEventDescription(eventData),
				Location:    parseEventLocation(eventData),
			}
			*elementsP = append(*elementsP, data)

		}

		if freq == "" {
			break
		}

		eventStart = eventStart.AddDate(years, months, days)
		eventEnd = eventEnd.AddDate(years, months, days)

		// TODO: support UNTIL
		if eventStart.After(end) {
			break
		}
	}
}