-
Notifications
You must be signed in to change notification settings - Fork 1
/
reminders.go
132 lines (99 loc) · 2.35 KB
/
reminders.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
package main
import (
"fmt"
"sort"
"sync"
"time"
)
type reminderTimer struct {
send func(*calendarEvent)
forDuration time.Duration
reminderTimes []time.Duration
cal queryableCalendar
stopTimer chan struct{}
stopTimerMutex sync.Mutex
}
func newReminderTimer(send func(*calendarEvent), forDuration time.Duration, cal queryableCalendar, reminderTimes []time.Duration) reminderTimer {
return reminderTimer{
send: send,
forDuration: forDuration,
reminderTimes: reminderTimes,
cal: cal,
}
}
func (t *reminderTimer) set() error {
reminders, err := t.createReminders()
if err != nil {
return err
}
t.stopTimerMutex.Lock()
defer t.stopTimerMutex.Unlock()
if t.stopTimer != nil {
t.stopTimer <- struct{}{}
}
t.stopTimer = make(chan struct{}, 1)
go reminderLoop(reminders, t.stopTimer, t.send)
return nil
}
func (t *reminderTimer) createReminders() ([]reminder, error) {
evs, err := t.cal.eventsBetween(time.Now(), time.Now().Add(t.forDuration).Add(t.highestReminderTime()))
if err != nil {
return []reminder{}, err
}
rems := []reminder{}
for _, ev := range evs {
for _, remT := range t.reminderTimes {
remTime := ev.from.Add(-remT)
if time.Now().Before(remTime) {
remPre := reminder{
when: remTime,
event: ev,
}
rems = append(rems, remPre)
}
}
}
sort.Sort(reminders(rems))
return rems, nil
}
func reminderLoop(reminders []reminder, stop <-chan struct{}, send func(*calendarEvent)) {
for {
if len(reminders) == 0 {
break
}
next := reminders[0]
fmt.Println("Setup reminder for: " + next.event.text)
select {
case <-stop:
fmt.Println("Reminderloop stopped")
break
case <-time.After(time.Until(next.when)):
send(next.event)
fmt.Println("Reminder for:", next.event.text, next.event.from.Sub(time.Now()))
reminders = append([]reminder{}, reminders[1:]...)
}
}
}
func (t reminderTimer) highestReminderTime() time.Duration {
highest := 0 * time.Second
for _, remT := range t.reminderTimes {
if remT > highest {
highest = remT
}
}
return highest
}
type reminder struct {
when time.Time
event *calendarEvent
}
type reminders []reminder
func (r reminders) Len() int {
return len(r)
}
func (r reminders) Less(i, j int) bool {
return r[i].when.Unix() < r[j].when.Unix()
}
func (r reminders) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}