-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
actor.go
355 lines (308 loc) · 7.8 KB
/
actor.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
// This file is part of the Smart Home
// Program complex distribution https://github.com/e154/smart-home
// Copyright (C) 2016-2021, Filippov Alex
//
// This library is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library. If not, see
// <https://www.gnu.org/licenses/>.
package telegram
import (
"fmt"
"strings"
"github.com/e154/smart-home/common/events"
"github.com/e154/smart-home/common/apperr"
"github.com/pkg/errors"
tgbotapi "github.com/Syfaro/telegram-bot-api"
"github.com/e154/smart-home/adaptors"
"github.com/e154/smart-home/common"
m "github.com/e154/smart-home/models"
"github.com/e154/smart-home/system/bus"
"github.com/e154/smart-home/system/entity_manager"
"github.com/e154/smart-home/system/scripts"
"github.com/e154/smart-home/version"
"go.uber.org/atomic"
)
// Actor ...
type Actor struct {
entity_manager.BaseActor
isStarted *atomic.Bool
eventBus bus.Bus
adaptors *adaptors.Adaptors
AccessToken string
bot *tgbotapi.BotAPI
commandPool chan Command
msgPool chan string
actionPool chan events.EventCallAction
}
// NewActor ...
func NewActor(entity *m.Entity,
entityManager entity_manager.EntityManager,
scriptService scripts.ScriptService,
eventBus bus.Bus,
adaptors *adaptors.Adaptors) (*Actor, error) {
settings := NewSettings()
_, _ = settings.Deserialize(entity.Settings.Serialize())
actor := &Actor{
BaseActor: entity_manager.NewBaseActor(entity, scriptService, adaptors),
eventBus: eventBus,
actionPool: make(chan events.EventCallAction, 10),
isStarted: atomic.NewBool(false),
adaptors: adaptors,
AccessToken: settings[AttrToken].String(),
commandPool: make(chan Command, 99),
msgPool: make(chan string, 99),
}
actor.Manager = entityManager
if actor.Attrs == nil {
actor.Attrs = NewAttr()
}
if actor.Setts == nil {
actor.Setts = NewSettings()
}
//if actor.Actions == nil {
// actor.Actions = NewActions()
//}
// Actions
for _, a := range actor.Actions {
if a.ScriptEngine != nil {
// bind
_, _ = a.ScriptEngine.Do()
}
}
actor.DeserializeAttr(entity.Attributes.Serialize())
// action worker
go func() {
for msg := range actor.actionPool {
actor.runAction(msg)
}
}()
return actor, nil
}
// Spawn ...
func (p *Actor) Spawn() entity_manager.PluginActor {
return p
}
// Start ...
func (p *Actor) Start() (err error) {
if p.isStarted.Load() {
return
}
defer func() {
if err == nil {
p.isStarted.Store(true)
}
}()
if !common.TestMode() {
p.bot, err = tgbotapi.NewBotAPI(p.AccessToken)
if err != nil {
err = errors.Wrap(apperr.ErrInternal, err.Error())
return
}
log.Infof("Authorized on account %s", p.bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
var updates tgbotapi.UpdatesChannel
if updates, err = p.bot.GetUpdatesChan(u); err != nil {
log.Error(err.Error())
return
}
go func() {
for update := range updates {
p.commandPool <- Command{
ChatId: update.Message.Chat.ID,
Text: update.Message.Text,
UserName: update.Message.From.UserName,
}
}
}()
}
go func() {
for v := range p.commandPool {
p.commandHandler(v)
}
}()
go func() {
var list []m.TelegramChat
var err error
for msg := range p.msgPool {
if list, err = p.getChatList(); err != nil {
continue
}
for _, chat := range list {
if _, err = p.sendMsg(msg, chat.ChatId); err != nil {
log.Warn(err.Error())
}
}
}
}()
return
}
// Stop ...
func (p *Actor) Stop() {
if !p.isStarted.Load() {
return
}
if p.bot != nil {
p.bot.StopReceivingUpdates()
}
close(p.commandPool)
close(p.msgPool)
p.isStarted.Store(false)
}
// Send ...
func (p *Actor) Send(message string) (err error) {
if !p.isStarted.Load() {
return
}
p.msgPool <- message
return
}
func (p *Actor) commandHandler(cmd Command) {
switch cmd.Text {
case "/start":
p.commandStart(cmd)
case "/help":
p.commandHelp(cmd)
case "/quit":
p.commandQuit(cmd)
default:
p.commandAction(cmd)
}
}
func (p *Actor) sendMsg(body string, chatId int64) (messageID int, err error) {
defer func() {
if err == nil {
go func() { _ = p.UpdateStatus() }()
log.Debugf("Sent message '%s' to chatId '%d'", body, chatId)
}
}()
if common.TestMode() {
messageID = 123
return
}
msgCfg := tgbotapi.NewMessage(chatId, body)
p.genKeyboard(msgCfg)
var msg tgbotapi.Message
if msg, err = p.bot.Send(msgCfg); err != nil {
return
}
messageID = msg.MessageID
return
}
func (p *Actor) getChatList() (list []m.TelegramChat, err error) {
list, _, err = p.adaptors.TelegramChat.List(999, 0, "", "", p.Id)
return
}
// UpdateStatus ...
func (p *Actor) UpdateStatus() (err error) {
oldState := p.GetEventState(p)
now := p.Now(oldState)
var attributeValues = make(m.AttributeValue)
// ...
p.AttrMu.Lock()
var changed bool
if changed, err = p.Attrs.Deserialize(attributeValues); !changed {
if err != nil {
log.Warn(err.Error())
}
if oldState.LastUpdated != nil {
delta := now.Sub(*oldState.LastUpdated).Milliseconds()
//fmt.Println("delta", delta)
if delta < 200 {
p.AttrMu.Unlock()
return
}
}
}
p.AttrMu.Unlock()
p.eventBus.Publish(bus.TopicEntities, events.EventStateChanged{
StorageSave: true,
PluginName: p.Id.PluginName(),
EntityId: p.Id,
OldState: oldState,
NewState: p.GetEventState(p),
})
return
}
func (p *Actor) commandStart(cmd Command) {
text := fmt.Sprintf(banner, version.GetHumanVersion(), cmd.Text)
_ = p.adaptors.TelegramChat.Add(m.TelegramChat{
EntityId: p.Id,
ChatId: cmd.ChatId,
Username: cmd.UserName,
})
_, _ = p.sendMsg(text, cmd.ChatId)
}
func (p *Actor) commandHelp(cmd Command) {
builder := &strings.Builder{}
if len(p.Actions) > 0 {
for _, action := range p.Actions {
builder.WriteString(fmt.Sprintf("/%s - %s\n", action.Name, action.Description))
}
}
builder.WriteString(help)
_, _ = p.sendMsg(builder.String(), cmd.ChatId)
}
func (p *Actor) commandQuit(cmd Command) {
_ = p.adaptors.TelegramChat.Delete(p.Id, cmd.ChatId)
_, _ = p.sendMsg("/quit -unsubscribe from bot\n/start - subscriber again", cmd.ChatId)
}
// todo add command args
func (p *Actor) commandAction(cmd Command) {
p.runAction(events.EventCallAction{
ActionName: strings.Replace(cmd.Text, "/", "", 1),
EntityId: p.Id,
})
}
func (p *Actor) addAction(event events.EventCallAction) {
p.actionPool <- event
}
func (p *Actor) runAction(msg events.EventCallAction) {
action, ok := p.Actions[msg.ActionName]
if !ok {
log.Warnf("action %s not found", msg.ActionName)
return
}
if action.ScriptEngine == nil {
return
}
if _, err := action.ScriptEngine.AssertFunction(FuncEntityAction, msg.EntityId, action.Name); err != nil {
log.Error(err.Error())
return
}
}
// gen keyboard from actions
// [button][button][button]
// [button][button][button]
// [button][button][button]
func (p *Actor) genKeyboard(msgCfg tgbotapi.MessageConfig) {
var row []tgbotapi.KeyboardButton
var rows [][]tgbotapi.KeyboardButton
var counter = 0
if len(p.Actions) == 0 {
return
}
for k := range p.Actions {
counter++
if counter >= 3 {
counter = 1
rows = append(rows, row)
row = []tgbotapi.KeyboardButton{}
}
row = append(row, tgbotapi.NewKeyboardButton(fmt.Sprintf("/%s", k)))
}
if counter < 3 {
rows = append(rows, row)
}
msgCfg.ReplyMarkup = tgbotapi.NewReplyKeyboard(rows...)
}