/
service.go
474 lines (401 loc) · 12 KB
/
service.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
package telegram
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/weAutomateEverything/go2hal/auth"
"github.com/weAutomateEverything/halMessageClassification/api"
"gopkg.in/telegram-bot-api.v4"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"runtime"
"strconv"
"strings"
)
type Service interface {
SendMessage(ctx context.Context, chatID int64, message string, messageID int) (msgid int, err error)
SendMessageWithCorrelation(ctx context.Context, chatID int64, message string, messageID int, correlationId string) (msgid int, err error)
SendMessagePlainText(ctx context.Context, chatID int64, message string, messageID int) (msgid int, err error)
SendImageToGroup(ctx context.Context, image []byte, group int64) error
SendDocumentToGroup(ctx context.Context, document []byte, extension string, group int64) error
SendKeyboard(ctx context.Context, buttons []string, text string, chat int64) (int, error)
RegisterCommand(command Command)
RegisterCommandLet(commandlet Commandlet)
requestAuthorisation(ctx context.Context, chat uint32, name string) (string, error)
pollAuthorisation(token string) (uint32, error)
}
type Command interface {
CommandIdentifier() string
CommandDescription() string
RestrictToAuthorised() bool
Show(chat uint32) bool
Execute(ctx context.Context, update tgbotapi.Update)
}
type Commandlet interface {
CanExecute(update tgbotapi.Update, state State) bool
Execute(ctx context.Context, update tgbotapi.Update, state State)
NextState(update tgbotapi.Update, state State) string
Fields(update tgbotapi.Update, state State) []string
}
type RemoteCommand interface {
GetCommandGroup() uint32
}
type service struct {
store Store
authService auth.Service
}
type commandCtor func() Command
type commandletCtor func() Commandlet
var commandList = map[string]commandCtor{}
var commandletList = []commandletCtor{}
var telegramBot *tgbotapi.BotAPI
func NewService(store Store, authService auth.Service) Service {
s := &service{store: store, authService: authService}
key := os.Getenv("BOT_KEY")
if key == "" {
panic("BOT_KEY environment variable not set.")
}
err := s.useBot(key)
if err != nil {
panic(err.Error())
}
return s
}
func (s *service) SendMessage(ctx context.Context, chatID int64, message string, messageID int) (msgid int, err error) {
return sendMessage(chatID, message, messageID, true)
}
func (s *service) SendMessagePlainText(ctx context.Context, chatID int64, message string, messageID int) (msgid int, err error) {
return sendMessage(chatID, message, messageID, false)
}
func (s *service) SendImageToGroup(ctx context.Context, image []byte, group int64) error {
path := ""
if runtime.GOOS == "windows" {
path = "c:/temp/"
} else {
path = "/tmp/"
}
path = path + string(rand.Int()) + ".png"
err := ioutil.WriteFile(path, image, os.ModePerm)
if err != nil {
return err
}
msg := tgbotapi.NewPhotoUpload(group, path)
_, err = telegramBot.Send(msg)
if err != nil {
return err
}
return nil
}
func (s *service) SendDocumentToGroup(ctx context.Context, document []byte, extension string, group int64) error {
path := ""
if runtime.GOOS == "windows" {
path = "c:/temp/"
} else {
path = "/tmp/"
}
path = path + string(rand.Int()) + "." + extension
err := ioutil.WriteFile(path, document, os.ModePerm)
if err != nil {
return err
}
msg := tgbotapi.NewDocumentUpload(group, path)
_, err = telegramBot.Send(msg)
if err != nil {
return err
}
return nil
}
func (s *service) RegisterCommand(command Command) {
register(func() Command {
return command
})
}
func (s *service) RegisterCommandLet(commandlet Commandlet) {
registerCommandlet(func() Commandlet {
return commandlet
})
}
func (s *service) SendKeyboard(ctx context.Context, buttons []string, text string, chat int64) (int, error) {
keyB := tgbotapi.NewReplyKeyboard()
keyBRow := tgbotapi.NewKeyboardButtonRow()
for i, l := range buttons {
btn := tgbotapi.KeyboardButton{l, false, false}
keyBRow = append(keyBRow, btn)
if i > 0 && i%3 == 0 {
keyB.Keyboard = append(keyB.Keyboard, keyBRow)
keyBRow = tgbotapi.NewKeyboardButtonRow()
}
}
if len(keyBRow) > 0 {
keyB.Keyboard = append(keyB.Keyboard, keyBRow)
}
keyB.OneTimeKeyboard = true
msg := tgbotapi.NewMessage(chat, text)
msg.ReplyMarkup = keyB
m, err := telegramBot.Send(msg)
if err != nil {
return 0, err
}
return m.MessageID, nil
}
func (s service) requestAuthorisation(ctx context.Context, chat uint32, name string) (authtoken string, err error) {
room, err := s.store.GetRoomKey(chat)
if err != nil {
return
}
id, err := s.SendKeyboard(ctx, []string{"Approve access", "Decline access"}, fmt.Sprintf("A user %v has requested access to edit the configuration for the room.", name), room)
if err != nil {
return "", err
}
token, err := s.store.newAuthRequest(id, room, name)
if err != nil {
return "", err
}
return token, nil
}
func (s service) pollAuthorisation(token string) (room uint32, err error) {
roomId, err := s.store.useToken(token)
if err != nil {
return
}
return s.store.GetUUID(roomId, "")
}
func (s service) useBot(botkey string) error {
var err error
telegramBot, err = tgbotapi.NewBotAPI(botkey)
if err != nil {
return err
}
go func() {
s.pollMessage()
}()
return nil
}
func (s service) pollMessage() {
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
for true {
updates, err := telegramBot.GetUpdates(u)
if err != nil {
log.Panic(err)
}
for _, update := range updates {
if update.UpdateID >= u.Offset {
u.Offset = update.UpdateID + 1
}
if update.Message == nil {
continue
}
if update.Message.NewChatMembers != nil {
for _, user := range *update.Message.NewChatMembers {
// Looks like the bot has been added to a new group - lets register the details.
if user.ID == telegramBot.Self.ID {
id, err := s.store.addBot(update.Message.Chat.ID, update.Message.Chat.Title)
if err != nil {
sendMessage(update.Message.Chat.ID, fmt.Sprintf("There was an error registering your bot: %v", err.Error()), update.Message.MessageID, false)
continue
}
sendMessage(update.Message.Chat.ID, fmt.Sprintf("The bot has been successfully registered. Your token is %v", id), update.Message.MessageID, false)
continue
}
}
}
if update.Message.IsCommand() {
if s.executeCommand(update) {
continue
}
}
if update.Message != nil {
if s.executeCommandLet(update) {
continue
}
if update.Message.ReplyToMessage != nil {
key, err := s.store.getCorrelationId(update.Message.Chat.ID, update.Message.ReplyToMessage.MessageID)
if err != nil {
log.Printf("Error getting correlation id %v", err)
continue
}
err = s.store.SaveReply(update.Message.Chat.ID, update.Message.Text, key)
if err != nil {
log.Printf("Error saving reply %v", err)
continue
}
}
}
log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
sendMessage(update.Message.Chat.ID, update.Message.Text, update.Message.MessageID, false)
}
}
}
func (s service) SendMessageWithCorrelation(ctx context.Context, chatID int64, message string, messageID int, correlationId string) (msgid int, err error) {
msgid, err = s.SendMessage(ctx, chatID, message, messageID)
if err != nil {
return
}
err = s.store.saveMessageCorrelation(chatID, msgid, correlationId)
return
}
func sendMessage(chatID int64, message string, messageID int, markup bool) (msgid int, err error) {
log.Printf("Sending Message %s", message)
msg := tgbotapi.NewMessage(chatID, message)
if markup {
msg.ParseMode = tgbotapi.ModeMarkdown
}
if messageID != 0 {
msg.ReplyToMessageID = messageID
}
out, err := telegramBot.Send(msg)
if err != nil {
log.Println(err)
return
}
err = auditMessage(message, chatID, strconv.FormatInt(int64(out.MessageID), 10))
if err != nil {
log.Printf("Error auditing message: %v", err)
}
return out.MessageID, nil
}
func (s service) executeCommand(update tgbotapi.Update) bool {
group, _ := s.store.GetUUID(update.Message.Chat.ID, update.Message.Chat.Title)
command := findCommand(update.Message.Command(), group)
if command != nil {
if command.RestrictToAuthorised() {
if !(s.authService.Authorize(strconv.Itoa(update.Message.From.ID))) {
s.SendMessage(context.Background(), update.Message.Chat.ID, "You are not authorized to use this transaction.", update.Message.MessageID)
return false
}
}
go func() {
command.Execute(context.Background(), update)
}()
return true
}
return false
}
func (s service) executeCommandLet(update tgbotapi.Update) bool {
state := s.store.getState(update.Message.From.ID, update.Message.Chat.ID)
for _, c := range commandletList {
a := c()
if a.CanExecute(update, state) {
a.Execute(context.Background(), update, state)
s.store.SetState(update.Message.From.ID, update.Message.Chat.ID, a.NextState(update, state), a.Fields(update, state))
return true
}
}
return false
}
func findCommand(command string, group uint32) (a Command) {
//Check if its a standard command
c, ok := commandList[strings.ToLower(command)]
if ok {
return c()
}
//see if its a command for a certain group
c, ok = commandList[strings.ToLower(command)+strconv.FormatUint(uint64(group), 10)]
if ok {
return c()
}
return nil
}
func register(newfunc commandCtor) {
id := newfunc().CommandIdentifier()
remote, ok := newfunc().(RemoteCommand)
if ok {
id = id + strconv.FormatUint(uint64(remote.GetCommandGroup()), 10)
}
commandList[strings.ToLower(id)] = newfunc
}
func registerCommandlet(newFunc commandletCtor) {
commandletList = append(commandletList, newFunc)
}
type help struct {
telegram Service
store Store
}
func NewHelpCommand(telegram Service, store Store) Command {
return &help{telegram, store}
}
func (s *help) RestrictToAuthorised() bool {
return false
}
func (s *help) CommandIdentifier() string {
return "help"
}
func (s *help) CommandDescription() string {
return "Gets list of commands"
}
func (*help) Show(uint32) bool {
return true
}
func (s *help) Execute(ctx context.Context, update tgbotapi.Update) {
var buffer bytes.Buffer
chat, err := s.store.GetUUID(update.Message.Chat.ID, update.Message.Chat.Title)
if err != nil {
s.telegram.SendMessage(ctx, update.Message.Chat.ID, fmt.Sprintf("There was an error trying to retrieve your commends. %v", err.Error()), update.Message.MessageID)
return
}
for _, x := range getCommands(chat) {
if x.Group != 0 {
if x.Group != chat {
continue
}
}
buffer.WriteString("/")
buffer.WriteString(x.Name)
buffer.WriteString(" - ")
buffer.WriteString(x.Description)
buffer.WriteString("\n")
}
s.telegram.SendMessage(ctx, update.Message.Chat.ID, buffer.String(), update.Message.MessageID)
}
func getCommands(chat uint32) []commandDescription {
result := make([]commandDescription, 0)
for _, x := range commandList {
r, ok := x().(RemoteCommand)
if ok {
result = append(result, commandDescription{x().CommandIdentifier(), x().CommandDescription(), r.GetCommandGroup()})
} else {
if x().Show(chat) {
result = append(result, commandDescription{x().CommandIdentifier(), x().CommandDescription(), 0})
}
}
}
return result
}
func auditMessage(message string, chat int64, messageId string) error {
if strings.Contains(message, "Negative Sentiment Message Detected for group") {
log.Println("Ignoring message")
return nil
}
log.Printf("Checking Audit endpoint: %v", os.Getenv("HAL_API_SERVICES"))
if os.Getenv("HAL_API_SERVICES") != "" {
req := api.TextEvent{
Message: message,
MessageID: messageId,
Chat: chat,
}
b, err := json.Marshal(req)
if err != nil {
return err
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
resp, err := http.Post(fmt.Sprintf("%v/halMessageClassification", os.Getenv("HAL_API_SERVICES")), "application/json", bytes.NewReader(b))
if err != nil {
return err
}
resp.Body.Close()
}
return nil
}
/**
Basic information about a command
*/
type commandDescription struct {
Name, Description string
Group uint32
}