-
Notifications
You must be signed in to change notification settings - Fork 4
/
bot.go
638 lines (550 loc) · 18.7 KB
/
bot.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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
bot "github.com/meinside/telegram-bot-go"
"github.com/meinside/telegram-remotecontrol-bot/cfg"
"github.com/meinside/telegram-remotecontrol-bot/consts"
"github.com/meinside/version-go"
)
const (
githubPageURL = "https://github.com/meinside/telegram-remotecontrol-bot"
)
type status int16
// application statuses
const (
StatusWaiting status = iota
StatusWaitingTransmissionUpload status = iota
)
type session struct {
UserID string
CurrentStatus status
}
type sessionPool struct {
Sessions map[string]session
sync.Mutex
}
var pool sessionPool
// keyboards
var allKeyboards = [][]bot.KeyboardButton{
bot.NewKeyboardButtons(consts.CommandTransmissionList, consts.CommandTransmissionAdd, consts.CommandTransmissionRemove, consts.CommandTransmissionDelete),
bot.NewKeyboardButtons(consts.CommandServiceStatus, consts.CommandServiceStart, consts.CommandServiceStop),
bot.NewKeyboardButtons(consts.CommandStatus, consts.CommandLogs, consts.CommandPrivacy, consts.CommandHelp),
}
var cancelKeyboard = [][]bot.KeyboardButton{
bot.NewKeyboardButtons(consts.CommandCancel),
}
var _stdout = log.New(os.Stdout, "", log.LstdFlags)
var _stderr = log.New(os.Stderr, "", log.LstdFlags)
// check if given Telegram id is available
func isAvailableID(config cfg.Config, id string) bool {
for _, v := range config.AvailableIDs {
if v == id {
return true
}
}
return false
}
// check if given service is controllable
func isControllableService(controllableServices []string, service string) bool {
for _, v := range controllableServices {
if v == service {
return true
}
}
return false
}
// for showing help message
func getHelp() string {
return fmt.Sprintf(`
following commands are supported:
*for transmission*
%s : show torrent list
%s : add torrent with url or magnet
%s : remove torrent from list
%s : remove torrent and delete data
*for systemctl*
%s : show status of each service (systemctl is-active)
%s : start a service (systemctl start)
%s : stop a service (systemctl stop)
*others*
%s : show this bot's status
%s : show latest logs of this bot
%s : show privacy policy of this bot
%s : show this help message
`,
consts.CommandTransmissionList,
consts.CommandTransmissionAdd,
consts.CommandTransmissionRemove,
consts.CommandTransmissionDelete,
consts.CommandServiceStatus,
consts.CommandServiceStart,
consts.CommandServiceStop,
consts.CommandStatus,
consts.CommandLogs,
consts.CommandPrivacy,
consts.CommandHelp,
)
}
// for showing privacy policy
func getPrivacyPolicy() string {
return fmt.Sprintf(`
privacy policy:
%s/raw/master/PRIVACY.md
`, githubPageURL)
}
// get recent logs
func getLogs(db *Database) string {
var lines []string
logs := db.GetLogs(consts.NumRecentLogs)
if len(logs) <= 0 {
return consts.MessageNoLogs
}
for _, log := range logs {
lines = append(lines, fmt.Sprintf("%s %s: %s", log.CreatedAt.Format("2006-01-02 15:04:05"), log.Type, log.Message))
}
return strings.Join(lines, "\n")
}
// for showing current status of this bot
func getStatus(config cfg.Config, launchedAt time.Time) string {
return fmt.Sprintf("app version: %s\napp uptime: %s\napp memory usage: %s\nsystem disk usage:\n%s",
version.Minimum(),
uptimeSince(launchedAt),
memoryUsage(),
diskUsage(config.MountPoints),
)
}
// parse service command and start/stop given service
func parseServiceCommand(config cfg.Config, db *Database, txt string) (message string, keyboards [][]bot.InlineKeyboardButton) {
message = consts.MessageNoControllableServices
for _, cmd := range []string{consts.CommandServiceStart, consts.CommandServiceStop} {
if strings.HasPrefix(txt, cmd) {
service := strings.TrimSpace(strings.Replace(txt, cmd, "", 1))
if isControllableService(config.ControllableServices, service) {
if strings.HasPrefix(txt, consts.CommandServiceStart) { // start service
if output, err := systemctlStart(service); err == nil {
message = fmt.Sprintf("started service: %s", service)
} else {
message = fmt.Sprintf("failed to start service: %s (%s)", service, err)
logError(db, "service failed to start: %s", output)
}
} else if strings.HasPrefix(txt, consts.CommandServiceStop) { // stop service
if output, err := systemctlStop(service); err == nil {
message = fmt.Sprintf("stopped service: %s", service)
} else {
message = fmt.Sprintf("failed to stop service: %s (%s)", service, err)
logError(db, "service failed to stop: %s", output)
}
}
} else {
if strings.HasPrefix(txt, consts.CommandServiceStart) { // start service
message = consts.MessageServiceToStart
} else if strings.HasPrefix(txt, consts.CommandServiceStop) { // stop service
message = consts.MessageServiceToStop
}
keys := map[string]string{}
for _, v := range config.ControllableServices {
keys[v] = fmt.Sprintf("%s %s", cmd, v)
}
keyboards = bot.NewInlineKeyboardButtonsAsRowsWithCallbackData(keys)
// add cancel button
keyboards = append(keyboards, []bot.InlineKeyboardButton{
bot.NewInlineKeyboardButton(consts.MessageCancel).
SetCallbackData(consts.CommandCancel),
})
}
}
continue
}
return message, keyboards
}
// parse transmission command
func parseTransmissionCommand(config cfg.Config, txt string) (message string, keyboards [][]bot.InlineKeyboardButton) {
if torrents, _ := GetTorrents(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd); len(torrents) > 0 {
for _, cmd := range []string{consts.CommandTransmissionRemove, consts.CommandTransmissionDelete} {
if strings.HasPrefix(txt, cmd) {
param := strings.TrimSpace(strings.Replace(txt, cmd, "", 1))
if _, err := strconv.Atoi(param); err == nil { // if torrent id number is given,
if strings.HasPrefix(txt, consts.CommandTransmissionRemove) { // remove torrent
message = RemoveTorrent(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd, param)
} else if strings.HasPrefix(txt, consts.CommandTransmissionDelete) { // delete service
message = DeleteTorrent(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd, param)
}
} else {
if strings.HasPrefix(txt, consts.CommandTransmissionRemove) { // remove torrent
message = consts.MessageTransmissionRemove
} else if strings.HasPrefix(txt, consts.CommandTransmissionDelete) { // delete torrent
message = consts.MessageTransmissionDelete
}
// inline keyboards
keys := map[string]string{}
for _, t := range torrents {
keys[fmt.Sprintf("%d. %s", t.ID, t.Name)] = fmt.Sprintf("%s %d", cmd, t.ID)
}
keyboards = bot.NewInlineKeyboardButtonsAsRowsWithCallbackData(keys)
// add cancel button
keyboards = append(keyboards, []bot.InlineKeyboardButton{
bot.NewInlineKeyboardButton(consts.MessageCancel).
SetCallbackData(consts.CommandCancel),
})
}
}
continue
}
} else {
message = consts.MessageTransmissionNoTorrents
}
return message, keyboards
}
// process incoming update from Telegram
func processUpdate(b *bot.Bot, config cfg.Config, db *Database, launchedAt time.Time, update bot.Update) bool {
// check username
var userID string
if from := update.GetFrom(); from == nil {
logError(db, "update has no 'from' value")
return false
} else {
if from.Username == nil {
logError(db, "has no user name: %s", from.FirstName)
return false
}
userID = *from.Username
if !isAvailableID(config, userID) {
logError(db, "not an allowed id: %s", userID)
return false
}
}
// save chat id
db.SaveChat(update.Message.Chat.ID, userID)
// process result
result := false
pool.Lock()
if s, exists := pool.Sessions[userID]; exists {
// text from message
var txt string
if update.Message.HasText() {
txt = *update.Message.Text
} else {
txt = ""
}
var message string
options := bot.OptionsSendMessage{}.
SetReplyMarkup(defaultReplyMarkup(true))
switch s.CurrentStatus {
case StatusWaiting:
if update.Message.Document != nil { // if a file is received,
fileResult := b.GetFile(update.Message.Document.FileID)
fileURL := b.GetFileURL(*fileResult.Result)
// XXX - only support: .torrent
if strings.HasSuffix(fileURL, ".torrent") {
addReaction(b, update, "👌")
message = AddTorrent(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd, fileURL)
} else {
message = consts.MessageUnprocessableFileFormat
}
} else {
switch {
// magnet url
case strings.HasPrefix(txt, "magnet:"):
addReaction(b, update, "👌")
message = AddTorrent(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd, txt)
// /start
case strings.HasPrefix(txt, consts.CommandStart):
message = consts.MessageDefault
// systemctl
case strings.HasPrefix(txt, consts.CommandServiceStatus):
statuses, _ := systemctlStatus(config.ControllableServices)
for service, status := range statuses {
message += fmt.Sprintf("%s: *%s*\n", service, status)
}
case strings.HasPrefix(txt, consts.CommandServiceStart) || strings.HasPrefix(txt, consts.CommandServiceStop):
if len(config.ControllableServices) > 0 {
var keyboards [][]bot.InlineKeyboardButton
message, keyboards = parseServiceCommand(config, db, txt)
if keyboards != nil {
options.SetReplyMarkup(bot.NewInlineKeyboardMarkup(keyboards))
}
} else {
message = consts.MessageNoControllableServices
}
// transmission
case strings.HasPrefix(txt, consts.CommandTransmissionList):
message = GetList(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd)
case strings.HasPrefix(txt, consts.CommandTransmissionAdd):
arg := strings.TrimSpace(strings.Replace(txt, consts.CommandTransmissionAdd, "", 1))
if strings.HasPrefix(arg, "magnet:") {
message = AddTorrent(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd, arg)
} else {
message = consts.MessageTransmissionUpload
pool.Sessions[userID] = session{
UserID: userID,
CurrentStatus: StatusWaitingTransmissionUpload,
}
options.SetReplyMarkup(cancelReplyMarkup(true))
}
case strings.HasPrefix(txt, consts.CommandTransmissionRemove) || strings.HasPrefix(txt, consts.CommandTransmissionDelete):
var keyboards [][]bot.InlineKeyboardButton
message, keyboards = parseTransmissionCommand(config, txt)
if keyboards != nil {
options.SetReplyMarkup(bot.NewInlineKeyboardMarkup(keyboards))
}
case strings.HasPrefix(txt, consts.CommandStatus):
message = getStatus(config, launchedAt)
case strings.HasPrefix(txt, consts.CommandLogs):
message = getLogs(db)
case strings.HasPrefix(txt, consts.CommandHelp):
message = getHelp()
options.SetReplyMarkup(helpInlineKeyboardMarkup())
case strings.HasPrefix(txt, consts.CommandPrivacy):
message = getPrivacyPolicy()
// fallback
default:
cmd := removeMarkdownChars(txt, "")
if len(cmd) > 0 {
message = fmt.Sprintf("*%s*: %s", cmd, consts.MessageUnknownCommand)
} else {
message = consts.MessageUnknownCommand
}
}
}
case StatusWaitingTransmissionUpload:
switch {
case strings.HasPrefix(txt, consts.CommandCancel):
message = consts.MessageCanceled
default:
var torrent string
if update.Message.Document != nil {
fileResult := b.GetFile(update.Message.Document.FileID)
torrent = b.GetFileURL(*fileResult.Result)
} else {
torrent = txt
}
addReaction(b, update, "👌")
message = AddTorrent(config.TransmissionRPCPort, config.TransmissionRPCUsername, config.TransmissionRPCPasswd, torrent)
}
// reset status
pool.Sessions[userID] = session{
UserID: userID,
CurrentStatus: StatusWaiting,
}
}
// send message
if checkMarkdownValidity(message) {
options.SetParseMode(bot.ParseModeMarkdown)
}
if sent := b.SendMessage(update.Message.Chat.ID, message, options); sent.Ok {
result = true
} else {
logError(db, "failed to send message: %s", *sent.Description)
}
} else {
logError(db, "no session for id: %s", userID)
}
pool.Unlock()
return result
}
// add reaction to a message
func addReaction(b *bot.Bot, update bot.Update, reaction string) {
if !update.HasMessage() {
return
}
chatID := update.Message.Chat.ID
messageID := update.Message.MessageID
_ = b.SetMessageReaction(chatID, messageID, bot.NewMessageReactionWithEmoji(reaction))
}
// process incoming callback query
func processCallbackQuery(b *bot.Bot, config cfg.Config, db *Database, update bot.Update) (result bool) {
query := *update.CallbackQuery
txt := *query.Data
// process result
result = false
var message string
if strings.HasPrefix(txt, consts.CommandCancel) {
message = ""
} else if strings.HasPrefix(txt, consts.CommandServiceStart) || strings.HasPrefix(txt, consts.CommandServiceStop) { // service
message, _ = parseServiceCommand(config, db, txt)
} else if strings.HasPrefix(txt, consts.CommandTransmissionRemove) || strings.HasPrefix(txt, consts.CommandTransmissionDelete) { // transmission
message, _ = parseTransmissionCommand(config, txt)
} else {
logError(db, "unprocessable callback query: %s", txt)
return result
}
// answer callback query
options := bot.OptionsAnswerCallbackQuery{}
if len(message) > 0 {
options.SetText(message)
}
if apiResult := b.AnswerCallbackQuery(query.ID, options); apiResult.Ok {
if len(message) <= 0 {
message = consts.MessageCanceled
}
// edit message and remove inline keyboards
if apiResult := b.EditMessageText(
message,
bot.OptionsEditMessageText{}.
SetIDs(query.Message.Chat.ID, query.Message.MessageID),
); apiResult.Ok {
result = true
} else {
logError(db, "failed to edit message text: %s", *apiResult.Description)
}
} else {
logError(db, "failed to answer callback query: %+v", query)
}
return result
}
// broadcast a messge to given chats
func broadcast(client *bot.Bot, config cfg.Config, db *Database, message string) {
for _, chat := range db.GetChats() {
if isAvailableID(config, chat.UserID) {
options := bot.OptionsSendMessage{}.
SetReplyMarkup(defaultReplyMarkup(true))
if checkMarkdownValidity(message) {
options.SetParseMode(bot.ParseModeMarkdown)
}
if sent := client.SendMessage(
chat.ChatID,
message,
options,
); !sent.Ok {
logError(db, "failed to broadcast to chat id %d: %s", chat.ChatID, *sent.Description)
}
} else {
logError(db, "not an allowed id for boradcasting: %s", chat.UserID)
}
}
}
// for processing incoming request through HTTP
func httpHandlerForCLI(config cfg.Config, queue chan string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
message := strings.TrimSpace(r.FormValue(consts.ParamMessage))
if len(message) > 0 {
if config.IsVerbose {
_stdout.Printf("received message from CLI: %s", message)
}
queue <- message
}
}
}
// check if given string is valid with markdown characters (true == valid)
func checkMarkdownValidity(txt string) bool {
if strings.Count(txt, "_")%2 == 0 &&
strings.Count(txt, "*")%2 == 0 &&
strings.Count(txt, "`")%2 == 0 &&
strings.Count(txt, "```")%2 == 0 {
return true
}
return false
}
// default reply markup for messages
func defaultReplyMarkup(resize bool) bot.ReplyKeyboardMarkup {
return bot.NewReplyKeyboardMarkup(allKeyboards).
SetResizeKeyboard(resize)
}
// reply markup for cancel
func cancelReplyMarkup(resize bool) bot.ReplyKeyboardMarkup {
return bot.NewReplyKeyboardMarkup(cancelKeyboard).
SetResizeKeyboard(resize)
}
// inline keyboard markup for help
func helpInlineKeyboardMarkup() bot.InlineKeyboardMarkup {
return bot.NewInlineKeyboardMarkup( // inline keyboard for link to github page
[][]bot.InlineKeyboardButton{
bot.NewInlineKeyboardButtonsWithURL(map[string]string{
"GitHub": githubPageURL,
}),
},
)
}
// run bot
func runBot(config cfg.Config, launchedAt time.Time) {
// initialize variables
sessions := make(map[string]session)
for _, v := range config.AvailableIDs {
sessions[v] = session{
UserID: v,
CurrentStatus: StatusWaiting,
}
}
pool = sessionPool{
Sessions: sessions,
}
queue := make(chan string, consts.QueueSize)
// open database
db, err := OpenDB()
if err != nil {
_stderr.Fatalf("failed to open database: %s", err)
}
db.Log("starting server...")
// catch SIGINT and SIGTERM and terminate gracefully
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
go func() {
<-sig
db.Log("stopping server...")
os.Exit(1)
}()
client := bot.NewClient(config.APIToken)
client.Verbose = config.IsVerbose
// get info about this bot
if me := client.GetMe(); me.Ok {
_stdout.Printf("launching bot: @%s (%s)", *me.Result.Username, me.Result.FirstName)
// delete webhook (getting updates will not work when wehbook is set up)
if unhooked := client.DeleteWebhook(false); unhooked.Ok {
// wait for CLI message channel
go func() {
// broadcast messages from CLI
for message := range queue {
broadcast(client, config, db, message)
}
}()
// start web server for CLI
go func(config cfg.Config) {
if config.CLIPort <= 0 {
config.CLIPort = consts.DefaultCLIPortNumber
}
_stdout.Printf("starting local web server for CLI on port: %d", config.CLIPort)
http.HandleFunc(consts.HTTPBroadcastPath, httpHandlerForCLI(config, queue))
if err := http.ListenAndServe(fmt.Sprintf(":%d", config.CLIPort), nil); err != nil {
panic(err)
}
}(config)
// set update handlers
client.SetMessageHandler(func(b *bot.Bot, update bot.Update, message bot.Message, edited bool) {
// 'is typing...'
b.SendChatAction(message.Chat.ID, bot.ChatActionTyping, nil)
// process message
processUpdate(b, config, db, launchedAt, update)
})
client.SetCallbackQueryHandler(func(b *bot.Bot, update bot.Update, callbackQuery bot.CallbackQuery) {
// 'is typing...'
b.SendChatAction(callbackQuery.Message.Chat.ID, bot.ChatActionTyping, nil)
// process callback query
processCallbackQuery(b, config, db, update)
})
// wait for new updates
client.StartPollingUpdates(0, config.MonitorInterval, func(b *bot.Bot, update bot.Update, err error) {
if err != nil {
logError(db, "error while receiving update: %s", err)
}
})
} else {
panic("Failed to delete webhook")
}
} else {
panic("Failed to get info of the bot")
}
}
// log error to stderr and DB
func logError(db *Database, format string, a ...any) {
_stderr.Printf(format, a...)
db.LogError(fmt.Sprintf(format, a...))
}