-
Notifications
You must be signed in to change notification settings - Fork 0
/
cron_irc.go
383 lines (337 loc) · 10.3 KB
/
cron_irc.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
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/osm/irc"
)
// cronAddLimitRegexp contains the regular expression used to add cron jobs
// with an execution limit.
var cronAddLimitRegexp *regexp.Regexp
// cronGrammarGiphySearchRegexp contains the regexp that finds
// <giphy search"xxx"> tags.
var cronGrammarGiphySearchRegexp *regexp.Regexp
// cronGrammarTenorSearchRegexp contains the regexp that finds
// <tenor search"xxx"> tags.
var cronGrammarTenorSearchRegexp *regexp.Regexp
// initCronDefaults sets default values for all settings.
func (b *bot) initCronDefaults() {
// Command and sub commands.
if b.IRC.CronCmd == "" {
b.IRC.CronCmd = "!cron"
}
if b.IRC.CronSubCmdAdd == "" {
b.IRC.CronSubCmdAdd = "add"
}
if b.IRC.CronSubCmdAddLimit == "" {
b.IRC.CronSubCmdAddLimit = "limit"
}
cronAddLimitRegexp = regexp.MustCompile("^" + b.IRC.CronSubCmdAddLimit + ":([0-9]+) ")
if b.IRC.CronSubCmdDelete == "" {
b.IRC.CronSubCmdDelete = "delete"
}
if b.IRC.CronSubCmdList == "" {
b.IRC.CronSubCmdList = "list"
}
if b.IRC.CronSubCmdUpdate == "" {
b.IRC.CronSubCmdUpdate = "update"
}
// Messages
if b.IRC.CronErr == "" {
b.IRC.CronErr = "check your syntax"
}
if b.IRC.CronMsgAdd == "" {
b.IRC.CronMsgAdd = "cron job added"
}
if b.IRC.CronMsgDelete == "" {
b.IRC.CronMsgDelete = "cron job deleted"
}
if b.IRC.CronMsgList == "" {
b.IRC.CronMsgList = "id: <id> expression: <expression> message: <message> limited: <is_limited> count: <exec_count>/<exec_limit>"
}
if b.IRC.CronMsgUpdate == "" {
b.IRC.CronMsgUpdate = "cron job updated"
}
// Grammar
if b.IRC.CronGrammarMsgExecCount == "" {
b.IRC.CronGrammarMsgExecCount = "<exec_count>"
}
if b.IRC.CronGrammarMsgExecLimit == "" {
b.IRC.CronGrammarMsgExecLimit = "<exec_limit>"
}
if b.IRC.CronGrammarMsgIsLimited == "" {
b.IRC.CronGrammarMsgIsLimited = "<is_limited>"
}
if b.IRC.CronGrammarMsgRandomWho == "" {
b.IRC.CronGrammarMsgRandomWho = "<random_who>"
}
if b.IRC.CronGrammarWeek == "" {
b.IRC.CronGrammarGiphy = "<week>"
}
if b.IRC.CronGrammarGiphy == "" {
b.IRC.CronGrammarGiphy = "<giphy>"
}
if b.IRC.CronGrammarGiphySearch == "" {
b.IRC.CronGrammarGiphySearch = `<giphy search="([a-zåäöA-ZÅÄÖ0-9 ]+)"[^>]*>"`
}
cronGrammarGiphySearchRegexp = regexp.MustCompile(b.IRC.CronGrammarGiphySearch)
if b.IRC.CronGrammarTenorSearch == "" {
b.IRC.CronGrammarTenorSearch = `<tenor search="([a-zåäöüA-ZÅÄÖÜ0-9 ]+)"[^>]*>"`
}
cronGrammarTenorSearchRegexp = regexp.MustCompile(b.IRC.CronGrammarTenorSearch)
}
// initCron initializes the cron jobs.
func (b *bot) initCron() {
// Fetch all active cron jobs from the database.
rows, err := b.query("SELECT id, expression, message, is_limited, exec_count, exec_limit FROM cron WHERE is_deleted = false")
if err != nil {
b.logger.Printf("initCron: %v", err)
b.privmsg(b.DB.Err)
return
}
defer rows.Close()
// Iterate over the results and add new cron jobs for each job.
for rows.Next() {
var id, expression, message string
var isLimited bool
var execCount, execLimit int
rows.Scan(&id, &expression, &message, &isLimited, &execCount, &execLimit)
// Add a new cron job for the given expression, the message
// that is defined will be sent back to the channel when the
// cron job is triggered. We don't add limited jobs where the
// execution count has reached its limit.
if isLimited == false || (isLimited == true && execCount < execLimit) {
err = b.cron.add(id, expression, message, execCount, execLimit, isLimited, b)
if err != nil {
b.logger.Printf("initCron: %v", err)
}
}
}
// Start the cron job runner.
b.cron.cron.Start()
}
// cronHandler handles the IRC integration of the cron job scheduler.
func (b *bot) cronHandler(m *irc.Message) {
// Parse the action
a := b.parseAction(m).(*privmsgAction)
if !a.validChannel {
return
}
// Not a valid cron cmd, return early.
if a.cmd != b.IRC.CronCmd || len(a.args) < 1 {
return
}
if b.shouldIgnore(m) {
return
}
subCmd := a.args[0]
if subCmd == b.IRC.CronSubCmdAdd && len(a.args) >= 7 {
// The cron expression should be within position 1 to 6 in the
// args slice, the rest of the args is the message to send
// when the cron expression is evaluated and hit.
b.cronAdd(strings.Join(a.args[1:6], " "), strings.Join(a.args[6:], " "))
} else if subCmd == b.IRC.CronSubCmdDelete && len(a.args) == 2 {
b.cronDelete(a.args[1])
} else if subCmd == b.IRC.CronSubCmdList && len(a.args) == 1 {
b.cronList()
} else if subCmd == b.IRC.CronSubCmdUpdate && len(a.args) >= 8 {
// The first argument should be the id of the cron job to
// update. The cron expression should be within position 2 to
// 7 in the args slice, the rest of the args is the message to
// send when the cron expression is evaluated and hit.
b.cronUpdate(a.args[1], strings.Join(a.args[2:7], " "), strings.Join(a.args[7:], " "))
}
}
// cronAdd adds the given expression and message to the database.
func (b *bot) cronAdd(expression, message string) {
// Make sure that the expression is valid.
schedule, err := b.cron.parser.Parse(expression)
if err != nil {
b.logger.Printf("cronAdd: %v", err)
b.privmsg(b.IRC.CronErr)
return
}
// Determine whether the message also holds an execution limit or not,
// if it does we'll extract the limit and use it when we insert the
// new job.
var execLimit int
var isLimited bool
if matches := cronAddLimitRegexp.FindStringSubmatch(message); len(matches) > 1 {
// Since the value is controlled by the regexp we can safely
// assume that the value is going to be converted correctly.
el, _ := strconv.Atoi(matches[1])
if el <= 0 {
execLimit = 1
} else {
execLimit = el
}
isLimited = true
message = strings.Replace(message, matches[0], "", 1)
}
// Prepare the INSERT statement.
stmt, err := b.prepare("INSERT INTO cron (id, expression, message, is_limited, exec_limit, is_deleted, inserted_at) VALUES($1, $2, $3, $4, $5, false, $6)")
if err != nil {
b.logger.Printf("cronAdd: %v", err)
b.privmsg(b.DB.Err)
return
}
defer stmt.Close()
// Execute it.
id := newUUID()
_, err = stmt.Exec(id, expression, message, isLimited, execLimit, newTimestamp())
if err != nil {
b.logger.Printf("cronAdd: %v", err)
b.privmsg(b.DB.Err)
return
}
// Add the job
err = b.cron.add(id, expression, message, 0, execLimit, isLimited, b)
if err != nil {
b.logger.Printf("cronAdd: %v", err)
b.privmsg(b.IRC.CronErr)
}
// ... and send a notice that the cron job has been stored.
b.privmsgph(b.IRC.CronMsgAdd, map[string]string{
"<next_execution>": schedule.Next(time.Now()).Format("2006-01-02 15:04"),
})
}
// cronDelete deletes the cron job.
func (b *bot) cronDelete(id string) {
// We expect a valid UUID to be sent.
if !isUUID(id) {
return
}
stmt, err := b.prepare("UPDATE cron SET is_deleted = true WHERE id = $1")
if err != nil {
b.logger.Printf("cronDelete: %v", err)
b.privmsg(b.DB.Err)
return
}
defer stmt.Close()
// Execute the UPDATE statement.
_, err = stmt.Exec(id)
if err != nil {
b.logger.Printf("cronDelete: %v", err)
b.privmsg(b.DB.Err)
return
}
// Delete the job from the runner.
b.cron.delete(id)
// Send a notice that the cron job was removed.
b.privmsg(b.IRC.CronMsgDelete)
}
// cronList lists all the cron jobs.
func (b *bot) cronList() {
rows, err := b.query("SELECT id, expression, message, is_limited, exec_count, exec_limit FROM cron WHERE is_deleted = false")
if err != nil {
b.logger.Printf("cronList: %v", err)
b.privmsg(b.DB.Err)
return
}
defer rows.Close()
type cronjob struct {
id string
expression string
message string
isLimited bool
execCount int
execLimit int
}
var cronjobs []cronjob
for rows.Next() {
var id, expression, message string
var isLimited bool
var execCount, execLimit int
rows.Scan(&id, &expression, &message, &isLimited, &execCount, &execLimit)
if isLimited == false || (isLimited == true && execCount < execLimit) {
cronjobs = append(cronjobs, cronjob{
id,
expression,
message,
isLimited,
execCount,
execLimit,
})
}
}
// Determine the target of the information.
var target string
if len(cronjobs) > 5 {
target = "pastebin"
} else {
target = b.IRC.Channel
}
// Send the information back to the given target.
var pastebinCode string
for _, c := range cronjobs {
var nextExecution string
schedule, err := b.cron.parser.Parse(c.expression)
if err == nil {
nextExecution = schedule.Next(time.Now()).Format("2006-01-02 15:04")
}
data := map[string]string{
"<id>": c.id,
"<expression>": c.expression,
"<message>": c.message,
"<is_limited>": strconv.FormatBool(c.isLimited),
"<exec_count>": strconv.FormatInt(int64(c.execCount), 10),
"<exec_limit>": strconv.FormatInt(int64(c.execLimit), 10),
"<next_execution>": nextExecution,
}
if target == "pastebin" {
code := b.IRC.CronMsgList
for k, v := range data {
code = strings.ReplaceAll(code, k, v)
}
if pastebinCode == "" {
pastebinCode = fmt.Sprintf("%s", code)
} else {
pastebinCode = fmt.Sprintf("%s\n%s", pastebinCode, code)
}
} else {
b.privmsgph(b.IRC.CronMsgList, data)
}
}
if target == "pastebin" {
b.newPaste("cron job", pastebinCode)
}
}
// cronUpdate updates the cron job.
func (b *bot) cronUpdate(id, expression, message string) {
// We expect a valid UUID to be sent.
if !isUUID(id) {
return
}
// Make sure that the expression is valid.
_, err := b.cron.parser.Parse(expression)
if err != nil {
b.logger.Printf("cronUpdate: %v", err)
b.privmsg(b.IRC.CronErr)
}
// Prepare the update query.
stmt, err := b.prepare("UPDATE cron SET expression = $1, message = $2, updated_at = $3 WHERE id = $4 AND is_deleted = false")
if err != nil {
b.logger.Printf("cronUpdate: %v", err)
b.privmsg(b.DB.Err)
return
}
defer stmt.Close()
// Execute the UPDATE statement.
_, err = stmt.Exec(expression, message, newTimestamp(), id)
if err != nil {
b.logger.Printf("cronUpdate: %v", err)
b.privmsg(b.DB.Err)
return
}
// Delete the old job and re-add it as a new.
b.cron.delete(id)
err = b.cron.add(id, expression, message, 0, 0, false, b)
if err != nil {
b.logger.Printf("cronUpdate: %v", err)
b.privmsg(b.IRC.CronErr)
}
// Send a notice that the cron job was updated.
b.privmsg(b.IRC.CronMsgUpdate)
}