-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathmain.go
More file actions
448 lines (383 loc) · 14.5 KB
/
main.go
File metadata and controls
448 lines (383 loc) · 14.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"path/filepath"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/gomessguii/logger"
"github.com/joho/godotenv"
"go.mau.fi/whatsmeow"
"gorm.io/gorm"
_ "modernc.org/sqlite"
call_handler "github.com/EvolutionAPI/evolution-go/pkg/call/handler"
call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service"
chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler"
chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service"
community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler"
community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service"
config "github.com/EvolutionAPI/evolution-go/pkg/config"
"github.com/EvolutionAPI/evolution-go/pkg/core"
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
nats_producer "github.com/EvolutionAPI/evolution-go/pkg/events/nats"
rabbitmq_producer "github.com/EvolutionAPI/evolution-go/pkg/events/rabbitmq"
webhook_producer "github.com/EvolutionAPI/evolution-go/pkg/events/webhook"
websocket_producer "github.com/EvolutionAPI/evolution-go/pkg/events/websocket"
group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler"
group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service"
instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler"
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler"
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service"
auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware"
newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler"
newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service"
poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler"
routes "github.com/EvolutionAPI/evolution-go/pkg/routes"
send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler"
send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service"
server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler"
storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"
minio_storage "github.com/EvolutionAPI/evolution-go/pkg/storage/minio"
"github.com/EvolutionAPI/evolution-go/pkg/telemetry"
user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler"
user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
amqp "github.com/rabbitmq/amqp091-go"
)
var devMode = flag.Bool("dev", false, "Enable development mode")
var version = func() string {
if v, err := os.ReadFile("VERSION"); err == nil {
return strings.TrimSpace(string(v))
}
return "dev"
}()
func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.Config, conn *amqp.Connection, exPath string, runtimeCtx *core.RuntimeContext) *gin.Engine {
killChannel := make(map[string](chan bool))
clientPointer := make(map[string]*whatsmeow.Client)
loggerWrapper := logger_wrapper.NewLoggerManager(config)
var rabbitmqProducer producer_interfaces.Producer
if conn != nil {
logger.LogInfo("RabbitMQ enabled")
rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer(
conn,
config.AmqpGlobalEnabled,
config.AmqpGlobalEvents,
config.AmqpSpecificEvents,
config.AmqpUrl,
loggerWrapper,
)
} else {
// Even if initial connection failed, pass the URL so reconnection can work
rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer(
nil,
config.AmqpGlobalEnabled,
config.AmqpGlobalEvents,
config.AmqpSpecificEvents,
config.AmqpUrl, // Keep the URL for reconnection attempts
loggerWrapper,
)
}
var natsProducer producer_interfaces.Producer
if config.NatsUrl != "" {
logger.LogInfo("NATS enabled")
natsProducer = nats_producer.NewNatsProducer(
config.NatsUrl,
config.NatsGlobalEnabled,
config.NatsGlobalEvents,
loggerWrapper,
)
} else {
natsProducer = nats_producer.NewNatsProducer(
"",
false,
nil,
loggerWrapper,
)
}
webhookProducer := webhook_producer.NewWebhookProducer(config.WebhookUrl, loggerWrapper)
websocketProducer := websocket_producer.NewWebsocketProducer(loggerWrapper)
// Cria filas globais se o RabbitMQ global estiver habilitado
if config.AmqpGlobalEnabled && conn != nil {
logger.LogInfo("Creating global RabbitMQ queues...")
if err := rabbitmqProducer.CreateGlobalQueues(); err != nil {
logger.LogError("Failed to create global RabbitMQ queues: %v", err)
} else {
logger.LogInfo("Global RabbitMQ queues created successfully")
}
}
var mediaStorage storage_interfaces.MediaStorage
var err error
if config.MinioEnabled {
mediaStorage, err = minio_storage.NewMinioMediaStorage(
config.MinioEndpoint,
config.MinioAccessKey,
config.MinioSecretKey,
config.MinioBucket,
config.MinioRegion,
config.MinioUseSSL,
)
if err != nil {
log.Fatal(err)
}
}
instanceRepository := instance_repository.NewInstanceRepository(db)
messageRepository := message_repository.NewMessageRepository(db)
labelRepository := label_repository.NewLabelRepository(db)
whatsmeowService := whatsmeow_service.NewWhatsmeowService(
instanceRepository,
authDB,
message_repository.NewMessageRepository(db),
labelRepository,
config,
killChannel,
clientPointer,
rabbitmqProducer,
webhookProducer,
websocketProducer,
sqliteDB,
exPath,
mediaStorage,
natsProducer,
loggerWrapper,
)
instanceService := instance_service.NewInstanceService(
instanceRepository,
killChannel,
clientPointer,
whatsmeowService,
config,
loggerWrapper,
)
sendMessageService := send_service.NewSendService(clientPointer, whatsmeowService, config, loggerWrapper)
userService := user_service.NewUserService(clientPointer, whatsmeowService, loggerWrapper)
messageService := message_service.NewMessageService(clientPointer, messageRepository, whatsmeowService, loggerWrapper)
chatService := chat_service.NewChatService(clientPointer, whatsmeowService, loggerWrapper)
groupService := group_service.NewGroupService(clientPointer, whatsmeowService, loggerWrapper)
callService := call_service.NewCallService(clientPointer, whatsmeowService, loggerWrapper)
communityService := community_service.NewCommunityService(clientPointer, whatsmeowService, loggerWrapper)
labelService := label_service.NewLabelService(clientPointer, whatsmeowService, labelRepository, loggerWrapper)
newsletterService := newsletter_service.NewNewsletterService(clientPointer, whatsmeowService, loggerWrapper)
// NOVO: PollHandler usando PollService já inicializado no whatsmeowService (evita dupla inicialização)
pollHandler := poll_handler.NewPollHandler(whatsmeowService.GetPollService(), loggerWrapper)
telemetry := telemetry.NewTelemetryService(config.TelemetryEnabled)
r := gin.Default()
// CORS middleware — must be before everything else
r.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Cache-Control, X-Requested-With, apikey, ApiKey")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
return
}
c.Next()
})
r.Use(telemetry.TelemetryMiddleware())
r.Use(core.GateMiddleware(runtimeCtx))
// License routes (always accessible, even without license)
core.LicenseRoutes(r, runtimeCtx)
routes.NewRouter(
auth_middleware.NewMiddleware(config, instanceService),
instance_handler.NewInstanceHandler(instanceService, config),
user_handler.NewUserHandler(userService),
send_handler.NewSendHandler(sendMessageService),
message_handler.NewMessageHandler(messageService),
chat_handler.NewChatHandler(chatService),
group_handler.NewGroupHandler(groupService),
call_handler.NewCallHandler(callService),
community_handler.NewCommunityHandler(communityService),
label_handler.NewLabelHandler(labelService),
newsletter_handler.NewNewsletterHandler(newsletterService),
pollHandler,
server_handler.NewServerHandler(),
).AssignRoutes(r)
if config.ConnectOnStartup {
go whatsmeowService.ConnectOnStartup(config.ClientName)
}
// @Summary WebSocket Connection
// @Description Connect to the WebSocket
// @Tags WebSocket
// @Param token query string true "Global API Key"
// @Param instanceId query string true "Instance ID"
// @Success 101 {string} string "Switching Protocols"
// @Failure 401 {object} gin.H "Unauthorized"
// @Router /ws [get]
r.GET("/ws", func(c *gin.Context) {
token := c.Query("token")
instanceId := c.Query("instanceId")
if token != config.GlobalApiKey {
logger.LogError("Token inválido: %s", token)
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido"})
return
}
websocket_producer.ServeWs(c.Writer, c.Request, instanceId, websocketProducer)
})
return r
}
func migrate(db *gorm.DB) {
err := db.AutoMigrate(&instance_model.Instance{}, &message_model.Message{}, &label_model.Label{})
if err != nil {
log.Fatal(err)
}
}
func initAuthDB(config *config.Config) (*sql.DB, string, error) {
if config.PostgresAuthDB != "" {
return nil, "", nil
}
ex, err := os.Executable()
if err != nil {
panic(err)
}
exPath := filepath.Dir(ex)
dbDirectory := exPath + "/dbdata"
_, err = os.Stat(dbDirectory)
if os.IsNotExist(err) {
errDir := os.MkdirAll(dbDirectory, 0751)
if errDir != nil {
panic("Could not create dbdata directory")
}
}
db, err := sql.Open("sqlite", exPath+"/dbdata/users.db?_pragma=foreign_keys(1)&_busy_timeout=3000")
if err != nil {
return nil, "", err
}
return db, exPath, nil
}
func initPostgresAuthDB(config *config.Config) (*sql.DB, error) {
if config.PostgresAuthDB == "" {
return nil, nil
}
if err := config.EnsureDBExists(config.PostgresAuthDB); err != nil {
logger.LogWarn("Auto-setup auth DB failed (will try connecting anyway): %v", err)
}
db, err := sql.Open("postgres", config.PostgresAuthDB)
if err != nil {
return nil, fmt.Errorf("erro ao conectar ao banco AUTH PostgreSQL: %v", err)
}
// Configurar pool de conexões para evitar conexões ociosas não fechadas
db.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente
db.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool
db.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts
db.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto
err = db.Ping()
if err != nil {
return nil, fmt.Errorf("erro ao pingar banco AUTH PostgreSQL: %v", err)
}
logger.LogInfo("Conectado ao banco AUTH PostgreSQL com pool configurado")
return db, nil
}
// @title Evolution GO
// @version 1.0
// @description Evolution GO - whatsmeow
func main() {
flag.Parse()
if *devMode {
err := godotenv.Load(".env")
if err != nil {
log.Fatal(err)
}
}
cfg := config.Load()
logger.LogInfo("Starting Evolution GO version %s", version)
startTime := time.Now()
db, err := cfg.CreateUsersDB()
if err != nil {
log.Fatal(err)
}
// Inicializar PostgreSQL AUTH
authDB, err := initPostgresAuthDB(cfg)
if err != nil {
log.Fatal(err)
}
if authDB != nil {
defer authDB.Close()
}
// Manter inicialização do SQLite
sqliteDB, exPath, err := initAuthDB(cfg)
if err != nil {
log.Fatal(err)
}
if sqliteDB != nil {
defer sqliteDB.Close()
}
migrate(db)
// Initialize core DB + license runtime
core.SetDB(db)
if err := core.MigrateDB(); err != nil {
log.Fatal("Failed to migrate runtime_configs: ", err)
}
tier := "evolution-go"
runtimeCtx := core.InitializeRuntime(tier, version, cfg.GlobalApiKey)
var conn *amqp.Connection
if cfg.AmqpUrl != "" {
logger.LogInfo("Attempting to connect to RabbitMQ...")
// Create connection with heartbeat to prevent timeouts
amqpConfig := amqp.Config{
Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds
Locale: "en_US",
}
conn, err = amqp.DialConfig(cfg.AmqpUrl, amqpConfig)
if err != nil {
logger.LogError("Failed to connect to RabbitMQ, err: %v", err)
logger.LogInfo("RabbitMQ producer will be created with reconnection capability")
} else {
logger.LogInfo("Successfully connected to RabbitMQ with heartbeat enabled")
defer func(conn *amqp.Connection) {
err := conn.Close()
if err != nil {
logger.LogError("Failed to close RabbitMQ connection, err: %v", err)
}
}(conn)
}
} else {
logger.LogInfo("RabbitMQ URL not configured, skipping RabbitMQ connection")
}
r := setupRouter(db, authDB, sqliteDB, cfg, conn, exPath, runtimeCtx)
// Graceful shutdown with heartbeat
heartbeatCtx, heartbeatCancel := context.WithCancel(context.Background())
defer heartbeatCancel()
core.StartHeartbeat(heartbeatCtx, runtimeCtx, startTime)
srv := &http.Server{
Addr: ":" + os.Getenv("SERVER_PORT"),
Handler: r,
}
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
go func() {
logger.LogInfo("Iniciando servidor na porta %s", os.Getenv("SERVER_PORT"))
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("server error: %v", err)
}
}()
<-quit
logger.LogInfo("[SHUTDOWN] Signal received, shutting down...")
// Stop heartbeat loop
heartbeatCancel()
core.Shutdown(runtimeCtx)
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownCancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.LogError("[SHUTDOWN] Server forced to shutdown: %v", err)
}
logger.LogInfo("[SHUTDOWN] Server exited")
}