-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook_server.go
98 lines (77 loc) · 2.11 KB
/
webhook_server.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
package bot
import (
"fmt"
"strconv"
"strings"
"sync"
"github.com/gofiber/fiber/v2"
"github.com/mymmrac/telego"
"github.com/samber/do"
"github.com/telle-bots/bot-runner/pkg/config"
"go.uber.org/zap"
)
type botContext struct {
handler telego.WebhookHandler
secretToken string
}
type WebhookServer struct {
cfg *config.Config
log *zap.SugaredLogger
app *fiber.App
lock *sync.Mutex
botHandlers map[int64]botContext
}
func NewWebhookServer(in *do.Injector) (*WebhookServer, error) {
return &WebhookServer{
cfg: do.MustInvoke[*config.Config](in),
log: do.MustInvoke[*zap.SugaredLogger](in),
app: fiber.New(fiber.Config{
AppName: "Bot Webhook Server",
DisableStartupMessage: true,
}),
lock: &sync.Mutex{},
botHandlers: map[int64]botContext{},
}, nil
}
func (w *WebhookServer) Start() error {
w.app.Post("/bots/:botID<int>/webhook", w.botHandler)
return w.app.Listen(w.cfg.RunnerListenAddress)
}
func (w *WebhookServer) Shutdown() error {
return w.app.ShutdownWithTimeout(w.cfg.ShutdownTimeout)
}
func (w *WebhookServer) RegisterBot(path string, handler telego.WebhookHandler) error {
botIDStr, token, ok := strings.Cut(path, delimiter)
if !ok {
return fmt.Errorf("invalid bot handler path: %q", path)
}
botID, _ := strconv.ParseInt(botIDStr, 10, 64)
w.lock.Lock()
defer w.lock.Unlock()
w.botHandlers[botID] = botContext{
handler: handler,
secretToken: token,
}
return nil
}
func (w *WebhookServer) UnregisterBot(botID int64) {
w.lock.Lock()
defer w.lock.Unlock()
delete(w.botHandlers, botID)
}
func (w *WebhookServer) botHandler(ctx *fiber.Ctx) error {
botID, _ := strconv.ParseInt(ctx.Params("botID"), 10, 64)
bot, ok := w.botHandlers[botID]
if !ok {
return ctx.SendStatus(fiber.StatusNotFound)
}
token := ctx.Get(telego.WebhookSecretTokenHeader)
if token != bot.secretToken {
return ctx.SendStatus(fiber.StatusForbidden)
}
if err := bot.handler(ctx.Body()); err != nil {
w.log.Errorw("webhook bot handler", "bot-id", botID, "error", err)
return ctx.SendStatus(fiber.StatusInternalServerError)
}
return ctx.SendStatus(fiber.StatusOK)
}