-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
247 lines (209 loc) · 6.14 KB
/
Copy pathmain.go
File metadata and controls
247 lines (209 loc) · 6.14 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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/gofiber/fiber/v3"
"github.com/mymmrac/telego"
"github.com/mymmrac/telego/telegohandler"
"github.com/spam-observer/internal/ai"
"github.com/spam-observer/internal/auth"
"github.com/spam-observer/internal/bot"
"github.com/spam-observer/internal/db"
"github.com/spam-observer/internal/handler"
"github.com/spam-observer/internal/logstream"
"github.com/spam-observer/internal/tracker"
)
const webhookPath = "/api/webhook/tg"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
envBotToken := os.Getenv("BOT_TOKEN")
dbPath := os.Getenv("DB_PATH")
if dbPath == "" {
dbPath = "./data/spam-observer.db"
}
webhookSecret := os.Getenv("WEBHOOK_SECRET")
if webhookSecret == "" {
webhookSecret = "spamo-whsec"
}
publicURL := os.Getenv("PUBLIC_URL")
if err := os.MkdirAll("./data", 0755); err != nil {
log.Fatalf("Failed to create data directory: %v", err)
}
store, err := db.New(dbPath)
if err != nil {
log.Fatalf("Failed to open database: %v", err)
}
defer store.Close()
if err := handler.InitAdmin(store); err != nil {
log.Fatalf("Failed to initialize admin: %v", err)
}
broker := logstream.NewBroker()
defer broker.Close()
broker.OnPublish = func(e logstream.Entry) {
if err := store.InsertLog(e); err != nil {
log.Printf("Failed to persist log entry: %v", err)
}
}
go func() {
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for range ticker.C {
if err := store.PurgeOldLogs(7 * 24 * time.Hour); err != nil {
log.Printf("Failed to purge old logs: %v", err)
}
}
}()
jwt := auth.NewJWTManager()
trk := tracker.New(store)
defer trk.Stop()
botEnabled := new(atomic.Bool)
if enabled, err := store.GetBotEnabled(); err == nil {
botEnabled.Store(enabled)
} else {
botEnabled.Store(true)
}
warnInGroup := new(atomic.Bool)
if wig, err := store.GetWarnInGroup(); err == nil {
warnInGroup.Store(wig)
} else {
warnInGroup.Store(false)
}
app := fiber.New(fiber.Config{
AppName: "SpamObserver",
BodyLimit: 1 * 1024 * 1024,
ReadTimeout: 30 * time.Second,
WriteTimeout: 0,
IdleTimeout: 120 * time.Second,
StreamRequestBody: true,
})
updatesChan := make(chan telego.Update, 256)
aiConfigFn := func() *ai.Config {
cfg, err := store.GetAIConfig()
if err != nil {
return nil
}
if cfg.BaseURL == "" || cfg.APIKey == "" || cfg.Model == "" {
return nil
}
return &ai.Config{BaseURL: cfg.BaseURL, APIKey: cfg.APIKey, Model: cfg.Model}
}
monitor := bot.New(broker, store.GetMonitoredIDs, botEnabled.Load, trk, store.GetVerificationBotIDs, aiConfigFn, func(chatID int64, title string) {
_ = store.UpdateGroupTitle(chatID, title)
}, warnInGroup.Load)
var (
botMu sync.Mutex
botCtx context.Context
botCancel context.CancelFunc
bh *telegohandler.BotHandler
)
startBot := func(token string) error {
botMu.Lock()
defer botMu.Unlock()
if botCancel != nil {
if bh != nil {
bh.Stop()
}
botCancel()
}
telegoBot, err := telego.NewBot(token, telego.WithDiscardLogger())
if err != nil {
return fmt.Errorf("create bot: %w", err)
}
monitor.SetBot(telegoBot)
botCtx, botCancel = context.WithCancel(context.Background())
bh, err = telegohandler.NewBotHandler(telegoBot, updatesChan)
if err != nil {
botCancel()
return fmt.Errorf("create bot handler: %w", err)
}
bh.Handle(func(ctx *telegohandler.Context, update telego.Update) error {
monitor.ProcessUpdate(update)
return nil
}, telegohandler.Any())
go func() {
if err := bh.Start(); err != nil {
broker.Publish(logstream.Error("SYSTEM", "Bot handler stopped: %v", err))
}
}()
if publicURL != "" {
go func() {
time.Sleep(2 * time.Second)
if err := telegoBot.SetWebhook(botCtx, &telego.SetWebhookParams{
URL: publicURL + webhookPath,
SecretToken: webhookSecret,
AllowedUpdates: []string{"message", "business_message", "guest_message", "chat_member", "my_chat_member", "callback_query"},
}); err != nil {
broker.Publish(logstream.Error("SYSTEM", "Failed to set webhook: %v", err))
} else {
broker.Publish(logstream.Info("SYSTEM", "Webhook registered at %s", publicURL+webhookPath))
}
}()
} else {
broker.Publish(logstream.Info("SYSTEM", "Bot started (no PUBLIC_URL, webhook not set)"))
}
return nil
}
app.Add([]string{"POST"}, webhookPath, func(c fiber.Ctx) error {
secretHeader := c.Get(telego.WebhookSecretTokenHeader)
if secretHeader != webhookSecret {
return c.SendStatus(fiber.StatusForbidden)
}
var update telego.Update
if err := json.Unmarshal(c.Body(), &update); err != nil {
return c.SendStatus(fiber.StatusBadRequest)
}
select {
case updatesChan <- update:
default:
}
return c.SendStatus(fiber.StatusOK)
})
h := handler.New(store, broker, jwt, botEnabled, startBot, trk, warnInGroup)
h.Register(app)
broker.Publish(logstream.Info("SYSTEM", "SpamObserver starting on port %s", port))
dbToken, _ := store.GetBotToken()
switch {
case dbToken != "":
broker.Publish(logstream.Info("SYSTEM", "Using bot token from database"))
if err := startBot(dbToken); err != nil {
broker.Publish(logstream.Error("SYSTEM", "Failed to start bot with DB token: %v", err))
}
case envBotToken != "":
broker.Publish(logstream.Info("SYSTEM", "Using bot token from environment"))
if err := startBot(envBotToken); err != nil {
broker.Publish(logstream.Error("SYSTEM", "Failed to start bot with env token: %v", err))
}
default:
broker.Publish(logstream.Warn("SYSTEM", "No bot token configured. Set one via Settings to start monitoring."))
}
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh
broker.Publish(logstream.Info("SYSTEM", "Shutdown signal received"))
botMu.Lock()
if botCancel != nil {
if bh != nil {
bh.Stop()
}
botCancel()
}
botMu.Unlock()
_ = app.Shutdown()
}()
fmt.Printf("SpamObserver listening on :%s\n", port)
if err := app.Listen(":" + port); err != nil {
log.Fatalf("Server error: %v", err)
}
}