-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
348 lines (299 loc) · 7.68 KB
/
main.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
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/martinlindhe/notify"
)
const (
defaultTimeBeforeNotify = 5 * time.Minute
defaultRefreshPeriod = 10 * time.Minute
timeFormat = "1/02/2006 15:04"
tzFile = "/etc/timezone"
messageAboutOffsets = "if event is in future, probably your timezone is not same as on your server, than please set offset in the CALDAV_SERVER_OFFSET_HOURS env var\n"
notifyEnvIcon = "CALDAV_NOTIFY_ICON"
notifyEnvOffset = "CALDAV_SERVER_OFFSET_HOURS"
notifyEnvRefreshPeriod = "CALDAV_REFRESH_PERIOD_MINUTES"
notifyEnvTimeBefore = "CALDAV_NOTIFY_BEFORE_MINUTES"
notifyEnvWithSound = "CALDAV_NOTIFY_WITH_SOUND"
)
func main() {
// TODO delete on first external contribution
notify.Notify("", "https://github.com/Truenya", "notification daemon started", "")
events := make(chan event)
go planEvents(events)
icon := os.Getenv(notifyEnvIcon)
needSound := os.Getenv(notifyEnvWithSound) != ""
for e := range events {
if needSound {
notify.Alert("", e.Summary, e.Description, icon)
} else {
notify.Notify("", e.Summary, e.Description, icon)
}
}
}
func planEvents(ch chan event) {
planned := map[string]struct{}{}
offset := getOffsetByServer()
period := getRefreshPeriod()
timeBefore := getTimeBeforeNotify()
for {
checkAndRememberEvents(ch, getEvents(offset), planned, timeBefore)
time.Sleep(period)
}
}
func checkAndRememberEvents(ch chan event, events []event, planned map[string]struct{}, timeBefore time.Duration) {
for _, e := range events {
key := e.Summary + e.Start.String()
if _, ok := planned[key]; ok || e.isPast() {
continue
}
go e.notify(ch, timeBefore)
planned[key] = struct{}{}
fmt.Println("planned event:", e.Summary, "at:", e.Start.String())
}
}
func (e event) notify(ch chan event, timeBefore time.Duration) {
dur := time.Until(e.Start) - timeBefore
if dur > 0 {
fmt.Println("sleeping for:", dur, "for event:", e.Summary)
time.Sleep(dur)
}
ch <- e
fmt.Printf("notified for event: %+v", e)
}
func getEvents(offset time.Duration) []event {
out, err := exec.Command("caldav-fetch.py").Output()
if err != nil {
processExitError(err)
}
data := []eventRaw{}
if err := json.Unmarshal(out, &data); err != nil {
panic(err)
}
result := make([]event, len(data))
for i, e := range data {
e, err := eventFromEventRaw(e, offset)
if err != nil {
fmt.Printf("failed to parse event: %+v", e)
continue
}
result[i] = repeatedEventFromEvent(e)
}
return result
}
type eventRaw struct {
Name string
Start string
End string
Datestamp string
Summary string
Description string
Duration string
Rrule *rruleRaw
}
type event struct {
Name string
Summary string
Description string
Start time.Time
End time.Time
CreatedAt time.Time
Rrule *rrule
}
type rruleRaw struct {
Freq []string
Until *string
ByDay []string
Interval []int
}
type rrule struct {
Freq string
Until *time.Time
ByDay map[time.Weekday]struct{}
Interval int
Duration time.Duration
}
func eventFromEventRaw(raw eventRaw, offset time.Duration) (event, error) {
start, err := time.Parse(timeFormat, raw.Start)
if err != nil {
return event{}, err
}
end, _ := time.Parse(timeFormat, raw.End)
datestamp, _ := time.Parse(timeFormat, raw.Datestamp)
if offset == 0 {
// The time comes according to the server time zone, but is read as UTC, so we subtract offset
// Let's assume that the server is in the same zone as the client
// Otherwise, offset must be set in the corresponding environment variable
_, offsetI := time.Now().Zone()
offset = time.Duration(offsetI) * time.Second
}
// change time by timezone of current location
start = start.Add(-offset)
end = end.Add(-offset)
datestamp = datestamp.Add(-offset)
return event{
Name: raw.Name,
Summary: raw.Summary,
Description: raw.Description,
Start: start,
End: end,
CreatedAt: datestamp,
Rrule: readRrule(raw.Rrule, offset, raw.Duration),
}, nil
}
func repeatedEventFromEvent(e event) event {
if e.Rrule == nil || (e.Rrule.Until != nil && e.Rrule.Until.Before(time.Now())) {
return e
}
if !e.Rrule.checkByFreq(e.Start) {
return e
}
today0 := time.Now().UTC().Truncate(24 * time.Hour)
e.Start = today0.Add(offsetFromTime(e.Start))
e.End = e.Start.Add(e.Rrule.Duration)
return e
}
func (r rrule) checkByFreq(start time.Time) bool {
switch r.Freq {
case "WEEKLY":
if r.ByDay == nil {
return false
}
if _, ok := r.ByDay[time.Now().Weekday()]; !ok {
return false
}
_, w := time.Now().ISOWeek()
_, w2 := start.ISOWeek()
return (w2-w)%r.Interval == 0
case "DAILY":
return (start.Day()-time.Now().Day())%r.Interval == 0
case "MONTHLY":
return (int(start.Month())-int(time.Now().Month()))%r.Interval == 0
case "YEARLY":
return (start.Year()-time.Now().Year())%r.Interval == 0
default:
return false
}
}
func offsetFromTime(t time.Time) time.Duration {
h, m, s := t.Clock()
return time.Duration(h)*time.Hour + time.Duration(m)*time.Minute + time.Duration(s)*time.Second
}
func readRrule(raw *rruleRaw, offset time.Duration, dur string) *rrule {
if raw == nil {
return nil
}
res := &rrule{
Freq: getFirst(raw.Freq),
Interval: getFirst(raw.Interval),
Until: parseTime(raw.Until, offset),
Duration: durationFromString(dur),
}
if len(raw.ByDay) == 0 {
return res
}
res.ByDay = make(map[time.Weekday]struct{})
for _, day := range raw.ByDay {
res.ByDay[dayFromString(day)] = struct{}{}
}
return res
}
func getFirst[T any](arr []T) T {
if len(arr) == 0 {
return *new(T)
}
return arr[0]
}
func parseTime(raw *string, offset time.Duration) *time.Time {
if raw == nil {
return nil
}
res, _ := time.Parse(timeFormat, *raw)
res = res.Add(-offset)
return &res
}
func durationFromString(dur string) time.Duration {
tmp := strings.Split(dur, ":")
if len(tmp) < 3 {
return 0
}
dur = tmp[0] + "h" + tmp[1] + "m" + tmp[2] + "s"
res, err := time.ParseDuration(dur)
if err != nil {
return 0
}
return res
}
func dayFromString(day string) time.Weekday {
switch day {
case "MO":
return time.Monday
case "TU":
return time.Tuesday
case "WE":
return time.Wednesday
case "TH":
return time.Thursday
case "FR":
return time.Friday
case "SA":
return time.Saturday
case "SU":
return time.Sunday
default:
return time.Sunday
}
}
func getRefreshPeriod() time.Duration {
period := os.Getenv(notifyEnvRefreshPeriod)
if period == "" {
return defaultRefreshPeriod
}
d, err := strconv.Atoi(period)
if err != nil {
fmt.Println("error parsing refresh period:", err)
return defaultRefreshPeriod
}
return time.Duration(d) * time.Minute
}
func getTimeBeforeNotify() time.Duration {
period := os.Getenv(notifyEnvTimeBefore)
if period == "" {
return defaultTimeBeforeNotify
}
d, err := strconv.Atoi(period)
if err != nil {
fmt.Println("error parsing time before notify:", err)
return defaultTimeBeforeNotify
}
return time.Duration(d) * time.Minute
}
func getOffsetByServer() time.Duration {
offsetHours := os.Getenv(notifyEnvOffset)
if offsetHours == "" {
return 0
}
intOffset, err := strconv.Atoi(offsetHours)
if err != nil {
return 0
}
return time.Duration(intOffset) * time.Hour
}
func processExitError(err error) {
ee := &exec.ExitError{}
if !errors.As(err, &ee) || !strings.Contains(string(ee.Stderr), "Unauthorized") {
fmt.Printf("failed to run caldav-fetch.py: \n%s", err)
os.Exit(1)
}
fmt.Println("Unauthorized. Please check your credentials in python script.")
os.Exit(1)
}
func (e event) isPast() bool {
return e.Start.Before(time.Now()) && e.End.Before(time.Now())
}