-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathroutines.go
345 lines (277 loc) · 9.49 KB
/
routines.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
// @license
// Copyright (C) 2022 Dinko Korunic
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/blang/semver/v4"
"github.com/dkorunic/e-dnevnik-bot/db"
"github.com/dkorunic/e-dnevnik-bot/logger"
"github.com/dkorunic/e-dnevnik-bot/messenger"
"github.com/dkorunic/e-dnevnik-bot/msgtypes"
"github.com/dkorunic/e-dnevnik-bot/scrape"
"github.com/dustin/go-broadcast"
"github.com/google/go-github/v68/github"
"github.com/tj/go-spin"
)
const (
broadcastBufLen = 10 // events to broadcast for sending at once
spinnerRotateDelay = 100 * time.Millisecond // spinner delay
githubOrg = "dkorunic"
githubRepo = "e-dnevnik-bot"
)
var (
ErrScrapingUser = errors.New("error scraping data for user")
ErrDiscord = errors.New("Discord messenger issue") //nolint:stylecheck
ErrTelegram = errors.New("Telegram messenger issue") //nolint:stylecheck
ErrSlack = errors.New("Slack messenger issue") //nolint:stylecheck
ErrMail = errors.New("Mail messenger issue") //nolint:stylecheck
ErrCalendar = errors.New("Google Calendar issue") //nolint:stylecheck
formatHRDateOnly = "2.1."
)
// scrapers will call subjects/grades/exams scraping for every configured AAI/AOSI user and send grades/exams messages
// to a channel.
func scrapers(ctx context.Context, wgScrape *sync.WaitGroup, gradesScraped chan<- msgtypes.Message, config tomlConfig) {
logger.Debug().Msg("Starting scrapers")
for _, i := range config.User {
wgScrape.Add(1)
go func() {
defer wgScrape.Done()
err := scrape.GetGradesAndEvents(ctx, gradesScraped, i.Username, i.Password, *retries)
if err != nil {
logger.Warn().Msgf("%v %v: %v", ErrScrapingUser, i.Username, err)
exitWithError.Store(true)
}
}()
}
}
// msgSend will process grades/exams messages and broadcast to one or more message services.
func msgSend(ctx context.Context, wgMsg *sync.WaitGroup, gradesMsg <-chan msgtypes.Message, config tomlConfig) {
wgMsg.Add(1)
go func() {
defer wgMsg.Done()
bcast := broadcast.NewBroadcaster(broadcastBufLen)
defer bcast.Close()
// Discord sender
if config.discordEnabled {
ch := make(chan interface{}) // broadcast listener
defer close(ch)
bcast.Register(ch) // broadcast registration
defer bcast.Unregister(ch)
wgMsg.Add(1)
go func() {
defer wgMsg.Done()
logger.Debug().Msg("Discord messenger started")
if err := messenger.Discord(ctx, ch, config.Discord.Token, config.Discord.UserIDs, *retries); err != nil {
logger.Warn().Msgf("%v: %v", ErrDiscord, err)
exitWithError.Store(true)
}
}()
}
// Telegram sender
if config.telegramEnabled {
ch := make(chan interface{}) // broadcast listener
defer close(ch)
bcast.Register(ch) // broadcast registration
defer bcast.Unregister(ch)
wgMsg.Add(1)
go func() {
defer wgMsg.Done()
logger.Debug().Msg("Telegram messenger started")
if err := messenger.Telegram(ctx, ch, config.Telegram.Token, config.Telegram.ChatIDs, *retries); err != nil {
logger.Warn().Msgf("%v: %v", ErrTelegram, err)
exitWithError.Store(true)
}
}()
}
// Slack sender
if config.slackEnabled {
ch := make(chan interface{}) // broadcast listener
defer close(ch)
bcast.Register(ch) // broadcast registration
defer bcast.Unregister(ch)
wgMsg.Add(1)
go func() {
defer wgMsg.Done()
logger.Debug().Msg("Slack messenger started")
if err := messenger.Slack(ctx, ch, config.Slack.Token, config.Slack.ChatIDs, *retries); err != nil {
logger.Warn().Msgf("%v: %v", ErrSlack, err)
exitWithError.Store(true)
}
}()
}
// mail Sender
if config.mailEnabled {
ch := make(chan interface{}) // broadcast listener
defer close(ch)
bcast.Register(ch) // broadcast registration
defer bcast.Unregister(ch)
wgMsg.Add(1)
go func() {
defer wgMsg.Done()
logger.Debug().Msg("Mail messenger started")
if err := messenger.Mail(ctx, ch, config.Mail.Server, config.Mail.Port, config.Mail.Username, config.Mail.Password, config.Mail.From, config.Mail.Subject, config.Mail.To, *retries); err != nil {
logger.Warn().Msgf("%v: %v", ErrMail, err)
exitWithError.Store(true)
}
}()
}
// Google Calendar Sender
if config.calendarEnabled {
ch := make(chan interface{}) // broadcast listener
defer close(ch)
bcast.Register(ch) // broadcast registration
defer bcast.Unregister(ch)
wgMsg.Add(1)
go func() {
defer wgMsg.Done()
logger.Debug().Msgf("Calendar messenger started")
if err := messenger.Calendar(ctx, ch, config.Calendar.Name, *calTokFile, *retries); err != nil {
logger.Warn().Msgf("%v: %v", ErrCalendar, err)
exitWithError.Store(true)
}
}()
}
// broadcast incoming messages
for g := range gradesMsg {
select {
case <-ctx.Done():
return
default:
bcast.Submit(g)
}
}
}()
}
// msgDedup acts like a filter: processes all incoming messages, calls in to database check and if it hasn't been found
// and if it is not an initial run, it will pass through to messengers for further alerting.
func msgDedup(ctx context.Context, wgFilter *sync.WaitGroup, gradesScraped <-chan msgtypes.Message, gradesMsg chan<- msgtypes.Message) {
wgFilter.Add(1)
go func() {
defer wgFilter.Done()
// open KV store
eDB, err := db.New(*dbFile)
if err != nil {
logger.Fatal().Msgf("Unable to open database: %v", err)
}
defer eDB.Close()
if !eDB.Existing() {
logger.Info().Msg("Newly initialized database, won't sent alerts in this run")
}
// cache current time for later
now := time.Now()
for g := range gradesScraped {
select {
case <-ctx.Done():
return
default:
// log all events
if *debugEvents {
logger.Debug().Msgf("Received event for: %v/%v: %+v", g.Username, g.Subject, g)
}
// check if it is an already known alert
found, err := eDB.CheckAndFlag(g.Username, g.Subject, g.Fields)
if err != nil {
logger.Fatal().Msgf("Problem with database, cannot continue: %v", err)
}
// check if is the initial run and send only if not
if !found && eDB.Existing() {
// check if it is an old event that should be ignored
if *relevancePeriod > 0 && !g.IsExam && len(g.Fields) > 0 {
t, err := time.Parse(formatHRDateOnly, g.Fields[0])
if err != nil {
logger.Error().Msgf("Unable to parse date for: %v/%v: %+v: %v", g.Username, g.Subject, g, err)
} else {
// assume current or previous year
if t.Month() > now.Month() {
t = t.AddDate(now.Year()-1, 0, 0)
} else {
t = t.AddDate(now.Year(), 0, 0)
}
if time.Since(t) > *relevancePeriod {
logger.Warn().Msgf("Ignoring changes in an old event: %v/%v: %+v", g.Username, g.Subject, g)
continue
}
}
}
logger.Info().Msgf("New alert for: %v/%v: %+v", g.Username, g.Subject, g)
gradesMsg <- g
}
}
}
close(gradesMsg)
}()
}
// spinner shows a spiffy terminal spinner while waiting endlessly.
func spinner() {
s := spin.New()
for {
fmt.Printf("\rWaiting... %v", s.Next())
time.Sleep(spinnerRotateDelay)
}
}
func versionCheck(ctx context.Context, wgVersion *sync.WaitGroup) {
wgVersion.Add(1)
go func() {
defer wgVersion.Done()
// if we don't have a tag or if it is a local source-build, we don't need to check for updates
if GitTag == "" || GitDirty != "" {
return
}
var currentTag, latestTag semver.Version
var err error
// semver-parse current version
if GitTag[0] == 'v' {
currentTag, err = semver.Parse(GitTag[1:])
} else {
currentTag, err = semver.Parse(GitTag)
}
if err != nil {
logger.Error().Msgf("Unable to parse current version of e-dnevnik-bot: %v", err)
return
}
client := github.NewClient(nil)
// get latest release from GitHub
latestRelease, _, err := client.Repositories.GetLatestRelease(ctx, githubOrg, githubRepo)
if err != nil {
logger.Error().Msgf("Unable to check latest version of e-dnevnik-bot: %v", err)
return
}
// semver-parse latest version
tagName := *latestRelease.TagName
if tagName[0] == 'v' {
latestTag, err = semver.Parse(tagName[1:])
} else {
latestTag, err = semver.Parse(tagName)
}
if err != nil {
logger.Error().Msgf("Unable to parse latest version of e-dnevnik-bot: %v", err)
return
}
// alert if there is a newer version
if latestTag.Compare(currentTag) == 1 {
logger.Info().Msgf("Newer version of e-dnevnik-bot is available: %v", latestTag)
}
}()
}