-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
303 lines (257 loc) · 6.96 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
package main
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"io"
"log"
"net/http"
"reflect"
"regexp"
"strings"
"time"
"github.com/akarnani/webcal_sync/gcal"
"github.com/apognu/gocal"
"google.golang.org/api/calendar/v3"
"google.golang.org/api/googleapi"
)
var dateFormatFix = regexp.MustCompile(`(?m)^(DTSTAMP:.*)T(.*)$`)
func parseICal(url string) []gocal.Event {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal("Failed to read calendar body")
}
//This is really remarkably dumb but some sources give back garbage
body := bytes.NewReader(dateFormatFix.ReplaceAll(b, []byte("$1")))
c := gocal.NewParser(body)
c.Strict = gocal.StrictParams{
Mode: gocal.StrictModeFailAttribute,
}
if err := c.Parse(); err != nil {
panic(err)
}
//"clever" way to trim whitespace on all string fields
for _, e := range c.Events {
v := reflect.ValueOf(&e).Elem()
for i := 0; i < v.Type().NumField(); i++ {
f := v.Field(i)
if f.Kind() == reflect.String {
f.SetString(strings.TrimSpace(f.String()))
}
}
}
return c.Events
}
func diffEvents(cfg Config, up []gocal.Event, gevent []*calendar.Event) ([]*calendar.Event, []*calendar.Event, []string) {
var create []*calendar.Event
var update []*calendar.Event
ids := make(map[string]*calendar.Event)
for _, e := range gevent {
ids[e.ICalUID] = e
}
seenIds := make(map[string]interface{})
for _, e := range up {
if (*e.Start).Before(time.Now()) {
continue
}
i := getIDForEvent(cfg, e)
if _, ok := seenIds[i]; ok {
log.Printf("ID %s is a duplicate, not processing", i)
continue
}
seenIds[i] = nil
g, ok := ids[i]
delete(ids, i)
if !ok {
//create event
create = append(create, iCalToGEvent(cfg, e))
continue
}
changed := false
n := &calendar.Event{
Id: g.Id,
}
if e.Summary != g.Summary {
n.Summary = e.Summary
changed = true
}
ts := parseGCalTime(g.Start)
te := parseGCalTime(g.End)
allDay := isAllDayEvent(e)
if !compareDateTime(ts, *e.Start) || (allDay && g.Start.DateTime != "") {
n.Start = getEventTime(*e.Start, allDay)
changed = true
}
// if all day only the date matters. However gocal's end time is 1 milisecond before
// the next day which makes comparing dates hard. So, just truncate the time for simplicity
if allDay {
*e.End = e.End.Truncate(24 * time.Hour)
}
if !compareDateTime(te, *e.End) || (allDay && g.End.DateTime != "") {
n.End = getEventTime(*e.End, allDay)
changed = true
}
if e.Description != g.Description {
n.Description = e.Description
n.ForceSendFields = append(n.ForceSendFields, "Description")
changed = true
}
if e.Location != g.Location {
n.Location = e.Location
n.ForceSendFields = append(n.ForceSendFields, "Location")
changed = true
}
if cfg.ColorID != g.ColorId {
n.ColorId = cfg.ColorID
changed = true
}
if g.Status != "confirmed" {
n.Status = "confirmed"
changed = true
}
if cfg.Reminder != 0 {
//reminder configured
if g.Reminders == nil || len(g.Reminders.Overrides) == 0 || g.Reminders.Overrides[0].Minutes != int64(cfg.Reminder) || g.Reminders.UseDefault {
n.Reminders = getReminderForConfig(cfg)
changed = true
}
} else {
//reminder not configured
if g.Reminders != nil {
n.Reminders = &calendar.EventReminders{
ForceSendFields: []string{"Overrides"},
}
changed = true
}
}
if changed {
update = append(update, n)
}
}
del := make([]string, 0, len(ids))
for _, e := range ids {
if e.Status != "cancelled" {
t, err := time.Parse(time.RFC3339, e.Start.DateTime)
if err != nil {
log.Fatalf("Unable to parse canceled date time %s: %v", e.Start.DateTime, err)
}
if time.Now().Before(t) {
del = append(del, e.Id)
} else {
log.Printf("Not deleting event %s because it already started", e.Summary)
}
}
}
return create, update, del
}
func iCalToGEvent(cfg Config, e gocal.Event) *calendar.Event {
allDay := isAllDayEvent(e)
return &calendar.Event{
Summary: jsonEscape(e.Summary),
Location: jsonEscape(e.Location),
Description: jsonEscape(e.Description),
Start: getEventTime(*e.Start, allDay),
End: getEventTime(*e.End, allDay),
ICalUID: getIDForEvent(cfg, e),
ColorId: cfg.ColorID,
ExtendedProperties: &calendar.EventExtendedProperties{
Private: map[string]string{"url": fmt.Sprintf("%x", sha256.Sum256([]byte(cfg.URL)))},
},
Reminders: getReminderForConfig(cfg),
}
}
func getReminderForConfig(cfg Config) *calendar.EventReminders {
if cfg.Reminder == 0 { //zero value means not specified
return nil
}
return &calendar.EventReminders{
Overrides: []*calendar.EventReminder{
{
Method: "popup",
Minutes: int64(cfg.Reminder),
},
},
ForceSendFields: []string{
"UseDefault",
},
}
}
func getIDForEvent(cfg Config, e gocal.Event) string {
switch cfg.IDFormat {
case "url":
return fmt.Sprintf("%x", sha256.Sum256([]byte(e.URL)))
case "":
return e.Uid
default:
log.Panicf("unknown id format %s", cfg.IDFormat)
}
//can't be reached due to default's Panicf
return ""
}
func isAllDayEvent(e gocal.Event) bool {
return e.RawStart.Params["VALUE"] == "DATE" || e.RawEnd.Params["VALUE"] == "DATE"
}
func compareDateTime(x, y time.Time) bool {
return x.Truncate(time.Second).Equal(y.Truncate(time.Second))
}
func getEventTime(t time.Time, allDay bool) *calendar.EventDateTime {
if allDay {
return &calendar.EventDateTime{
Date: t.Format("2006-01-02"),
NullFields: []string{"DateTime"},
}
}
return &calendar.EventDateTime{
DateTime: t.Truncate(time.Second).Format(time.RFC3339),
NullFields: []string{"Date"},
}
}
func parseGCalTime(t *calendar.EventDateTime) time.Time {
if t.Date != "" {
out, err := time.Parse("2006-01-02", t.Date)
if err != nil {
log.Fatalf("Unable to parse date %s: %v", t.Date, err)
}
return out
}
out, err := time.Parse(time.RFC3339, t.DateTime)
if err != nil {
log.Fatalf("Unable to parse date time %s: %v", t.DateTime, err)
}
return out
}
func main() {
client := gcal.NewClient()
for _, cfg := range getConfig() {
log.Printf("Starting on calendar %s", cfg.URL)
c, u, d := diffEvents(cfg, parseICal(cfg.URL), client.GetEventsForAttribute(map[string]string{"url": fmt.Sprintf("%x", sha256.Sum256([]byte(cfg.URL)))}))
log.Println(cfg.URL, len(c), len(u), len(d))
for _, e := range c {
if err := client.CreateEvent(e); err != nil {
var gErr *googleapi.Error
if errors.As(err, &gErr) && gErr.Code == http.StatusConflict {
log.Printf("Event already existed: %v, %v", e, gErr)
continue
}
log.Fatalf("failed to create event: %v", err)
}
}
for _, e := range u {
if err := client.UpdateEvent(e); err != nil {
log.Fatalf("failed to update event: %v", err)
}
}
for _, id := range d {
if err := client.DeleteEvent(id); err != nil {
log.Fatalf("failed to update event: %v", err)
}
}
log.Printf("finished with calendar")
}
}