release: v0.6.1
This commit is contained in:
commit
877eef7f07
118 files changed
+46315
No files matched your search
@@ -0,0 +1,644 @@
|
||||
package instance_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
config "github.com/EvolutionAPI/evolution-go/pkg/config"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
|
||||
)
|
||||
|
||||
type InstanceHandler interface {
|
||||
Create(ctx *gin.Context)
|
||||
Connect(ctx *gin.Context)
|
||||
Reconnect(ctx *gin.Context)
|
||||
Disconnect(ctx *gin.Context)
|
||||
Logout(ctx *gin.Context)
|
||||
Delete(ctx *gin.Context)
|
||||
Status(ctx *gin.Context)
|
||||
Qr(ctx *gin.Context)
|
||||
All(ctx *gin.Context)
|
||||
Info(ctx *gin.Context)
|
||||
Pair(ctx *gin.Context)
|
||||
SetProxy(ctx *gin.Context)
|
||||
DeleteProxy(ctx *gin.Context)
|
||||
ForceReconnect(ctx *gin.Context)
|
||||
GetLogs(ctx *gin.Context)
|
||||
GetAdvancedSettings(ctx *gin.Context)
|
||||
UpdateAdvancedSettings(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type instanceHandler struct {
|
||||
config *config.Config
|
||||
instanceService instance_service.InstanceService
|
||||
}
|
||||
|
||||
// Create a new instance
|
||||
// @Summary Create a new instance
|
||||
// @Description Creates a new instance with the provided data including optional advanced settings
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.CreateStruct true "Instance data with optional advanced settings"
|
||||
// @Success 200 {object} gin.H "Instance created successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/create [post]
|
||||
func (i *instanceHandler) Create(ctx *gin.Context) {
|
||||
var data *instance_service.CreateStruct
|
||||
err := ctx.ShouldBindJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Token == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "token is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy != nil {
|
||||
if data.Proxy.Port == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy port is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Password == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy password is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Username == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy username is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Host == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy host is required"})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if i.config.ProxyHost != "" && i.config.ProxyPort != "" && i.config.ProxyUsername != "" && i.config.ProxyPassword != "" {
|
||||
data.Proxy = &instance_service.ProxyConfig{
|
||||
Host: i.config.ProxyHost,
|
||||
Port: i.config.ProxyPort,
|
||||
Username: i.config.ProxyUsername,
|
||||
Password: i.config.ProxyPassword,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createdInstance, err := i.instanceService.Create(data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": createdInstance})
|
||||
}
|
||||
|
||||
// Connect to instance
|
||||
// @Summary Connect to instance
|
||||
// @Description Connect to instance with the provided data
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.ConnectStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Instance connected successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/connect [post]
|
||||
func (i *instanceHandler) Connect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.ConnectStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
instance, jid, eventString, err := i.instanceService.Connect(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", instance)
|
||||
|
||||
responseData := gin.H{
|
||||
"jid": jid,
|
||||
"webhookUrl": instance.Webhook,
|
||||
"eventString": eventString,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Reconnect to instance
|
||||
// @Summary Reconnect to instance
|
||||
// @Description Reconnect to instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance reconnected successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/reconnect [post]
|
||||
func (i *instanceHandler) Reconnect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.Reconnect(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Disconnect from instance
|
||||
// @Summary Disconnect from instance
|
||||
// @Description Disconnect from instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance disconnected successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/disconnect [post]
|
||||
func (i *instanceHandler) Disconnect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
updateInstance, err := i.instanceService.Disconnect(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", updateInstance)
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Logout from instance
|
||||
// @Summary Logout from instance
|
||||
// @Description Logout from instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance logged out successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/logout [delete]
|
||||
func (i *instanceHandler) Logout(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
updateInstance, err := i.instanceService.Logout(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", updateInstance)
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Get instance status
|
||||
// @Summary Get instance status
|
||||
// @Description Get instance status
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance status"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/status [get]
|
||||
func (i *instanceHandler) Status(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
status, err := i.instanceService.Status(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": status})
|
||||
}
|
||||
|
||||
// Get instance QR code
|
||||
// @Summary Get instance QR code
|
||||
// @Description Get instance QR code
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance QR code"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/qr [get]
|
||||
func (i *instanceHandler) Qr(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
qrcode, err := i.instanceService.GetQr(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": qrcode})
|
||||
}
|
||||
|
||||
// Request pairing code
|
||||
// @Summary Request pairing code
|
||||
// @Description Request pairing code
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.PairStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Pairing code"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/pair [post]
|
||||
func (i *instanceHandler) Pair(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.PairStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Phone == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone is required"})
|
||||
return
|
||||
}
|
||||
|
||||
pairingCode, err := i.instanceService.Pair(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": pairingCode})
|
||||
}
|
||||
|
||||
// Get all instances
|
||||
// @Summary Get all instances
|
||||
// @Description Get all instances
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "All instances"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/all [get]
|
||||
func (i *instanceHandler) All(ctx *gin.Context) {
|
||||
instances, err := i.instanceService.GetAll()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instances})
|
||||
}
|
||||
|
||||
// Get instance
|
||||
// @Summary Get instance
|
||||
// @Description Get instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Success 200 {object} gin.H "Instance"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/get/{instanceId} [get]
|
||||
func (i *instanceHandler) Info(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
instance, err := i.instanceService.Info(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instance})
|
||||
}
|
||||
|
||||
// Delete instance
|
||||
// @Summary Delete instance
|
||||
// @Description Delete instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Success 200 {object} gin.H "Instance deleted successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/delete/{instanceId} [delete]
|
||||
func (i *instanceHandler) Delete(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.Delete(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Set proxy
|
||||
// @Summary Set proxy configuration
|
||||
// @Description Set proxy configuration for an instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance id"
|
||||
// @Param proxy body instance_service.SetProxyStruct true "Proxy configuration"
|
||||
// @Success 200 {object} gin.H "Proxy set successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/proxy/{instanceId} [post]
|
||||
func (i *instanceHandler) SetProxy(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.SetProxyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if data.Host == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "host is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Port == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "port is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = i.instanceService.SetProxyFromStruct(instanceId, data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"host": data.Host,
|
||||
"port": data.Port,
|
||||
"hasAuth": data.Username != "" && data.Password != "",
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Delete proxy
|
||||
// @Summary Delete proxy
|
||||
// @Description Delete proxy
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance id"
|
||||
// @Success 200 {object} gin.H "Proxy deleted successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/proxy/{instanceId} [delete]
|
||||
func (i *instanceHandler) DeleteProxy(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.RemoveProxy(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Force reconnect
|
||||
// @Summary Force reconnect
|
||||
// @Description Force reconnect
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Param instance body instance_service.ForceReconnectStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Instance force reconnected successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/forcereconnect/{instanceId} [post]
|
||||
func (i *instanceHandler) ForceReconnect(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.ForceReconnectStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var number string
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
number = data.Number
|
||||
|
||||
err = i.instanceService.ForceReconnect(instanceId, number)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
type GetLogsQuery struct {
|
||||
StartDate string `form:"start_date"`
|
||||
EndDate string `form:"end_date"`
|
||||
Level string `form:"level"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
func (h *instanceHandler) GetLogs(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
var query GetLogsQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Converte as datas
|
||||
startDate, err := time.Parse("2006-01-02", query.StartDate)
|
||||
if err != nil {
|
||||
startDate = time.Now().AddDate(0, 0, -7) // Default: 7 dias atrás
|
||||
}
|
||||
|
||||
endDate, err := time.Parse("2006-01-02", query.EndDate)
|
||||
if err != nil {
|
||||
endDate = time.Now()
|
||||
}
|
||||
|
||||
// Ajusta o endDate para o final do dia
|
||||
endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, time.UTC)
|
||||
|
||||
if query.Limit == 0 {
|
||||
query.Limit = 100 // Default: 100 registros
|
||||
}
|
||||
|
||||
logs, err := h.instanceService.GetLogs(instanceId, startDate, endDate, query.Level, query.Limit)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, logs)
|
||||
}
|
||||
|
||||
// GetAdvancedSettings retrieves advanced settings for an instance
|
||||
// @Summary Get advanced settings
|
||||
// @Description Get advanced settings for a specific instance
|
||||
// @Tags Instance
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance ID"
|
||||
// @Success 200 {object} instance_model.AdvancedSettings "Advanced settings retrieved successfully"
|
||||
// @Failure 400 {object} gin.H "Invalid instance ID"
|
||||
// @Failure 404 {object} gin.H "Instance not found"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/{instanceId}/advanced-settings [get]
|
||||
func (h *instanceHandler) GetAdvancedSettings(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
settings, err := h.instanceService.GetAdvancedSettings(instanceId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, settings)
|
||||
}
|
||||
|
||||
// UpdateAdvancedSettings updates advanced settings for an instance
|
||||
// @Summary Update advanced settings
|
||||
// @Description Update advanced settings for a specific instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance ID"
|
||||
// @Param settings body instance_model.AdvancedSettings true "Advanced settings data"
|
||||
// @Success 200 {object} gin.H "Advanced settings updated successfully"
|
||||
// @Failure 400 {object} gin.H "Invalid request data"
|
||||
// @Failure 404 {object} gin.H "Instance not found"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/{instanceId}/advanced-settings [put]
|
||||
func (h *instanceHandler) UpdateAdvancedSettings(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var settings instance_model.AdvancedSettings
|
||||
if err := c.ShouldBindJSON(&settings); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err := h.instanceService.UpdateAdvancedSettings(instanceId, &settings)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Advanced settings updated successfully",
|
||||
"settings": settings,
|
||||
})
|
||||
}
|
||||
|
||||
func NewInstanceHandler(instanceService instance_service.InstanceService, config *config.Config) InstanceHandler {
|
||||
return &instanceHandler{instanceService: instanceService, config: config}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package instance_model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Instance struct {
|
||||
Id string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
Name string `json:"name"`
|
||||
Token string `json:"token" gorm:"unique"`
|
||||
Webhook string `json:"webhook"`
|
||||
RabbitmqEnable string `json:"rabbitmqEnable"`
|
||||
WebSocketEnable string `json:"websocketEnable"`
|
||||
NatsEnable string `json:"natsEnable"`
|
||||
Jid string `json:"jid" gorm:"column:jid"`
|
||||
Qrcode string `json:"qrcode" gorm:"type:text"`
|
||||
Connected bool `json:"connected"`
|
||||
Expiration int64 `json:"expiration"`
|
||||
DisconnectReason string `json:"disconnect_reason"`
|
||||
Events string `json:"events"`
|
||||
OsName string `json:"os_name"`
|
||||
Proxy string `json:"proxy"`
|
||||
ClientName string `json:"client_name"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime"`
|
||||
|
||||
// Advanced Settings
|
||||
AlwaysOnline bool `json:"alwaysOnline" gorm:"default:false"`
|
||||
RejectCall bool `json:"rejectCall" gorm:"default:false"`
|
||||
MsgRejectCall string `json:"msgRejectCall" gorm:"default:''"`
|
||||
ReadMessages bool `json:"readMessages" gorm:"default:false"`
|
||||
IgnoreGroups bool `json:"ignoreGroups" gorm:"default:false"`
|
||||
IgnoreStatus bool `json:"ignoreStatus" gorm:"default:false"`
|
||||
}
|
||||
|
||||
// AdvancedSettings representa as configurações avançadas de uma instância
|
||||
type AdvancedSettings struct {
|
||||
AlwaysOnline bool `json:"alwaysOnline"`
|
||||
RejectCall bool `json:"rejectCall"`
|
||||
MsgRejectCall string `json:"msgRejectCall"`
|
||||
ReadMessages bool `json:"readMessages"`
|
||||
IgnoreGroups bool `json:"ignoreGroups"`
|
||||
IgnoreStatus bool `json:"ignoreStatus"`
|
||||
}
|
||||
|
||||
func (m *Instance) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
if m.Id == "" {
|
||||
m.Id = uuid.New().String()
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package instance_repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
|
||||
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
|
||||
|
||||
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
|
||||
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
|
||||
)
|
||||
|
||||
type InstanceRepository interface {
|
||||
Create(instance instance_model.Instance) (*instance_model.Instance, error)
|
||||
GetInstanceByID(instanceId string) (*instance_model.Instance, error)
|
||||
GetConnectedInstanceByID(instanceId string) (*instance_model.Instance, error)
|
||||
GetInstanceByToken(token string) (*instance_model.Instance, error)
|
||||
GetInstanceByName(name string) (*instance_model.Instance, error)
|
||||
Update(*instance_model.Instance) error
|
||||
UpdateConnected(userId string, status bool, disconnectReason string) error
|
||||
UpdateQrcode(userId string, qr string) error
|
||||
UpdateProxy(userId string, proxy string) error
|
||||
UpdateJid(userId string, jid string) error
|
||||
GetAllConnectedInstances() ([]*instance_model.Instance, error)
|
||||
GetAllConnectedInstancesByClientName(clientName string) ([]*instance_model.Instance, error)
|
||||
GetAll(clientName string) ([]*instance_model.Instance, error)
|
||||
Delete(instanceId string) error
|
||||
GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error)
|
||||
UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error
|
||||
}
|
||||
|
||||
type instanceRepository struct {
|
||||
db *gorm.DB
|
||||
labelRepo label_repository.LabelRepository
|
||||
messageRepo message_repository.MessageRepository
|
||||
}
|
||||
|
||||
func (i *instanceRepository) Create(instance instance_model.Instance) (*instance_model.Instance, error) {
|
||||
if err := i.db.Create(&instance).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetInstanceByToken(token string) (*instance_model.Instance, error) {
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("token = ?", token).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetInstanceByName(name string) (*instance_model.Instance, error) {
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("name = ?", name).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetInstanceByID(instanceId string) (*instance_model.Instance, error) {
|
||||
// Valida o formato do UUID
|
||||
if _, err := uuid.Parse(instanceId); err != nil {
|
||||
return nil, fmt.Errorf("invalid UUID format: %v", err)
|
||||
}
|
||||
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("id = ?", instanceId).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetConnectedInstanceByID(instanceId string) (*instance_model.Instance, error) {
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("id = ? AND connected = ?", instanceId, true).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) Update(instance *instance_model.Instance) error {
|
||||
err := i.db.Save(&instance).Error
|
||||
if err != nil {
|
||||
logger.LogError("Error updating instance in DB: %v", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateConnected(userId string, status bool, disconnectReason string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("connected", status).Update("disconnect_reason", disconnectReason).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateQrcode(userId string, qr string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("qrcode", qr).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateProxy(userId string, proxy string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("proxy", proxy).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateJid(userId string, jid string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("jid", jid).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAllConnectedInstances() ([]*instance_model.Instance, error) {
|
||||
var instances []*instance_model.Instance
|
||||
err := i.db.Where("connected = ?", true).Find(&instances).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAllConnectedInstancesByClientName(clientName string) ([]*instance_model.Instance, error) {
|
||||
var instances []*instance_model.Instance
|
||||
err := i.db.Where("connected = ? AND client_name = ?", true, clientName).Find(&instances).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAll(clientName string) ([]*instance_model.Instance, error) {
|
||||
var instances []*instance_model.Instance
|
||||
err := i.db.Where("client_name = ?", clientName).Find(&instances).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) Delete(instanceId string) error {
|
||||
return i.db.Transaction(func(tx *gorm.DB) error {
|
||||
// Deleta todas as labels associadas à instância
|
||||
if err := tx.Where("instance_id = ?", instanceId).Delete(&label_model.Label{}).Error; err != nil {
|
||||
return fmt.Errorf("erro ao deletar labels: %v", err)
|
||||
}
|
||||
|
||||
// Deleta todas as mensagens associadas à instância
|
||||
if err := tx.Where("source = ?", instanceId).Delete(&message_model.Message{}).Error; err != nil {
|
||||
return fmt.Errorf("erro ao deletar mensagens: %v", err)
|
||||
}
|
||||
|
||||
// Deleta a instância
|
||||
if err := tx.Where("id = ?", instanceId).Delete(&instance_model.Instance{}).Error; err != nil {
|
||||
return fmt.Errorf("erro ao deletar instância: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error) {
|
||||
// Valida o formato do UUID
|
||||
if _, err := uuid.Parse(instanceId); err != nil {
|
||||
return nil, fmt.Errorf("invalid UUID format: %v", err)
|
||||
}
|
||||
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Select("always_online, reject_call, msg_reject_call, read_messages, ignore_groups, ignore_status").
|
||||
Where("id = ?", instanceId).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
settings := &instance_model.AdvancedSettings{
|
||||
AlwaysOnline: instance.AlwaysOnline,
|
||||
RejectCall: instance.RejectCall,
|
||||
MsgRejectCall: instance.MsgRejectCall,
|
||||
ReadMessages: instance.ReadMessages,
|
||||
IgnoreGroups: instance.IgnoreGroups,
|
||||
IgnoreStatus: instance.IgnoreStatus,
|
||||
}
|
||||
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error {
|
||||
// Valida o formato do UUID
|
||||
if _, err := uuid.Parse(instanceId); err != nil {
|
||||
return fmt.Errorf("invalid UUID format: %v", err)
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{
|
||||
"always_online": settings.AlwaysOnline,
|
||||
"reject_call": settings.RejectCall,
|
||||
"msg_reject_call": settings.MsgRejectCall,
|
||||
"read_messages": settings.ReadMessages,
|
||||
"ignore_groups": settings.IgnoreGroups,
|
||||
"ignore_status": settings.IgnoreStatus,
|
||||
}
|
||||
|
||||
err := i.db.Model(&instance_model.Instance{}).Where("id = ?", instanceId).Updates(updates).Error
|
||||
if err != nil {
|
||||
logger.LogError("Error updating advanced settings in DB: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewInstanceRepository(db *gorm.DB) InstanceRepository {
|
||||
return &instanceRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,854 @@
|
||||
package instance_service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/config"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"
|
||||
event_types "github.com/EvolutionAPI/evolution-go/pkg/internal/event_types"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type InstanceService interface {
|
||||
Create(data *CreateStruct) (*instance_model.Instance, error)
|
||||
Connect(data *ConnectStruct, instance *instance_model.Instance) (*instance_model.Instance, string, string, error)
|
||||
Reconnect(instance *instance_model.Instance) error
|
||||
Disconnect(instance *instance_model.Instance) (*instance_model.Instance, error)
|
||||
Logout(instance *instance_model.Instance) (*instance_model.Instance, error)
|
||||
Status(instance *instance_model.Instance) (*StatusStruct, error)
|
||||
GetQr(instance *instance_model.Instance) (*QrcodeStruct, error)
|
||||
Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error)
|
||||
GetAll() ([]*instance_model.Instance, error)
|
||||
Info(instanceId string) (*instance_model.Instance, error)
|
||||
Delete(id string) error
|
||||
SetProxy(id string, proxyConfig *ProxyConfig) error
|
||||
SetProxyFromStruct(id string, data *SetProxyStruct) error
|
||||
RemoveProxy(id string) error
|
||||
ForceReconnect(instanceId string, number string) error
|
||||
GetInstanceByToken(token string) (*instance_model.Instance, error)
|
||||
GetLogs(instanceId string, startDate, endDate time.Time, level string, limit int) ([]logger_wrapper.LogEntry, error)
|
||||
GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error)
|
||||
UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error
|
||||
}
|
||||
|
||||
type instances struct {
|
||||
instanceRepository instance_repository.InstanceRepository
|
||||
config *config.Config
|
||||
killChannel map[string](chan bool)
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type ProxyConfig struct {
|
||||
Port string `json:"port"`
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
type CreateStruct struct {
|
||||
InstanceId string `json:"instanceId"`
|
||||
Name string `json:"name"`
|
||||
Token string `json:"token"`
|
||||
Proxy *ProxyConfig `json:"proxy"`
|
||||
AdvancedSettings *instance_model.AdvancedSettings `json:"advancedSettings"`
|
||||
}
|
||||
|
||||
type ConnectStruct struct {
|
||||
WebhookUrl string `json:"webhookUrl"`
|
||||
Subscribe []string `json:"subscribe"`
|
||||
Immediate bool `json:"immediate"`
|
||||
Phone string `json:"phone"`
|
||||
RabbitmqEnable string `json:"rabbitmqEnable"`
|
||||
WebSocketEnable string `json:"websocketEnable"`
|
||||
NatsEnable string `json:"natsEnable"`
|
||||
}
|
||||
|
||||
type StatusStruct struct {
|
||||
Connected bool
|
||||
LoggedIn bool
|
||||
myJid *types.JID
|
||||
Name string
|
||||
}
|
||||
|
||||
type QrcodeStruct struct {
|
||||
Qrcode string
|
||||
Code string
|
||||
}
|
||||
|
||||
type PairStruct struct {
|
||||
Subscribe []string `json:"subscribe"`
|
||||
Phone string `json:"phone"`
|
||||
}
|
||||
|
||||
type PairReturnStruct struct {
|
||||
PairingCode string
|
||||
}
|
||||
|
||||
type SetProxyStruct struct {
|
||||
Host string `json:"host" validate:"required"`
|
||||
Port string `json:"port" validate:"required"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type ForceReconnectStruct struct {
|
||||
Number string `json:"number"`
|
||||
}
|
||||
|
||||
func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
logger := i.loggerWrapper.GetLogger(instanceId)
|
||||
client := i.clientPointer[instanceId]
|
||||
logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
logger.LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := i.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
logger.LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = i.clientPointer[instanceId]
|
||||
logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
logger.LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
logger.LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
logger.LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (i instances) Create(data *CreateStruct) (*instance_model.Instance, error) {
|
||||
proxyJson, err := json.Marshal(data.Proxy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
findInstance, _ := i.instanceRepository.GetInstanceByName(data.Name)
|
||||
|
||||
if findInstance != nil {
|
||||
return nil, fmt.Errorf("instance already exists")
|
||||
}
|
||||
|
||||
instance := instance_model.Instance{
|
||||
Id: data.InstanceId,
|
||||
Name: data.Name,
|
||||
Token: data.Token,
|
||||
OsName: i.config.OsName,
|
||||
Proxy: string(proxyJson),
|
||||
Connected: false,
|
||||
ClientName: i.config.ClientName,
|
||||
}
|
||||
|
||||
// Set advanced settings if provided
|
||||
if data.AdvancedSettings != nil {
|
||||
instance.AlwaysOnline = data.AdvancedSettings.AlwaysOnline
|
||||
instance.RejectCall = data.AdvancedSettings.RejectCall
|
||||
instance.MsgRejectCall = data.AdvancedSettings.MsgRejectCall
|
||||
instance.ReadMessages = data.AdvancedSettings.ReadMessages
|
||||
instance.IgnoreGroups = data.AdvancedSettings.IgnoreGroups
|
||||
instance.IgnoreStatus = data.AdvancedSettings.IgnoreStatus
|
||||
}
|
||||
|
||||
createdInstance, err := i.instanceRepository.Create(instance)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return createdInstance, nil
|
||||
}
|
||||
|
||||
func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instance) (*instance_model.Instance, string, string, error) {
|
||||
var subscribedEvents []string
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Processing subscribe events: %v", instance.Id, data.Subscribe)
|
||||
|
||||
if len(data.Subscribe) == 0 {
|
||||
subscribedEvents = append(subscribedEvents, event_types.MESSAGE)
|
||||
} else if len(data.Subscribe) > 0 && data.Subscribe[0] == "ALL" {
|
||||
for _, event := range event_types.AllEventTypes {
|
||||
subscribedEvents = append(subscribedEvents, event)
|
||||
}
|
||||
} else {
|
||||
for _, arg := range data.Subscribe {
|
||||
if !event_types.IsEventType(arg) {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Message type discarded '%s'", instance.Id, arg)
|
||||
continue
|
||||
}
|
||||
subscribedEvents = append(subscribedEvents, arg)
|
||||
}
|
||||
}
|
||||
|
||||
eventString := strings.Join(subscribedEvents, ",")
|
||||
|
||||
instance.Events = eventString
|
||||
instance.Webhook = data.WebhookUrl
|
||||
instance.RabbitmqEnable = data.RabbitmqEnable
|
||||
instance.NatsEnable = data.NatsEnable
|
||||
instance.WebSocketEnable = data.WebSocketEnable
|
||||
|
||||
err := i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error updating instance: %s", instance.Id, err)
|
||||
return nil, "", "", err
|
||||
}
|
||||
|
||||
// Verifica se a instância já está rodando
|
||||
isInstanceRunning := i.clientPointer[instance.Id] != nil
|
||||
|
||||
// Sincroniza as configurações na instância em execução (se já estiver conectada)
|
||||
err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance not in runtime yet, will be updated when connected", instance.Id)
|
||||
isInstanceRunning = false
|
||||
} else {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance settings updated successfully in runtime", instance.Id)
|
||||
isInstanceRunning = true
|
||||
}
|
||||
|
||||
// Se a instância não estiver rodando, inicia uma nova
|
||||
if !isInstanceRunning {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
Subscriptions: subscribedEvents,
|
||||
Phone: data.Phone,
|
||||
IsProxy: false,
|
||||
}
|
||||
|
||||
if instance.Proxy != "" || i.config.ProxyHost != "" {
|
||||
var proxyConfig ProxyConfig
|
||||
err := json.Unmarshal([]byte(instance.Proxy), &proxyConfig)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmarshalling proxy config: %v", instance.Id, err)
|
||||
return nil, "", "", err
|
||||
}
|
||||
|
||||
if proxyConfig.Host != "" || i.config.ProxyHost != "" {
|
||||
clientData.IsProxy = true
|
||||
}
|
||||
}
|
||||
|
||||
go i.whatsmeowService.StartClient(clientData)
|
||||
} else {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance already running, settings updated without restarting client", instance.Id)
|
||||
}
|
||||
|
||||
// logger.LogInfo("Waiting 1 seconds")
|
||||
// time.Sleep(1000 * time.Millisecond)
|
||||
|
||||
// if i.clientPointer[instance.Id] != nil {
|
||||
// if !i.clientPointer[instance.Id].IsConnected() {
|
||||
// return instance, "", "", fmt.Errorf("failed to connect")
|
||||
// }
|
||||
// } else {
|
||||
// return instance, "", "", fmt.Errorf("failed to connect")
|
||||
// }
|
||||
|
||||
return instance, instance.Jid, eventString, nil
|
||||
}
|
||||
|
||||
func (i instances) Reconnect(instance *instance_model.Instance) error {
|
||||
_, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return i.whatsmeowService.ReconnectClient(instance.Id)
|
||||
}
|
||||
|
||||
func (i instances) Disconnect(instance *instance_model.Instance) (*instance_model.Instance, error) {
|
||||
client, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
if client.IsConnected() {
|
||||
if client.IsLoggedIn() {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
i.killChannel[instance.Id] <- true
|
||||
|
||||
instance.Events = ""
|
||||
|
||||
err := i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
return instance, nil
|
||||
}
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Ignoring disconnect as it was not connected", instance.Id)
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
func (i instances) Logout(instance *instance_model.Instance) (*instance_model.Instance, error) {
|
||||
client, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
if client.IsLoggedIn() && client.IsConnected() {
|
||||
err := client.Logout(context.Background())
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
instance.Connected = false
|
||||
err = i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
if client.IsConnected() {
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Ignoring logout as it was not connected", instance.Id)
|
||||
return instance, fmt.Errorf("ignoring logout as it was not connected")
|
||||
}
|
||||
|
||||
func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {
|
||||
client, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
isConnected := client.IsConnected()
|
||||
isLoggedIn := client.IsLoggedIn()
|
||||
|
||||
var myJid *types.JID
|
||||
var name string
|
||||
if isLoggedIn {
|
||||
myJid = client.Store.ID
|
||||
name = client.Store.PushName
|
||||
}
|
||||
|
||||
status := &StatusStruct{
|
||||
Connected: isConnected,
|
||||
LoggedIn: isLoggedIn,
|
||||
myJid: myJid,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {
|
||||
logger := i.loggerWrapper.GetLogger(instance.Id)
|
||||
client := i.clientPointer[instance.Id]
|
||||
|
||||
// Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente
|
||||
if client == nil || client.IsLoggedIn() {
|
||||
if client != nil && client.IsLoggedIn() {
|
||||
logger.LogInfo("[%s] Client is logged in, starting new instance for QR code", instance.Id)
|
||||
} else {
|
||||
logger.LogInfo("[%s] No client found, starting new instance for QR code", instance.Id)
|
||||
}
|
||||
|
||||
// Iniciar nova instância para gerar QR code
|
||||
err := i.whatsmeowService.StartInstance(instance.Id)
|
||||
if err != nil {
|
||||
logger.LogError("[%s] Failed to start instance: %v", instance.Id, err)
|
||||
return nil, fmt.Errorf("failed to start instance: %w", err)
|
||||
}
|
||||
|
||||
// Aguardar um pouco para o cliente iniciar e gerar QR code
|
||||
logger.LogInfo("[%s] Waiting for QR code generation...", instance.Id)
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Verificar novamente se há cliente
|
||||
client = i.clientPointer[instance.Id]
|
||||
if client != nil && client.IsLoggedIn() {
|
||||
return nil, fmt.Errorf("session already logged in")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
// Se o cliente existe mas não está conectado, pode estar aguardando QR code
|
||||
logger.LogInfo("[%s] Client exists but not connected, checking for existing QR code", instance.Id)
|
||||
}
|
||||
|
||||
// Buscar instância atualizada do banco para pegar o QR code mais recente
|
||||
instance, err := i.instanceRepository.GetInstanceByID(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
code := instance.Qrcode
|
||||
if code == "" {
|
||||
// Se não há QR code ainda, aguardar um pouco mais e tentar novamente
|
||||
logger.LogInfo("[%s] No QR code available yet, waiting a bit more...", instance.Id)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
instance, err = i.instanceRepository.GetInstanceByID(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
code = instance.Qrcode
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("no QR code available. Please wait a moment and try again")
|
||||
}
|
||||
}
|
||||
|
||||
parts := strings.Split(code, "|")
|
||||
if len(parts) < 2 {
|
||||
return nil, fmt.Errorf("invalid QR code format")
|
||||
}
|
||||
|
||||
qr := &QrcodeStruct{
|
||||
Qrcode: parts[0],
|
||||
Code: parts[1],
|
||||
}
|
||||
|
||||
return qr, nil
|
||||
}
|
||||
|
||||
func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {
|
||||
code, err := i.clientPointer[instance.Id].PairPhone(context.Background(), data.Phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] something went wrong calling pair phone", instance.Id)
|
||||
}
|
||||
|
||||
return &PairReturnStruct{PairingCode: code}, nil
|
||||
}
|
||||
|
||||
func (i instances) GetAll() ([]*instance_model.Instance, error) {
|
||||
instances, err := i.instanceRepository.GetAll(i.config.ClientName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, instance := range instances {
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
instance.Connected = false
|
||||
}
|
||||
|
||||
instance.Proxy = ""
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i instances) Info(instanceId string) (*instance_model.Instance, error) {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(instanceId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Atualiza o status connected com base no estado real do cliente
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
instance.Connected = false
|
||||
}
|
||||
|
||||
instance.Proxy = ""
|
||||
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
func (i instances) Delete(id string) error {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() {
|
||||
if i.clientPointer[instance.Id].IsLoggedIn() {
|
||||
i.clientPointer[instance.Id].Logout(context.Background())
|
||||
}
|
||||
i.clientPointer[instance.Id].Disconnect()
|
||||
}
|
||||
|
||||
// Limpar todos os recursos da instância antes de deletar
|
||||
delete(i.clientPointer, instance.Id)
|
||||
if i.killChannel[instance.Id] != nil {
|
||||
close(i.killChannel[instance.Id])
|
||||
delete(i.killChannel, instance.Id)
|
||||
}
|
||||
|
||||
// Limpar cache via whatsmeow service
|
||||
err = i.whatsmeowService.ClearInstanceCache(instance.Id, instance.Token)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to clear instance cache: %v", instance.Id, err)
|
||||
}
|
||||
|
||||
err = i.instanceRepository.Delete(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) SetProxy(id string, proxyConfig *ProxyConfig) error {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Validate proxy configuration
|
||||
if proxyConfig == nil {
|
||||
return fmt.Errorf("proxy configuration cannot be nil")
|
||||
}
|
||||
|
||||
if proxyConfig.Host == "" {
|
||||
return fmt.Errorf("proxy host is required")
|
||||
}
|
||||
|
||||
if proxyConfig.Port == "" {
|
||||
return fmt.Errorf("proxy port is required")
|
||||
}
|
||||
|
||||
// Convert proxy config to JSON
|
||||
proxyJSON, err := json.Marshal(proxyConfig)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(id).LogError("[%s] Failed to marshal proxy config: %v", id, err)
|
||||
return fmt.Errorf("failed to marshal proxy configuration: %v", err)
|
||||
}
|
||||
|
||||
instance.Proxy = string(proxyJSON)
|
||||
|
||||
// Update instance in database
|
||||
err = i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(id).LogError("[%s] Failed to update instance with proxy: %v", id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration updated: %s:%s", id, proxyConfig.Host, proxyConfig.Port)
|
||||
|
||||
// Reconnect to apply proxy changes
|
||||
go i.Reconnect(instance)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) SetProxyFromStruct(id string, data *SetProxyStruct) error {
|
||||
if data == nil {
|
||||
return fmt.Errorf("proxy data cannot be nil")
|
||||
}
|
||||
|
||||
proxyConfig := &ProxyConfig{
|
||||
Host: data.Host,
|
||||
Port: data.Port,
|
||||
Username: data.Username,
|
||||
Password: data.Password,
|
||||
}
|
||||
|
||||
return i.SetProxy(id, proxyConfig)
|
||||
}
|
||||
|
||||
func (i instances) RemoveProxy(id string) error {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
instance.Proxy = ""
|
||||
|
||||
err = i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration removed", id)
|
||||
|
||||
go i.Reconnect(instance)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) ForceReconnect(instanceId string, number string) error {
|
||||
if i.clientPointer[instanceId].IsConnected() && i.clientPointer[instanceId].IsLoggedIn() {
|
||||
return fmt.Errorf("client already connected")
|
||||
}
|
||||
|
||||
err := i.whatsmeowService.ForceUpdateJid(instanceId, number)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
instance, err := i.instanceRepository.GetInstanceByID(instanceId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
subscribedEvents := strings.Split(instance.Events, ",")
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
Subscriptions: subscribedEvents,
|
||||
Phone: "",
|
||||
IsProxy: false,
|
||||
}
|
||||
|
||||
if instance.Proxy != "" || i.config.ProxyHost != "" {
|
||||
var proxyConfig ProxyConfig
|
||||
err := json.Unmarshal([]byte(instance.Proxy), &proxyConfig)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmarshalling proxy config: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if proxyConfig.Host != "" || i.config.ProxyHost != "" {
|
||||
clientData.IsProxy = true
|
||||
}
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
client := i.clientPointer[instance.Id]
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
}
|
||||
|
||||
go i.whatsmeowService.StartClient(clientData)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
if !i.clientPointer[instance.Id].IsConnected() {
|
||||
return fmt.Errorf("failed to connect")
|
||||
}
|
||||
|
||||
if !i.clientPointer[instance.Id].IsLoggedIn() {
|
||||
return fmt.Errorf("failed to login")
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("failed to connect")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) GetInstanceByToken(token string) (*instance_model.Instance, error) {
|
||||
return i.instanceRepository.GetInstanceByToken(token)
|
||||
}
|
||||
|
||||
func (i instances) GetLogs(instanceId string, startDate, endDate time.Time, level string, limit int) ([]logger_wrapper.LogEntry, error) {
|
||||
// Inicializa o slice vazio para garantir que nunca retorne null
|
||||
logs := make([]logger_wrapper.LogEntry, 0)
|
||||
|
||||
// Define valores padrão
|
||||
if limit <= 0 {
|
||||
limit = 100 // Limite padrão de 100 registros
|
||||
}
|
||||
|
||||
// Se não foi fornecida data inicial, usa 7 dias atrás
|
||||
if startDate.IsZero() {
|
||||
startDate = time.Now().AddDate(0, 0, -7)
|
||||
}
|
||||
|
||||
// Se não foi fornecida data final, usa data atual
|
||||
if endDate.IsZero() {
|
||||
endDate = time.Now()
|
||||
}
|
||||
|
||||
// Ajusta as datas para início e fim do dia
|
||||
startDate = time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, time.UTC)
|
||||
endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, time.UTC)
|
||||
|
||||
// Garante que a data inicial não seja posterior à data final
|
||||
if startDate.After(endDate) {
|
||||
return logs, fmt.Errorf("data inicial não pode ser posterior à data final")
|
||||
}
|
||||
|
||||
// Níveis de log válidos
|
||||
validLevels := map[string]bool{
|
||||
"INFO": true,
|
||||
"ERROR": true,
|
||||
"WARN": true,
|
||||
"DEBUG": true,
|
||||
}
|
||||
|
||||
var levelArray []string
|
||||
if level == "" {
|
||||
// Se nenhum nível foi especificado, usa todos
|
||||
levelArray = []string{"INFO", "ERROR", "WARN", "DEBUG"}
|
||||
} else {
|
||||
// Divide e normaliza os níveis fornecidos
|
||||
for _, l := range strings.Split(level, ",") {
|
||||
l = strings.TrimSpace(strings.ToUpper(l))
|
||||
if !validLevels[l] {
|
||||
return logs, fmt.Errorf("nível de log inválido: %s", l)
|
||||
}
|
||||
levelArray = append(levelArray, l)
|
||||
}
|
||||
}
|
||||
|
||||
// Lê os logs do arquivo
|
||||
logPath := filepath.Join(i.config.LogDirectory, instanceId, "instance.log")
|
||||
file, err := os.Open(logPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return logs, nil // Retorna array vazio se arquivo não existir
|
||||
}
|
||||
return logs, fmt.Errorf("erro ao abrir arquivo de log: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
|
||||
// Aumenta o buffer do scanner para lidar com linhas grandes
|
||||
const maxCapacity = 1024 * 1024 // 1MB
|
||||
buf := make([]byte, maxCapacity)
|
||||
scanner.Buffer(buf, maxCapacity)
|
||||
|
||||
for scanner.Scan() {
|
||||
var entry logger_wrapper.LogEntry
|
||||
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
|
||||
continue // Ignora linhas inválidas
|
||||
}
|
||||
|
||||
// Ajusta o timestamp da entrada para UTC para comparação correta
|
||||
entry.Timestamp = entry.Timestamp.UTC()
|
||||
|
||||
// Aplica os filtros
|
||||
if entry.Timestamp.Before(startDate) || entry.Timestamp.After(endDate) {
|
||||
continue
|
||||
}
|
||||
|
||||
if !slices.Contains(levelArray, entry.Level) {
|
||||
continue
|
||||
}
|
||||
|
||||
logs = append(logs, entry)
|
||||
|
||||
// Verifica o limite
|
||||
if len(logs) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return logs, fmt.Errorf("erro ao ler arquivo de log: %v", err)
|
||||
}
|
||||
|
||||
// Ordena os logs por timestamp em ordem decrescente
|
||||
sort.Slice(logs, func(i, j int) bool {
|
||||
return logs[i].Timestamp.After(logs[j].Timestamp)
|
||||
})
|
||||
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
func (i instances) GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error) {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Getting advanced settings", instanceId)
|
||||
|
||||
settings, err := i.instanceRepository.GetAdvancedSettings(instanceId)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting advanced settings: %v", instanceId, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Updating advanced settings", instanceId)
|
||||
|
||||
err := i.instanceRepository.UpdateAdvancedSettings(instanceId, settings)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error updating advanced settings: %v", instanceId, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Sincroniza as configurações na instância em execução
|
||||
err = i.whatsmeowService.UpdateInstanceAdvancedSettings(instanceId)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Error syncing advanced settings to runtime: %v", instanceId, err)
|
||||
// Não falha a operação, apenas loga o warning
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Advanced settings updated successfully", instanceId)
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewInstanceService(
|
||||
instanceRepository instance_repository.InstanceRepository,
|
||||
killChannel map[string](chan bool),
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
config *config.Config,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) InstanceService {
|
||||
return &instances{
|
||||
instanceRepository: instanceRepository,
|
||||
killChannel: killChannel,
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
config: config,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user