This repository was archived by the owner on Jul 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
493 lines (407 loc) · 14 KB
/
Copy pathmain.go
File metadata and controls
493 lines (407 loc) · 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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package main
import (
"bufio"
"context"
"fmt"
"os"
"os/signal"
"runtime/debug"
"strings"
"syscall"
"time"
"github.com/bradselph/CODStatusBot/bot"
"github.com/bradselph/CODStatusBot/command/verdansk"
"github.com/bradselph/CODStatusBot/configuration"
"github.com/bradselph/CODStatusBot/database"
"github.com/bradselph/CODStatusBot/logger"
"github.com/bradselph/CODStatusBot/models"
"github.com/bradselph/CODStatusBot/services"
"github.com/bwmarrin/discordgo"
)
var discord *discordgo.Session
func loadEnv(filename string) error {
file, err := os.Open(filename)
if err != nil {
return fmt.Errorf("error opening config file: %w", err)
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Printf("Error closing config file: %v\n", err)
}
}(file)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
value = strings.Trim(value, `"'`)
if err := os.Setenv(key, value); err != nil {
return fmt.Errorf("error setting environment variable %s: %w", key, err)
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("error reading config file: %w", err)
}
return nil
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovered from panic: %v\n%s\n", r, debug.Stack())
}
}()
if err := run(); err != nil {
fmt.Printf("Bot encountered an error and is shutting down: %v\n", err)
os.Exit(1)
}
}
func run() error {
fmt.Println("Starting COD Status Bot...")
if err := loadEnv("config.env"); err != nil {
return fmt.Errorf("failed to load environment variables: %w", err)
}
if err := configuration.Load(); err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
if err := logger.InitializeLogger(); err != nil {
return fmt.Errorf("failed to initialize logger: %w", err)
}
logger.Log.Info("Starting COD Status Bot...")
cfg := configuration.Get()
if cfg.Discord.Token == "" {
return fmt.Errorf("DISCORD_TOKEN is required but not set")
}
if cfg.Database.Host == "" || cfg.Database.User == "" || cfg.Database.Password == "" || cfg.Database.Name == "" {
return fmt.Errorf("database configuration is incomplete")
}
services.InitHTTPClients()
if !cfg.CaptchaService.Capsolver.Enabled && !cfg.CaptchaService.EZCaptcha.Enabled && !cfg.CaptchaService.TwoCaptcha.Enabled {
logger.Log.Warn("No captcha services are enabled - functionality will be limited")
} else {
var enabledServices []string
if cfg.CaptchaService.Capsolver.Enabled && cfg.CaptchaService.Capsolver.ClientKey != "" {
enabledServices = append(enabledServices, "Capsolver")
if err := services.ValidateDefaultCapsolverConfig(); err != nil {
logger.Log.WithError(err).Error("Capsolver service enabled but configuration is invalid")
cfg.CaptchaService.Capsolver.Enabled = false
} else {
logger.Log.Info("Capsolver service enabled and configured correctly")
}
}
if cfg.CaptchaService.EZCaptcha.Enabled && cfg.CaptchaService.EZCaptcha.ClientKey != "" {
enabledServices = append(enabledServices, "EZCaptcha")
if services.VerifyEZCaptchaConfig() {
logger.Log.Info("EZCaptcha service enabled and configured correctly")
} else {
logger.Log.Error("EZCaptcha service enabled but configuration is invalid")
cfg.CaptchaService.EZCaptcha.Enabled = false
}
}
if cfg.CaptchaService.TwoCaptcha.Enabled && cfg.CaptchaService.TwoCaptcha.ClientKey != "" {
enabledServices = append(enabledServices, "2Captcha")
logger.Log.Info("2Captcha service enabled and configured correctly")
}
if len(enabledServices) == 0 {
logger.Log.Error("No properly configured captcha services found")
} else {
logger.Log.Infof("Enabled captcha services: %s", strings.Join(enabledServices, ", "))
}
}
if err := database.Databaselogin(); err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
logger.Log.Info("Database connection established successfully")
services.InitializeProxyStatsAfterDB()
logger.Log.Info("Proxy stats initialization completed")
appShardManager := services.GetAppShardManager()
appShardManager.EnsureInitialized()
shardCtx, shardCancel := context.WithCancel(context.Background())
defer shardCancel()
appShardManager.StartHeartbeat(shardCtx)
logger.Log.Infof("Application shard %d of %d initialized successfully (Instance: %s)",
appShardManager.ShardID, appShardManager.TotalShards, appShardManager.InstanceID)
cfg = configuration.Get()
if !cfg.Sharding.Enabled || appShardManager.IsLeader() {
services.StartAdminAPI()
logger.Log.Info("Started Admin API")
} else {
logger.Log.Info("Skipping Admin API startup (not leader shard)")
}
var err error
discord, err = bot.StartBot()
if err != nil {
return fmt.Errorf("failed to start Discord bot: %w", err)
}
logger.Log.Info("Discord bot started successfully")
services.StartNotificationProcessor(discord)
logger.Log.Info("Notification processor started successfully")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
periodicTasksCtx, cancelPeriodicTasks := context.WithCancel(ctx)
go startPeriodicTasks(periodicTasksCtx, discord, appShardManager)
errorCleanupCtx, cancelErrorCleanup := context.WithCancel(ctx)
if !cfg.Sharding.Enabled || appShardManager.IsLeader() {
go services.StartErrorCleanupRoutine(errorCleanupCtx)
logger.Log.Info("Started error cleanup routine")
}
edgeCaseCtx, cancelEdgeCase := context.WithCancel(ctx)
if !cfg.Sharding.Enabled || appShardManager.IsLeader() {
go services.StartEdgeCaseCleanupRoutine(edgeCaseCtx)
logger.Log.Info("Started edge case cleanup routine")
}
if !cfg.Sharding.Enabled || appShardManager.IsLeader() {
verdansk.InitCleanupRoutine()
logger.Log.Info("Initialized Verdansk cleanup routine")
}
logger.Log.Info("COD Status Bot startup complete")
go startHealthCheckRoutine(discord, appShardManager)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
startupComplete := make(chan bool, 1)
go func() {
time.Sleep(5 * time.Second)
startupComplete <- true
}()
select {
case <-startupComplete:
logger.Log.Info("All services are ready")
case <-time.After(time.Duration(cfg.Startup.TimeoutSeconds) * time.Second):
logger.Log.Warn("Startup timeout reached, continuing anyway")
}
services.LogAnalyticsEvent("shard_startup_complete", "", "", "", "",
appShardManager.ShardID, appShardManager.InstanceID, map[string]interface{}{
"is_leader": appShardManager.IsLeader(),
"startup_duration_seconds": 5,
})
<-stop
logger.Log.Info("Shutting down COD Status Bot...")
cancelPeriodicTasks()
cancelErrorCleanup()
cancelEdgeCase()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), cfg.Startup.ShutdownTimeout)
defer shutdownCancel()
done := make(chan struct{})
go func() {
services.HandleGracefulShutdown(discord)
close(done)
}()
select {
case <-done:
logger.Log.Info("All goroutines terminated gracefully")
case <-shutdownCtx.Done():
logger.Log.Warn("Shutdown timed out, forcing exit")
}
services.LogAnalyticsEvent("shard_shutdown", "", "", "", "",
appShardManager.ShardID, appShardManager.InstanceID, map[string]interface{}{
"shutdown_reason": "signal_received",
})
logger.Log.Info("Shutdown complete")
return nil
}
func startPeriodicTasks(ctx context.Context, s *discordgo.Session, shardManager *services.AppShardManager) {
cfg := configuration.Get()
go func() {
checkTicker := time.NewTicker(time.Duration(cfg.Intervals.Sleep) * time.Minute)
defer checkTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-checkTicker.C:
if shardManager.Initialized {
logger.Log.Debugf("Shard %d starting account check cycle", shardManager.ShardID)
services.CheckAccounts(s)
}
}
}
}()
if !cfg.Sharding.Enabled || shardManager.IsLeader() {
go func() {
updateTicker := time.NewTicker(time.Hour)
defer updateTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-updateTicker.C:
logger.Log.Debug("Processing consolidated daily updates")
var allUsers []models.UserSettings
if err := database.DB.Find(&allUsers).Error; err != nil {
logger.Log.WithError(err).Error("Failed to fetch users for consolidated updates")
continue
}
users := services.FilterUserSettingsByShardAssignment(allUsers)
if cfg.Sharding.Enabled && shardManager.TotalShards > 1 {
logger.Log.Debugf("Processing daily updates for %d users assigned to this shard (filtered from %d total)", len(users), len(allUsers))
} else {
logger.Log.Debugf("Processing daily updates for %d users (sharding disabled)", len(users))
}
processedUsers := 0
for _, user := range users {
if user.UserID == "" {
continue
}
if cfg.Sharding.Enabled && shardManager.TotalShards > 1 {
if !shardManager.IsUserAssignedToShard(user.UserID) {
logger.Log.Debugf("User %s no longer assigned to this shard, skipping", user.UserID)
continue
}
}
var accounts []models.Account
if err := database.DB.Where("user_id = ? AND is_check_disabled = ? AND is_expired_cookie = ?",
user.UserID, false, false).Find(&accounts).Error; err != nil {
logger.Log.WithError(err).Errorf("Failed to fetch accounts for user %s", user.UserID)
continue
}
if time.Since(user.LastDailyUpdateNotification) >=
time.Duration(cfg.Intervals.Notification)*time.Hour {
services.SendConsolidatedDailyUpdate(s, user.UserID, user, accounts)
processedUsers++
}
}
logger.Log.Debugf("Processed %d users for daily updates", processedUsers)
}
}
}()
go services.ScheduleBalanceChecks(s)
go func() {
announcementTicker := time.NewTicker(24 * time.Hour)
defer announcementTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-announcementTicker.C:
if err := services.SendAnnouncementToAllUsers(s); err != nil {
logger.Log.WithError(err).Error("Failed to send global announcement")
}
}
}
}()
go func() {
cleanupTicker := time.NewTicker(12 * time.Hour)
defer cleanupTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-cleanupTicker.C:
services.CleanupOldRateLimitData()
logger.Log.Debug("Completed rate limit cleanup")
}
}
}()
go func() {
userCleanupTicker := time.NewTicker(cfg.Users.CleanupInterval)
defer userCleanupTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-userCleanupTicker.C:
logger.Log.Info("Starting comprehensive cleanup")
services.CleanupInactiveUsers()
logger.Log.Info("Completed inactive users cleanup")
services.CleanupUsersByShardAssignment()
logger.Log.Info("Completed shard assignment cleanup")
services.CleanupOldShardInfo()
logger.Log.Info("Completed shard info cleanup")
services.LogInstallationStats(s)
logger.Log.Info("Completed comprehensive cleanup")
}
}
}()
go func() {
analyticsTicker := time.NewTicker(24 * time.Hour)
defer analyticsTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-analyticsTicker.C:
logger.Log.Info("Starting analytics cleanup")
if err := services.CleanupOldAnalyticsData(cfg.Admin.RetentionDays); err != nil {
logger.Log.WithError(err).Error("Failed to clean up old analytics data")
} else {
logger.Log.Info("Completed analytics data cleanup")
}
stats, err := services.ValidateUserShardAssignments()
if err != nil {
logger.Log.WithError(err).Error("Failed to validate user shard assignments")
} else {
logger.Log.Infof("Shard assignment validation: %+v", stats)
}
}
}
}()
}
go func() {
statusTicker := time.NewTicker(60 * time.Minute)
defer statusTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-statusTicker.C:
if err := s.UpdateWatchStatus(0, bot.StatusMessage); err != nil {
logger.Log.WithError(err).Error("Failed to refresh presence status")
}
}
}
}()
if cfg.Sharding.Enabled {
logger.Log.Infof("Shard %d periodic tasks started (leader: %v)", shardManager.ShardID, shardManager.IsLeader())
} else {
logger.Log.Info("Periodic tasks started (sharding disabled)")
}
}
func startHealthCheckRoutine(s *discordgo.Session, shardManager *services.AppShardManager) {
cfg := configuration.Get()
ticker := time.NewTicker(cfg.Startup.HealthCheckInterval)
defer ticker.Stop()
for range ticker.C {
healthy := true
issues := []string{}
if !shardManager.Initialized {
logger.Log.Warn("Shard manager not initialized during health check, attempting to initialize")
shardManager.EnsureInitialized()
}
if s.DataReady == false {
logger.Log.Errorf("Shard %d Discord connection is not ready", shardManager.ShardID)
healthy = false
issues = append(issues, "Discord connection not ready")
}
if err := database.CheckConnection(); err != nil {
logger.Log.WithError(err).Errorf("Shard %d database health check failed", shardManager.ShardID)
healthy = false
issues = append(issues, fmt.Sprintf("Database connection failed: %v", err))
}
if !shardManager.Initialized {
logger.Log.Errorf("Shard %d manager could not be initialized", shardManager.ShardID)
healthy = false
issues = append(issues, "Shard manager initialization failed")
}
if time.Now().Minute()%5 == 0 {
services.PerformShardHealthCheck()
}
if healthy {
logger.Log.Debugf("Shard %d health check passed", shardManager.ShardID)
} else {
logger.Log.Errorf("Shard %d health check failed: %v", shardManager.ShardID, issues)
services.LogAnalyticsEvent("health_check_failed", "", "", "", "failed",
shardManager.ShardID, shardManager.InstanceID, map[string]interface{}{
"issues": issues,
"discord_ready": s.DataReady,
"shard_initialized": shardManager.Initialized,
})
}
}
}