-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
427 lines (409 loc) · 13.5 KB
/
main.go
File metadata and controls
427 lines (409 loc) · 13.5 KB
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
package main
import (
"context"
"crypto/tls"
"fmt"
apiGrpc "github.com/awakari/bot-telegram/api/grpc"
"github.com/awakari/bot-telegram/api/grpc/queue"
apiGrpcTgBot "github.com/awakari/bot-telegram/api/grpc/tgbot"
apiGrpcUsageLimits "github.com/awakari/bot-telegram/api/grpc/usage/limits"
"github.com/awakari/bot-telegram/api/http/interests"
"github.com/awakari/bot-telegram/api/http/pub"
apiHttpSubs "github.com/awakari/bot-telegram/api/http/subscriptions"
"github.com/awakari/bot-telegram/config"
"github.com/awakari/bot-telegram/service"
"github.com/awakari/bot-telegram/service/chats"
"github.com/awakari/bot-telegram/service/limits"
"github.com/awakari/bot-telegram/service/messages"
"github.com/awakari/bot-telegram/service/subscriptions"
"github.com/awakari/bot-telegram/service/support"
"github.com/awakari/bot-telegram/util"
"github.com/cloudevents/sdk-go/binding/format/protobuf/v2/pb"
"github.com/gin-gonic/gin"
"github.com/microcosm-cc/bluemonday"
grpcpool "github.com/processout/grpc-go-pool"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"gopkg.in/telebot.v3"
"log/slog"
"net/http"
"os"
"strings"
"sync"
"time"
)
func main() {
// init config and logger
slog.Info("starting...")
cfg, err := config.NewConfigFromEnv()
if err != nil {
slog.Error(fmt.Sprintf("failed to load the config: %s", err))
}
opts := slog.HandlerOptions{
Level: slog.Level(cfg.Log.Level),
}
log := slog.New(slog.NewTextHandler(os.Stdout, &opts))
svcPub := pub.NewService(http.DefaultClient, cfg.Api.Writer.Uri, cfg.Api.Token.Internal)
svcPub = pub.NewLogging(svcPub, log)
log.Info("initialized the Awakari publish API client")
svcInterests := interests.NewService(http.DefaultClient, cfg.Api.Interests.Uri, cfg.Api.Token.Internal)
svcInterests = interests.NewLogging(svcInterests, log)
log.Info("initialized the Awakari interests API client")
// init websub
clientHttp := http.Client{}
svcSubs := apiHttpSubs.NewService(&clientHttp, cfg.Api.Subscriptions.Uri, cfg.Api.Token.Internal)
svcSubs = apiHttpSubs.NewServiceLogging(svcSubs, log)
urlCallbackBase := fmt.Sprintf(
"%s://%s:%d%s",
cfg.Api.Subscriptions.CallBack.Protocol,
cfg.Api.Subscriptions.CallBack.Host,
cfg.Api.Subscriptions.CallBack.Port,
cfg.Api.Subscriptions.CallBack.Path,
)
// init queues
connQueue, err := grpc.NewClient(cfg.Api.Queue.Uri, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
panic(err)
}
log.Info("connected to the queue service")
clientQueue := queue.NewServiceClient(connQueue)
svcQueue := queue.NewService(clientQueue)
svcQueue = queue.NewLoggingMiddleware(svcQueue, log)
err = svcQueue.SetConsumer(context.TODO(), cfg.Api.Queue.InterestsCreated.Name, cfg.Api.Queue.InterestsCreated.Subj)
if err != nil {
panic(err)
}
log.Info(fmt.Sprintf("initialized the %s queue", cfg.Api.Queue.InterestsCreated.Name))
go func() {
err = consumeQueueInterestsCreated(
context.Background(),
svcSubs,
urlCallbackBase,
cfg.Api.GroupId,
svcQueue,
cfg.Api.Queue.InterestsCreated.Name,
cfg.Api.Queue.InterestsCreated.Subj,
cfg.Api.Queue.InterestsCreated.BatchSize,
)
if err != nil {
panic(err)
}
}()
connPoolLimits, err := grpcpool.New(
func() (*grpc.ClientConn, error) {
return grpc.NewClient(cfg.Api.Usage.Uri, grpc.WithTransportCredentials(insecure.NewCredentials()))
},
int(cfg.Api.Usage.Connection.Count.Init),
int(cfg.Api.Usage.Connection.Count.Max),
cfg.Api.Usage.Connection.IdleTimeout,
)
if err != nil {
panic(err)
}
defer connPoolLimits.Close()
clientLimits := apiGrpcUsageLimits.NewClientPool(connPoolLimits)
svcLimits := limits.NewService(clientLimits)
svcLimits = limits.NewLogging(svcLimits, log)
// init events format, see https://core.telegram.org/bots/api#html-style for details
htmlPolicy := bluemonday.NewPolicy()
htmlPolicy.AllowStandardURLs()
htmlPolicy.
AllowAttrs("href").
OnElements("a")
htmlPolicy.AllowElements("b", "strong", "i", "em", "u", "ins", "s", "strike", "del", "code", "pre")
htmlPolicy.
AllowAttrs("class").
OnElements("span")
htmlPolicy.AllowURLSchemes("tg")
htmlPolicy.
AllowAttrs("emoji-ids").
OnElements("tg-emoji")
htmlPolicy.
AllowAttrs("class").
OnElements("code")
htmlPolicy.AllowDataURIImages()
fmtMsg := messages.Format{
HtmlPolicy: htmlPolicy,
UriEvtBase: cfg.Api.Messages.UriBase,
}
// init handlers
groupId := cfg.Api.GroupId
supportHandler := support.Handler{
SupportChatId: cfg.Api.Telegram.SupportChatId,
}
chanPostHandler := messages.ChanPostHandler{
SvcPub: svcPub,
GroupId: groupId,
Log: log,
Channels: map[string]time.Time{},
ChansLock: &sync.Mutex{},
CfgMsgs: cfg.Api.Messages,
}
handlerSubscribe := subscriptions.StartHandler(svcInterests, svcSubs, svcLimits, urlCallbackBase, groupId)
callbackHandlers := map[string]service.ArgHandlerFunc{
subscriptions.CmdStart: handlerSubscribe,
subscriptions.CmdStop: subscriptions.Stop(svcSubs, urlCallbackBase, cfg.Api.GroupId),
subscriptions.CmdPageNext: subscriptions.PageNext(svcInterests, svcSubs, groupId, urlCallbackBase),
subscriptions.CmdPageNextFollowing: subscriptions.PageNextFollowing(svcInterests, svcSubs, groupId, urlCallbackBase),
}
replyHandlers := map[string]service.ArgHandlerFunc{
subscriptions.ReqSubCreate: subscriptions.CreateBasicReplyHandlerFunc(svcInterests, groupId),
subscriptions.ReqStart: handlerSubscribe,
messages.ReqMsgPub: messages.PublishBasicReplyHandlerFunc(svcPub, groupId, cfg),
"support": supportHandler.Request,
}
txtHandlers := map[string]telebot.HandlerFunc{}
hRoot := service.RootHandler{
ReplyHandlers: replyHandlers,
TxtHandlers: txtHandlers,
}
hPaid := service.PaidChatMemberHandler{
GroupId: groupId,
LimitByChatIdSubscriptions: cfg.Api.Usage.Limits.Subscriptions,
LimitByChatIdInterests: cfg.Api.Usage.Limits.Interests,
LimitByChatIdInterestsPublic: cfg.Api.Usage.Limits.InterestsPublic,
SvcLimits: svcLimits,
}
// init Telegram bot
s := telebot.Settings{
Client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
},
Poller: &telebot.Webhook{
Endpoint: &telebot.WebhookEndpoint{
PublicURL: fmt.Sprintf("https://%s%s", cfg.Api.Telegram.Webhook.Host, cfg.Api.Telegram.Webhook.Path),
},
Listen: fmt.Sprintf(":%d", cfg.Api.Telegram.Webhook.Port),
MaxConnections: int(cfg.Api.Telegram.Webhook.ConnMax),
SecretToken: cfg.Api.Telegram.Webhook.Token,
AllowedUpdates: []string{
"callback_query",
"channel_post",
"chat_member",
"chosen_inline_result",
"inline_query",
"message",
"poll",
},
},
Token: cfg.Api.Telegram.Token,
}
log.Debug(fmt.Sprintf("Telegram bot settigs: %+v", s))
var b *telebot.Bot
b, err = telebot.NewBot(s)
if err != nil {
panic(err)
}
err = b.SetCommands([]telebot.Command{
{
Text: "start",
Description: "Start: list own interests",
},
{
Text: "app",
Description: "Go to application",
},
{
Text: "pub",
Description: "Publish a simple message",
},
{
Text: "sub",
Description: "Create a simple interest and subscribe",
},
{
Text: "following",
Description: "List subscriptions in this chat",
},
{
Text: "interests",
Description: "List all available interests",
},
{
Text: "donate",
Description: "Donate",
},
{
Text: "help",
Description: "Help",
},
{
Text: "support",
Description: "Request support",
},
{
Text: "terms",
Description: "Terms of service",
},
{
Text: "privacy",
Description: "Privacy policy",
},
})
if err != nil {
panic(err)
}
// init the Telegram Bot grpc service
controllerGrpc := apiGrpcTgBot.NewController(
[]byte(cfg.Api.Telegram.Token),
chanPostHandler,
svcSubs,
urlCallbackBase,
log,
b,
fmtMsg,
)
go func() {
log.Info(fmt.Sprintf("starting to listen the grpc API @ port #%d...", cfg.Api.Telegram.Bot.Port))
err = apiGrpc.Serve(cfg.Api.Telegram.Bot.Port, controllerGrpc)
if err != nil {
panic(err)
}
}()
// assign handlers
b.Use(func(next telebot.HandlerFunc) telebot.HandlerFunc {
return service.LoggingHandlerFunc(next, log)
})
subListHandlerFunc := subscriptions.ListOnGroupStartHandlerFunc(svcInterests, svcSubs, groupId, urlCallbackBase)
b.Handle(
"/start",
service.ErrorHandlerFunc(func(tgCtx telebot.Context) (err error) {
cmdTxt := tgCtx.Text()
if strings.HasPrefix(cmdTxt, "/start ") && len(cmdTxt) > len("/start ") {
args := strings.Split(cmdTxt, " ")
err = handlerSubscribe(tgCtx, args...)
} else {
chat := tgCtx.Chat()
switch chat.Type {
case telebot.ChatChannel:
case telebot.ChatChannelPrivate:
case telebot.ChatGroup:
err = subListHandlerFunc(tgCtx)
case telebot.ChatSuperGroup:
err = subListHandlerFunc(tgCtx)
case telebot.ChatPrivate:
// err = service.DonationMessagePin(tgCtx)
err = subListHandlerFunc(tgCtx)
default:
err = fmt.Errorf("unsupported chat type (supported options: \"private\", \"group\", \"supergroup\"): %s", chat.Type)
}
}
return
}),
)
b.Handle("/app", func(tgCtx telebot.Context) error {
return tgCtx.Send("<a href=\"https://awakari.com/login.html\">Link to App</a>", telebot.ModeHTML)
})
b.Handle("/pub", messages.PublishBasicRequest)
b.Handle("/sub", subscriptions.CreateBasicRequest)
b.Handle("/following", subscriptions.ListFollowing(svcInterests, svcSubs, groupId, urlCallbackBase))
b.Handle("/interests", subscriptions.ListPublicHandlerFunc(svcInterests, svcSubs, groupId, urlCallbackBase))
b.Handle("/donate", service.DonationHandler)
b.Handle("/help", func(tgCtx telebot.Context) error {
return tgCtx.Send("Open the <a href=\"https://awakari.com/#resources\">link</a>", telebot.ModeHTML)
})
b.Handle("/support", func(tgCtx telebot.Context) error {
_ = tgCtx.Send("Describe your issue in the reply to the next message")
return tgCtx.Send("support", &telebot.ReplyMarkup{
ForceReply: true,
})
})
b.Handle("/terms", func(tgCtx telebot.Context) error {
return tgCtx.Send("Open the <a href=\"https://awakari.com/tos.html\">terms link</a>", telebot.ModeHTML)
})
b.Handle("/privacy", func(tgCtx telebot.Context) error {
return tgCtx.Send("Open the <a href=\"https://awakari.com/privacy.html\">privacy link</a>", telebot.ModeHTML)
})
b.Handle(telebot.OnCallback, service.ErrorHandlerFunc(service.Callback(callbackHandlers)))
b.Handle(telebot.OnText, service.ErrorHandlerFunc(hRoot.Handle))
b.Handle(telebot.OnPhoto, service.ErrorHandlerFunc(hRoot.Handle))
b.Handle(telebot.OnAudio, service.ErrorHandlerFunc(hRoot.Handle))
b.Handle(telebot.OnVideo, service.ErrorHandlerFunc(hRoot.Handle))
b.Handle(telebot.OnDocument, service.ErrorHandlerFunc(hRoot.Handle))
b.Handle(telebot.OnLocation, service.ErrorHandlerFunc(hRoot.Handle))
//
b.Handle(telebot.OnChannelPost, func(tgCtx telebot.Context) (err error) {
txt := tgCtx.Text()
ch := tgCtx.Chat()
chanUserName := ch.Username
if strings.HasPrefix(chanUserName, cfg.Api.Telegram.PublicInterestChannelPrefix) && strings.HasPrefix(txt, "/start ") {
// public interest channel created by Awakari
args := strings.Split(txt, " ")
err = handlerSubscribe(tgCtx, args...)
} else {
err = chanPostHandler.Publish(tgCtx, chanUserName)
}
return
})
b.Handle(telebot.OnAddedToGroup, func(tgCtx telebot.Context) error {
// err = service.DonationMessagePin(tgCtx)
return service.ErrorHandlerFunc(subListHandlerFunc)(tgCtx)
})
b.Handle(telebot.OnChatMember, func(tgCtx telebot.Context) error {
err = hPaid.Handle(tgCtx)
ll := util.LogLevel(err)
log.Log(context.TODO(), ll, fmt.Sprintf("PaidChatMemberHandler.Handle(): %s", err))
return err
})
//
go b.Start()
// chats websub handler (subscriber)
hChats := chats.NewHandler(cfg.Api.Subscriptions.Uri+"/v1", fmtMsg, urlCallbackBase, svcSubs, b, svcInterests, groupId)
r := gin.Default()
r.
Group(cfg.Api.Subscriptions.CallBack.Path).
GET("/:chatId", hChats.Confirm).
POST("/:chatId", hChats.DeliverMessages)
err = r.Run(fmt.Sprintf(":%d", cfg.Api.Subscriptions.CallBack.Port))
if err != nil {
panic(err)
}
}
func consumeQueueInterestsCreated(
ctx context.Context,
svcSubs apiHttpSubs.Service,
urlCallbackBase string,
groupId string,
svcQueue queue.Service,
name, subj string,
batchSize uint32,
) (err error) {
consume := func(evts []*pb.CloudEvent) (err error) {
// commented because the bot should not consume the user's subscriptions permits anymore
//for _, evt := range evts {
// interestId := evt.GetTextData()
// var userId string
// if userIdAttr, userIdPresent := evt.Attributes["awakariuserid"]; userIdPresent {
// userId = userIdAttr.GetCeString()
// }
// if !strings.HasPrefix(userId, util.PrefixUserId) {
// continue
// }
// var chatId int64
// if err == nil {
// chatId, err = strconv.ParseInt(userId[len(util.PrefixUserId):], 10, 64)
// if err != nil {
// err = status.Error(codes.InvalidArgument, fmt.Sprintf("User id should end with numeric id: %s, %s", userId, err))
// }
// }
// if err == nil {
// err = svcSubs.Subscribe(ctx, interestId, groupId, userId, subscriptions.MakeCallbackUrl(urlCallbackBase, chatId, userId), 0)
// }
// if err != nil {
// break
// }
//}
return
}
for {
err = svcQueue.ReceiveMessages(ctx, name, subj, batchSize, consume)
if err != nil {
break
}
}
return
}