-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
611 lines (509 loc) · 18.7 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
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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path"
"regexp"
"strings"
"sync"
"time"
"flag"
"github.com/badkaktus/gorocket"
"github.com/go-resty/resty/v2"
)
const defaultConfigFileName = "config.yml"
var ErrLogin = errors.New("the login was not successfull most likely due to invalid credentails")
const defaultLogFilePath = "/var/log"
const defaultLogFileName = "teamup-rocket-chat.log"
const eventsTrackerFile = "/var/cache/events_tracker.json"
const defaultRepeatIn = 5
const botPrefix = "TEAMUP-ROCKETCHAT-BOT "
var customLogPath = ""
var customConfigFile = ""
// Global logger for writting to log file
var logger *log.Logger
// Wrapper struct to keep track of notified events
// Also will be useful while resuming
type EventsForDay struct {
Day string `json:"day"`
EventIDs []EventIDWithStartTime `json:"event_ids"`
}
type EventIDWithStartTime struct {
EventID string `json:"event_id"`
StartTime string `json:"start_dt"`
}
type AllEvents struct {
DayEvents []EventsForDay `json:"all_events"`
}
// Create events tracking json file if it does not exist
func createJSONFile() {
_, err := os.Stat(eventsTrackerFile)
// TODO: Improvement
// Add better logic
// Not just check if file exists
// but also if content is correct
// If not , write down an empty struct
if errors.Is(err, os.ErrNotExist) {
f, err := os.OpenFile(eventsTrackerFile, os.O_WRONLY|os.O_CREATE, 0640) // 0640 = user can read and write, groups can read
if err != nil {
logger.Fatal(err.Error())
}
defer f.Close()
allEvents := AllEvents{DayEvents: []EventsForDay{}}
writeData, err := json.Marshal(allEvents)
if err != nil {
logger.Fatal(err.Error())
}
_, err = f.Write(writeData)
if err != nil {
logger.Fatal(err.Error())
}
}
}
// reads the events that were already notifed for the given day
func readFromJSONFile(day string) EventsForDay {
var dayEvents *EventsForDay
data, err := os.ReadFile(eventsTrackerFile)
if err != nil {
logger.Fatal(err.Error())
}
var allEvents AllEvents
// Parse the json
err = json.Unmarshal(data, &allEvents)
if err != nil {
logger.Fatal(err.Error())
}
for i := 0; i < len(allEvents.DayEvents); i++ {
if (allEvents.DayEvents[i]).Day == day {
dayEvents = &allEvents.DayEvents[i]
break
}
}
if dayEvents == nil {
return EventsForDay{}
}
return *dayEvents
}
// writes to the events tracker json file
// inside the provided day's object
func writeToJSONFile(day, eventID, startTime string) {
data, err := os.ReadFile(eventsTrackerFile)
if err != nil {
logger.Fatal(err.Error())
}
var allEvents AllEvents
// Parse the json
err = json.Unmarshal(data, &allEvents)
if err != nil {
logger.Fatal(err.Error())
}
var dayEvents *EventsForDay
for i := 0; i < len(allEvents.DayEvents); i++ {
if (allEvents.DayEvents[i]).Day == day {
dayEvents = &allEvents.DayEvents[i]
break
}
}
otherDayEvents := EventsForDay{Day: day, EventIDs: []EventIDWithStartTime{}}
// Means no events have been notified yet
if dayEvents == nil {
dayEvents = &otherDayEvents
// Append the event id to the slice
dayEvents.EventIDs = append(dayEvents.EventIDs, EventIDWithStartTime{EventID: eventID, StartTime: startTime})
allEvents.DayEvents = append(allEvents.DayEvents, *dayEvents)
} else {
// Append the event id to the slice
dayEvents.EventIDs = append(dayEvents.EventIDs, EventIDWithStartTime{EventID: eventID, StartTime: startTime})
}
f, err := os.OpenFile(eventsTrackerFile, os.O_WRONLY|os.O_CREATE, 0644) // 0644 = user can read and write, other and groups can read
if err != nil {
logger.Fatal(err.Error())
}
writeData, err := json.Marshal(allEvents)
if err != nil {
logger.Fatal(err.Error())
}
_, err = f.Write(writeData)
if err != nil {
logger.Fatal(err.Error())
}
f.Close()
}
type TeamupEvent struct {
ID string `json:"id"`
SeriesID interface{} `json:"series_id"`
RemoteID string `json:"remote_id"`
SubcalendarID int `json:"subcalendar_id"`
SubcalendarIds []int `json:"subcalendar_ids"`
AllDay bool `json:"all_day"`
Rrule string `json:"rrule"`
Title string `json:"title"`
Who string `json:"who"`
Location string `json:"location"`
Notes string `json:"notes"`
Version string `json:"version"`
Readonly bool `json:"readonly"`
Tz interface{} `json:"tz"`
Attachments []interface{} `json:"attachments"`
StartDt string `json:"start_dt"`
EndDt string `json:"end_dt"`
RistartDt interface{} `json:"ristart_dt"`
RsstartDt interface{} `json:"rsstart_dt"`
CreationDt time.Time `json:"creation_dt"`
UpdateDt interface{} `json:"update_dt"`
DeleteDt interface{} `json:"delete_dt"`
}
type TeamupEvents struct {
Events []TeamupEvent `json:"events"`
Timestamp int `json:"timestamp"`
}
func checkForMeetings(config *Configuration, chatClient *gorocket.Client) {
locale, _ := time.LoadLocation("Asia/Kathmandu")
now := time.Now().In(locale)
fmt.Println("Trying to check for new meetings at Nepal time:", now)
events, err := fetchMeetingEvents(config)
if err != nil {
logger.Println("Error while fetching events. Please check the error\n", err.Error())
}
today := time.Now().Format("2006-01-02")
if len(events.Events) == 0 {
logger.Println("No meetings found today!!!")
} else {
dayEvents := readFromJSONFile(today)
fmt.Println(dayEvents) // TODO: used for inspection
var futureEvents []TeamupEvent
if len(dayEvents.EventIDs) > 0 {
futureEvents = getFutureEvents(events, dayEvents.EventIDs)
} else {
futureEvents = getFutureEvents(events, []EventIDWithStartTime{})
}
// add logic to send notice for modified events
// with start time later and eventsIDs stored in json
toNotifyEventsIds := []EventIDWithStartTime{}
toSendMsgs := []string{}
for _, event := range futureEvents {
diff := timeDiffWithNow(event.StartDt)
if diff > 10 && diff < 21 {
toNotifyEventsIds = append(toNotifyEventsIds, EventIDWithStartTime{event.ID, event.StartDt})
toSendMsgs = append(toSendMsgs, prepareMeetingMsg(event))
}
}
finalMsg := strings.Join(toSendMsgs, ("\n" + strings.Repeat("-", 100) + "\n"))
if len(finalMsg) > 0 {
// See what msg will be sent
fmt.Println("Trying to send the following messge currently:\n", finalMsg)
msgSent, err := chatClient.PostMessage(&gorocket.Message{Channel: config.Room, Text: finalMsg})
if err != nil {
logger.Printf("Failed to send the message due to following error:\n%s", err.Error())
log.Printf("Failed to send the message due to following error:\n%s", err.Error()) // Print to stdout
return
}
// For checking message sent status
fmt.Println("Message send status: ", msgSent.Success, msgSent.Error)
}
for _, val := range toNotifyEventsIds {
writeToJSONFile(today, val.EventID, val.StartTime)
}
}
}
var logOutput string // for initial output
func init() {
// Set the usage for printing usage info
flag.Usage = displayHelpMessageWithoutBanner
flag.StringVar(&customConfigFile, "config", "", "Point to the configuration (config) file. It overrides the default configuration file located at app directory")
flag.StringVar(&customLogPath, "logpath", "", "Set the custom logpath. It overrides the log path specified in configuration (config.yml) file")
flag.Parse()
log.SetPrefix(botPrefix)
// If no flags are provided, use defaults
fmt.Println(bannerText) // Print the banner, for some cli awesomeness
if len(customConfigFile) == 0 && len(customLogPath) == 0 {
customConfigFile = defaultConfigFileName // Set the default config.yml if no parameter was provided for custom config
logOutput = "No options specified. Looking for configuration at current directory. Directory for log output will be set at location specified in configuration."
} else {
if len(customConfigFile) == 0 {
customConfigFile = defaultConfigFileName
logOutput = "Looking for configuration at current directory."
} else {
logOutput = "Looking for configuration at \"" + customConfigFile + "\"."
}
if len(customLogPath) == 0 {
logOutput += " Setting directory specified by configuration for log output."
} else {
logOutput += " Setting \"" + customLogPath + "\" directory specified by configuration for log output."
}
}
log.Println(logOutput) // Print for the stdout only
}
func main() {
// Show proper log message after crash
defer func() {
if err := recover(); err != nil {
log.Printf("The app suffered a panic due to following\n%v", err)
log.Println("This is probably related to error mentioned above.")
return
}
}()
// Setup logger
// Here, we will use default log path and log file name
// And only change to provided input log path after validation
var defaultPath string
// has CustomPath been used
var isCustomPath bool = false
if len(customLogPath) == 0 {
defaultPath = defaultLogFilePath + "/" + defaultLogFileName
} else {
defaultPath = path.Clean(customLogPath) + "/" + defaultLogFileName
isCustomPath = true
}
defaultLog, err := os.OpenFile(defaultPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) // 0644 = user can read and write, and groups can read
if err != nil {
log.Println(err.Error()) // Also print to stdout
logger.Fatal(err.Error())
}
//defer to close when you're done with it
defer defaultLog.Close()
// set this logger to the global variable
logger = log.New(defaultLog, botPrefix, log.Flags())
config, err := readConfig(customConfigFile, isCustomPath)
// The app will exit if any errors while reading configuration file
if err != nil {
log.Printf("Error while reading configuration file at %q. Please check the error.\n%v\n", customConfigFile, err.Error()) // Also print to stdout
logger.Printf("Error while reading configuration file at %q. Please check the error.\n%v\n", customConfigFile, err.Error()) // Also print to stdout
// if no config parameter was provided and default config.yml could not be read
if len(customConfigFile) == 0 {
log.Println("No config parameter was mentioned and config.yml at appication directory could not read. Please check application usage.")
logger.Println("No config parameter was mentioned and config.yml at appication directory could not read. Please check application usage.")
}
logger.Fatalln("Application terminated")
}
var customPath string
// Override the config's pointed log path if provided from cli
if len(customLogPath) > 0 {
customPath = path.Clean(customLogPath) + "/" + config.LogFileName
} else {
customPath = path.Clean(config.LogPath) + "/" + config.LogFileName
}
customLog, err := os.OpenFile(customPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) // 0644 = user can read and write, other and groups can read
if err != nil {
log.Println(err.Error()) // Also print to stdout
logger.Fatal(err.Error())
}
log.Printf("The file at %q has been been set for log output.\n", customPath)
defer customLog.Close()
// Change the file for logger
logger.SetOutput(customLog)
logger.Println(logOutput) // Initial output for custom log file
logger.Println("Read the following configuration\n", config)
// Create json file if does not exist
createJSONFile()
// login to rocketchat
loginResp, err := UpadatedLogin(config, "api/v1")
if err != nil {
log.Println("Error while trying to login. Please check the error.\n", err.Error()) // Print to stdout
logger.Fatalln("Error while trying to login. Please check the error.\n", err.Error())
}
userIDOpt := gorocket.WithUserID(loginResp.Data.UserID)
xTokenOpt := gorocket.WithXToken(loginResp.Data.AuthToken)
chatClient := gorocket.NewWithOptions(config.URL, userIDOpt, xTokenOpt)
// run this once before cron job
checkForMeetings(config, chatClient)
// Ticker will send a signal at each specified time period
ticker := time.NewTicker(time.Duration(config.RepeatIn) * time.Minute)
wg := &sync.WaitGroup{}
wg.Add(1)
// Run a separate go routine
go func(wg *sync.WaitGroup) {
// Range over the ticker
// Will run each time the ticker ticks, .i.e each 10 mins
for range ticker.C {
// check for meeting
checkForMeetings(config, chatClient)
}
wg.Done()
}(wg)
// Wait for the goroutine to complete
wg.Wait()
}
func UpadatedLogin(config *Configuration, apiVersion string) (*UpdatedLoginResponse, error) {
loginPayload := gorocket.LoginPayload{
User: config.Username,
Password: config.Password,
}
url := fmt.Sprintf("%s/%s/login", config.URL, apiVersion)
client := resty.New()
var errMsg interface{}
result := UpdatedLoginResponse{}
res, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("Accept", "application/json").
SetBody(loginPayload).
SetResult(&result). // set the response to result with required json parsing
SetError(&errMsg).
Post(url)
if err != nil {
return &result, err
} else if res.StatusCode() != 200 {
return &result, fmt.Errorf("%v", fmt.Errorf("recieved status code %v with body\n%v", res.StatusCode(), string(res.Body())))
} else if result.Status != "success" {
return &result, fmt.Errorf("%v", fmt.Errorf("recieved status code %v with body\n%v", res.StatusCode(), string(res.Body())))
}
// success auth
return &result, nil
}
// fetchMeetingEvents fetches events for the day
// for the meetings sub-calendar
func fetchMeetingEvents(config *Configuration) (*TeamupEvents, error) {
startDate := time.Now().Format("2006-01-02")
url := fmt.Sprintf("https://api.teamup.com/%s/events?startDate=%v&endDate=%v", config.MeetingsCode, startDate, startDate)
client := resty.New()
result := TeamupEvents{} // empty struct
var errMsg interface{}
res, err := client.R().
SetHeader("Accept", "application/json").
SetHeader("Teamup-Token", config.TeamupToken).
SetResult(&result). // set the response to result with required json parsing
SetError(&errMsg).
Get(url)
if err != nil {
return &result, err
} else if res.StatusCode() != 200 {
return &result, fmt.Errorf("%v", fmt.Errorf("recieved status code %v with body\n%v", res.StatusCode(), string(res.Body())))
}
return &result, nil
}
// timeDiffWithNow returns the time difference (in minutes) between provided time
// and the current time based on unix timestamp
// Example: dateTime = "2023-01-04T07:00:00+05:45"
// Return -1 if any errors
func timeDiffWithNow(dateTime string) int64 {
epochNow := time.Now().Unix()
timeGiven, err := time.Parse(time.RFC3339, dateTime)
if err != nil {
fmt.Println("Error while converting time stamps")
return -1
}
epochGiven := timeGiven.Unix()
diff := epochGiven - epochNow
mins := (diff / 60)
return mins
}
// returns time difference (in mins) between two time stamps
// Example: dateTime = "2023-01-04T07:00:00+05:45"
func timeDiffBetween(less, more string) int64 {
timeLess, err := time.Parse(time.RFC3339, less)
if err != nil {
fmt.Println("Error while converting time stamps")
return -1
}
timeMore, err := time.Parse(time.RFC3339, more)
if err != nil {
fmt.Println("Error while converting time stamps")
return -1
}
epochLess := timeLess.Unix()
epochMore := timeMore.Unix()
diff := epochMore - epochLess
mins := (diff / 60)
return mins
}
// getFutureEvents returns a slice of future events
// from the current time period
func getFutureEvents(events *TeamupEvents, alreadyNotified []EventIDWithStartTime) []TeamupEvent {
futureEvents := []TeamupEvent{}
for _, ev := range events.Events {
diff := timeDiffWithNow(ev.StartDt)
// Events yet to come is added to slice
if diff > 0 {
shouldAdd := true
// Loop through noticeIDs to check if it was already notified
for _, val := range alreadyNotified {
d := timeDiffBetween(val.StartTime, ev.StartDt)
if val.EventID == ev.ID && d == 0 {
shouldAdd = false
break
}
}
// Add if the flag is true, i.e the id is not listed in already notified
if shouldAdd {
futureEvents = append(futureEvents, ev)
}
}
}
return futureEvents
}
// prepareMeetingMsg prepares message to be
// sent for the upcoming event
// with following format
//
// @mentions *Event title* will start soon
// Start-time: 10:00
// let's meet in:
// Some description
// of the meeting
func prepareMeetingMsg(event TeamupEvent) string {
title := event.Title
who := event.Who
locale, _ := time.LoadLocation("Asia/Kathmandu")
startTime, _ := time.Parse(time.RFC3339, event.StartDt) // Parse the time in locale time
location := event.Location
notes := event.Notes
description := strings.Split(notes, "\n")
descSlice := make([]string, 0)
// Catches the html tags present
removeTag := regexp.MustCompile(`<\/?[^>]+(>|$)`) // Create a global func for this
// Catches the whole line containing Who: @mention1 @mention2
removeMention := regexp.MustCompile(`^(Who|who):\s*@.*$`) // Create a global func for this
// Trim the white space, remove html tags, remove "Who: @"
for i := 0; i < len(description); i++ {
str := strings.TrimSpace(description[i])
str = removeTag.ReplaceAllString(str, "")
str = removeMention.ReplaceAllString(str, "")
// Only add the non-empty lines
if len(str) > 0 {
descSlice = append(descSlice, str)
}
}
finalDesc := strings.Join(descSlice, "\n")
msg := fmt.Sprintf("%s *%s* will start soon\nStart-time: *%s*\nlet's meet in: %s\n%s",
who,
title,
strings.Split(startTime.In(locale).String(), "+")[0],
location,
finalDesc,
)
return msg
}
// Some struct definitions
type UpdatedMe struct {
ID string `json:"_id"`
Services gorocket.Services `json:"services"`
Emails []gorocket.Email `json:"emails"`
Status string `json:"status"`
Active bool `json:"active"`
UpdatedAt time.Time `json:"_updatedAt"`
Roles []string `json:"roles"`
Name string `json:"name"`
StatusConnection string `json:"statusConnection"`
Username string `json:"username"`
UtcOffset float64 `json:"utcOffset"`
StatusText string `json:"statusText"`
Settings gorocket.Settings `json:"settings"`
AvatarOrigin string `json:"avatarOrigin"`
RequirePasswordChange bool `json:"requirePasswordChange"`
Language string `json:"language"`
Email string `json:"email"`
AvatarURL string `json:"avatarUrl"`
}
type UpdatedDataLogin struct {
UserID string `json:"userId"`
AuthToken string `json:"authToken"`
Me UpdatedMe `json:"me"`
}
type UpdatedLoginResponse struct {
Status string `json:"status"`
Data UpdatedDataLogin `json:"data"`
Message string `json:"message,omitempty"`
}