release: v0.6.1

This commit is contained in:
Davidson Gomes committed 2026-03-25 12:40:16 -03:00
commit 877eef7f07
118 files changed
+46315

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
package call_handler
import (
"net/http"
call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
type CallHandler interface {
RejectCall(ctx *gin.Context)
}
type callHandler struct {
callService call_service.CallService
}
// Reject call
// @Summary Reject call
// @Description Reject call
// @Tags Call
// @Accept json
// @Produce json
// @Param message body call_service.RejectCallStruct true "Call data"
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /call/reject [post]
func (g *callHandler) RejectCall(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 *call_service.RejectCallStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err = g.callService.RejectCall(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
func NewCallHandler(
callService call_service.CallService,
) CallHandler {
return &callHandler{
callService: callService,
}
}
+95
View File
@@ -0,0 +1,95 @@
package call_service
import (
"context"
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"github.com/gomessguii/logger"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
)
type CallService interface {
RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error
}
type callService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type RejectCallStruct struct {
CallCreator types.JID `json:"callCreator"`
CallID string `json:"callId"`
}
func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := c.whatsmeowService.StartInstance(instanceId)
if err != nil {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
c.loggerWrapper.GetLogger(instanceId).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() {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return err
}
err = client.RejectCall(context.Background(), data.CallCreator, data.CallID)
if err != nil {
logger.LogError("[%s] error reject call: %v", instance.Id, err)
return err
}
return nil
}
func NewCallService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) CallService {
return &callService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}
+337
View File
@@ -0,0 +1,337 @@
package chat_handler
import (
"net/http"
chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
type ChatHandler interface {
ChatPin(ctx *gin.Context)
ChatUnpin(ctx *gin.Context)
ChatArchive(ctx *gin.Context)
ChatUnarchive(ctx *gin.Context)
ChatMute(ctx *gin.Context)
ChatUnmute(ctx *gin.Context)
HistorySyncRequest(ctx *gin.Context)
}
type chatHandler struct {
chatService chat_service.ChatService
}
// Pin a chat
// @Summary Pin a chat
// @Description Pin a chat
// @Tags Chat
// @Accept json
// @Produce json
// @Param message body chat_service.BodyStruct true "Chat"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/pin [post]
func (c *chatHandler) ChatPin(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 *chat_service.BodyStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
ts, err := c.chatService.ChatPin(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// Unpin a chat
// @Summary Unpin a chat
// @Description Unpin a chat
// @Tags Chat
// @Accept json
// @Produce json
// @Param message body chat_service.BodyStruct true "Chat"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/unpin [post]
func (c *chatHandler) ChatUnpin(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 *chat_service.BodyStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
ts, err := c.chatService.ChatUnpin(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// Archive a chat
// @Summary Archive a chat
// @Description Archive a chat
// @Tags Chat
// @Accept json
// @Produce json
// @Param message body chat_service.BodyStruct true "Chat"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/archive [post]
func (c *chatHandler) ChatArchive(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 *chat_service.BodyStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
ts, err := c.chatService.ChatArchive(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// Unarchive a chat
// @Summary Unarchive a chat
// @Description Unarchive a chat
// @Tags Chat
// @Accept json
// @Produce json
// @Param message body chat_service.BodyStruct true "Chat"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/unarchive [post]
func (c *chatHandler) ChatUnarchive(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 *chat_service.BodyStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
ts, err := c.chatService.ChatUnarchive(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// Mute a chat
// @Summary Mute a chat
// @Description Mute a chat
// @Tags Chat
// @Accept json
// @Produce json
// @Param message body chat_service.BodyStruct true "Chat"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/mute [post]
func (c *chatHandler) ChatMute(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 *chat_service.BodyStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
ts, err := c.chatService.ChatMute(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// Unmute a chat
// @Summary Unmute a chat
// @Description Unmute a chat
// @Tags Chat
// @Accept json
// @Produce json
// @Param message body chat_service.BodyStruct true "Chat"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/unmute [post]
func (c *chatHandler) ChatUnmute(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 *chat_service.BodyStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
ts, err := c.chatService.ChatUnmute(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// HistorySyncRequest a chat
// @Summary HistorySyncRequest a chat
// @Description HistorySyncRequest a chat
// @Tags Chat
// @Accept json
// @Produce json
// @Param message body chat_service.HistorySyncRequestStruct true "Chat"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/history-sync-request [post]
func (c *chatHandler) HistorySyncRequest(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 *chat_service.HistorySyncRequestStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
resp, err := c.chatService.HistorySyncRequest(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
func NewChatHandler(
chatService chat_service.ChatService,
) ChatHandler {
return &chatHandler{
chatService: chatService,
}
}
+256
View File
@@ -0,0 +1,256 @@
package chat_service
import (
"context"
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/types"
)
type ChatService interface {
ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error)
HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error)
}
type chatService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type BodyStruct struct {
Chat string `json:"chat"`
}
type HistorySyncRequestStruct struct {
MessageInfo *types.MessageInfo `json:"messageInfo"`
Count int `json:"count"`
}
func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := c.whatsmeowService.StartInstance(instanceId)
if err != nil {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
c.loggerWrapper.GetLogger(instanceId).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() {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (c *chatService) ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, true))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error pin chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, false))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unpin chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, true, time.Time{}, nil))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error archive chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, false, time.Time{}, nil))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unarchive chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, true, 1*time.Hour))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, false, 0*time.Hour))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmute chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{
Chat: data.MessageInfo.Chat,
IsFromMe: data.MessageInfo.IsFromMe,
IsGroup: data.MessageInfo.IsGroup,
},
ID: data.MessageInfo.ID,
Timestamp: data.MessageInfo.Timestamp,
}
histRequest := client.BuildHistorySyncRequest(&messageInfo, data.Count)
res, err := client.SendMessage(context.Background(), messageInfo.Chat, histRequest, whatsmeow.SendRequestExtra{Peer: true})
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error history sync request: %v", instance.Id, err)
return nil, err
}
return &res, nil
}
func NewChatService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) ChatService {
return &chatService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}
+160
View File
@@ -0,0 +1,160 @@
package community_handler
import (
"net/http"
community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
type CommunityHandler interface {
CreateCommunity(ctx *gin.Context)
CommunityAdd(ctx *gin.Context)
CommunityRemove(ctx *gin.Context)
}
type communityHandler struct {
communityService community_service.CommunityService
}
// Create community
// @Summary Create community
// @Description Create community
// @Tags Community
// @Accept json
// @Produce json
// @Param message body community_service.CreateCommunityStruct true "Community data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /community/create [post]
func (c *communityHandler) CreateCommunity(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 *community_service.CreateCommunityStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.CommunityName == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community name is required"})
return
}
community, err := c.communityService.CreateCommunity(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": community})
}
// Add participant to community
// @Summary Add participant to community
// @Description Add participant to community
// @Tags Community
// @Accept json
// @Produce json
// @Param message body community_service.AddParticipantStruct true "Participant data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /community/add [post]
func (c *communityHandler) CommunityAdd(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 *community_service.AddParticipantStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.CommunityJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})
return
}
if len(data.GroupJID) == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})
return
}
resp, err := c.communityService.CommunityAdd(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Remove participant from community
// @Summary Remove participant from community
// @Description Remove participant from community
// @Tags Community
// @Accept json
// @Produce json
// @Param message body community_service.AddParticipantStruct true "Participant data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /community/remove [post]
func (c *communityHandler) CommunityRemove(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 *community_service.AddParticipantStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.CommunityJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})
return
}
if len(data.GroupJID) == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})
return
}
resp, err := c.communityService.CommunityRemove(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
func NewCommunityHandler(
communityService community_service.CommunityService,
) CommunityHandler {
return &communityHandler{
communityService: communityService,
}
}
+169
View File
@@ -0,0 +1,169 @@
package community_service
import (
"context"
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"github.com/gin-gonic/gin"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
)
type CommunityService interface {
CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error)
CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
}
type communityService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type CreateCommunityStruct struct {
CommunityName string `json:"communityName"`
}
type AddParticipantStruct struct {
CommunityJID string `json:"communityJid"`
GroupJID []string `json:"groupJid"`
}
func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := c.whatsmeowService.StartInstance(instanceId)
if err != nil {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
c.loggerWrapper.GetLogger(instanceId).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() {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (c *communityService) CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{
Name: data.CommunityName,
GroupParent: types.GroupParent{
IsParent: true,
},
})
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create community: %v", instance.Id, err)
return nil, err
}
return resp, nil
}
func (c *communityService) CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
communityJID, ok := utils.ParseJID(data.CommunityJID)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return nil, errors.New("error parse community jid")
}
var successList []string
var failedList []string
for _, participant := range data.GroupJID {
groupJID, _ := utils.ParseJID(participant)
err := client.LinkGroup(context.Background(), communityJID, groupJID)
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
failedList = append(failedList, groupJID.String())
}
successList = append(failedList, groupJID.String())
}
return gin.H{
"success": successList,
"failed": failedList,
}, nil
}
func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
communityJID, ok := utils.ParseJID(data.CommunityJID)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return nil, errors.New("error parse community jid")
}
var successList []string
var failedList []string
for _, participant := range data.GroupJID {
groupJID, _ := utils.ParseJID(participant)
err := client.UnlinkGroup(context.Background(), communityJID, groupJID)
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
failedList = append(failedList, groupJID.String())
}
successList = append(failedList, groupJID.String())
}
return gin.H{
"success": successList,
"failed": failedList,
}, nil
}
func NewCommunityService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) CommunityService {
return &communityService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}
+455
View File
@@ -0,0 +1,455 @@
package config
import (
"database/sql"
"fmt"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/gomessguii/logger"
"gorm.io/driver/postgres"
"gorm.io/gorm"
config_env "github.com/EvolutionAPI/evolution-go/pkg/config/env"
)
type Config struct {
PostgresAuthDB string
postgresUsersDB string
PostgresHost string
PostgresPort string
PostgresUser string
PostgresPassword string
PostgresDB string
DatabaseSaveMessages bool
GlobalApiKey string
WaDebug string
LogType string
WebhookFiles bool
ConnectOnStartup bool
OsName string
AmqpUrl string
AmqpGlobalEnabled bool
WebhookUrl string
ClientName string
ApiAudioConverter string
ApiAudioConverterKey string
MinioEndpoint string
MinioAccessKey string
MinioSecretKey string
MinioBucket string
MinioUseSSL bool
MinioEnabled bool
MinioRegion string
WhatsappVersionMajor int
WhatsappVersionMinor int
WhatsappVersionPatch int
ProxyHost string
ProxyPort string
ProxyUsername string
ProxyPassword string
AmqpGlobalEvents []string
AmqpSpecificEvents []string
NatsUrl string
NatsGlobalEnabled bool
NatsGlobalEvents []string
EventIgnoreGroup bool
EventIgnoreStatus bool
QrcodeMaxCount int
CheckUserExists bool
// Logger configurations
LogMaxSize int
LogMaxBackups int
LogMaxAge int
LogDirectory string
LogCompress bool
}
// EnsureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.
func (c *Config) EnsureDBExists(dsn string) error {
return ensureDBExists(dsn)
}
// ensureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.
func ensureDBExists(dsn string) error {
dbName, adminDSN, err := extractDBNameAndAdminDSN(dsn)
if err != nil {
return err
}
db, err := sql.Open("postgres", adminDSN)
if err != nil {
return fmt.Errorf("failed to connect to postgres for auto-setup: %v", err)
}
defer db.Close()
var exists bool
err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", dbName).Scan(&exists)
if err != nil {
return fmt.Errorf("failed to check database existence: %v", err)
}
if !exists {
logger.LogInfo("[CONFIG] Database %q not found, creating it automatically...", dbName)
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE %q", dbName))
if err != nil {
return fmt.Errorf("failed to create database %q: %v", dbName, err)
}
logger.LogInfo("[CONFIG] Database %q created successfully", dbName)
}
return nil
}
// extractDBNameAndAdminDSN parses a DSN (URL or key=value) and returns the database name
// and a DSN pointing to the "postgres" maintenance database.
func extractDBNameAndAdminDSN(dsn string) (string, string, error) {
// Try URL format: postgres://user:pass@host:port/dbname?...
if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
u, err := url.Parse(dsn)
if err != nil {
return "", "", fmt.Errorf("failed to parse DSN URL: %v", err)
}
dbName := strings.TrimPrefix(u.Path, "/")
u.Path = "/postgres"
return dbName, u.String(), nil
}
// Key=value format: host=... user=... password=... dbname=... sslmode=...
parts := strings.Fields(dsn)
kvMap := make(map[string]string, len(parts))
for _, p := range parts {
kv := strings.SplitN(p, "=", 2)
if len(kv) == 2 {
kvMap[kv[0]] = kv[1]
}
}
dbName, ok := kvMap["dbname"]
if !ok || dbName == "" {
return "", "", fmt.Errorf("could not extract dbname from DSN")
}
kvMap["dbname"] = "postgres"
adminParts := make([]string, 0, len(kvMap))
for k, v := range kvMap {
adminParts = append(adminParts, k+"="+v)
}
return dbName, strings.Join(adminParts, " "), nil
}
func (c *Config) CreateUsersDB() (*gorm.DB, error) {
logger.LogDebug("Connecting to database on: %s", c.postgresUsersDB)
dbDSN := c.postgresUsersDB
if c.postgresUsersDB == "" {
dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)
}
if err := ensureDBExists(dbDSN); err != nil {
logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)
}
db, err := gorm.Open(
postgres.Open(dbDSN),
&gorm.Config{},
)
if err != nil {
return nil, err
}
// Configurar pool de conexões no GORM
sqlDB, err := db.DB()
if err != nil {
return nil, fmt.Errorf("erro ao obter sql.DB do GORM: %v", err)
}
// Configurar pool de conexões para evitar conexões ociosas não fechadas
sqlDB.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente
sqlDB.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool
sqlDB.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts
sqlDB.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto
return db, nil
}
func (c *Config) CreateAuthDB() (*sql.DB, error) {
dbDSN := c.postgresUsersDB
if c.postgresUsersDB == "" {
dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)
}
if err := ensureDBExists(dbDSN); err != nil {
logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)
}
db, err := sql.Open("postgres", dbDSN)
if err != nil {
return nil, 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
// Testar a conexão
err = db.Ping()
if err != nil {
return nil, fmt.Errorf("erro ao testar conexão PostgreSQL AUTH: %v", err)
}
return db, nil
}
func Load() *Config {
postgresAuthDB := os.Getenv(config_env.POSTGRES_AUTH_DB)
postgresUsersDB := os.Getenv(config_env.POSTGRES_USERS_DB)
postgresHost := os.Getenv(config_env.POSTGRES_HOST)
postgresPort := os.Getenv(config_env.POSTGRES_PORT)
postgresUser := os.Getenv(config_env.POSTGRES_USER)
postgresPassword := os.Getenv(config_env.POSTGRES_PASSWORD)
postgresDB := os.Getenv(config_env.POSTGRES_DB)
if postgresUsersDB == "" && (postgresHost == "" || postgresPort == "" || postgresUser == "" || postgresPassword == "" || postgresDB == "") {
logger.LogFatal("[CONFIG] required database configuration variables are missing. Please check your environment configuration.")
}
databaseSaveMessages := os.Getenv(config_env.DATABASE_SAVE_MESSAGES)
panicIfEmpty(config_env.DATABASE_SAVE_MESSAGES, databaseSaveMessages)
globalApiKey := os.Getenv(config_env.GLOBAL_API_KEY)
panicIfEmpty(config_env.GLOBAL_API_KEY, globalApiKey)
clientName := os.Getenv(config_env.CLIENT_NAME)
waDebug := os.Getenv(config_env.WA_DEBUG)
logType := os.Getenv(config_env.LOGTYPE)
webhookFiles := os.Getenv(config_env.WEBHOOKFILES)
if webhookFiles == "" {
webhookFiles = "true"
}
connectOnStartup := os.Getenv(config_env.CONNECT_ON_STARTUP)
if connectOnStartup == "" {
connectOnStartup = "false"
}
osName := os.Getenv(config_env.OS_NAME)
amqpUrl := os.Getenv(config_env.AMQP_URL)
// Validate AMQP URL format
if err := validateAMQPURL(amqpUrl); err != nil {
logger.LogFatal("[CONFIG] AMQP URL validation failed: %v", err)
}
amqpGlobalEnabled := os.Getenv(config_env.AMQP_GLOBAL_ENABLED)
webhookUrl := os.Getenv(config_env.WEBHOOK_URL)
apiAudioConverter := os.Getenv(config_env.API_AUDIO_CONVERTER)
apiAudioConverterKey := os.Getenv(config_env.API_AUDIO_CONVERTER_KEY)
whatsappVersionMajor := os.Getenv(config_env.WHATSAPP_VERSION_MAJOR)
whatsappVersionMinor := os.Getenv(config_env.WHATSAPP_VERSION_MINOR)
whatsappVersionPatch := os.Getenv(config_env.WHATSAPP_VERSION_PATCH)
proxyHost := os.Getenv(config_env.PROXY_HOST)
proxyPort := os.Getenv(config_env.PROXY_PORT)
proxyUsername := os.Getenv(config_env.PROXY_USERNAME)
proxyPassword := os.Getenv(config_env.PROXY_PASSWORD)
eventIgnoreGroup := os.Getenv(config_env.EVENT_IGNORE_GROUP)
eventIgnoreStatus := os.Getenv(config_env.EVENT_IGNORE_STATUS)
qrcodeMaxCount := os.Getenv(config_env.QRCODE_MAX_COUNT)
checkUserExists := os.Getenv(config_env.CHECK_USER_EXISTS)
if checkUserExists == "" {
checkUserExists = "true"
}
// Convertendo para int com valores padrão caso estejam vazios
major := 0
if whatsappVersionMajor != "" {
major, _ = strconv.Atoi(whatsappVersionMajor)
}
minor := 0
if whatsappVersionMinor != "" {
minor, _ = strconv.Atoi(whatsappVersionMinor)
}
patch := 0
if whatsappVersionPatch != "" {
patch, _ = strconv.Atoi(whatsappVersionPatch)
}
qrMaxCount := 5 // Valor padrão
if qrcodeMaxCount != "" {
qrMaxCount, _ = strconv.Atoi(qrcodeMaxCount)
}
amqpGlobalEvents := strings.Split(os.Getenv(config_env.AMQP_GLOBAL_EVENTS), ",")
if len(amqpGlobalEvents) == 1 && amqpGlobalEvents[0] == "" {
amqpGlobalEvents = []string{}
}
amqpSpecificEvents := strings.Split(os.Getenv(config_env.AMQP_SPECIFIC_EVENTS), ",")
if len(amqpSpecificEvents) == 1 && amqpSpecificEvents[0] == "" {
amqpSpecificEvents = []string{}
}
natsUrl := os.Getenv(config_env.NATS_URL)
natsGlobalEnabled := os.Getenv(config_env.NATS_GLOBAL_ENABLED)
natsGlobalEvents := strings.Split(os.Getenv(config_env.NATS_GLOBAL_EVENTS), ",")
if len(natsGlobalEvents) == 1 && natsGlobalEvents[0] == "" {
natsGlobalEvents = []string{}
}
// Logger configurations
logMaxSize, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_SIZE))
if logMaxSize == 0 {
logMaxSize = 100 // Default 100MB
}
logMaxBackups, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_BACKUPS))
if logMaxBackups == 0 {
logMaxBackups = 5 // Default 5 backups
}
logMaxAge, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_AGE))
if logMaxAge == 0 {
logMaxAge = 30 // Default 30 days
}
logDirectory := os.Getenv(config_env.LOG_DIRECTORY)
if logDirectory == "" {
logDirectory = "./logs" // Default logs directory
}
logCompress := os.Getenv(config_env.LOG_COMPRESS) == "true"
if os.Getenv(config_env.LOG_COMPRESS) == "" {
logCompress = true // Default compression enabled
}
config := &Config{
PostgresAuthDB: postgresAuthDB,
postgresUsersDB: postgresUsersDB,
DatabaseSaveMessages: databaseSaveMessages == "true",
GlobalApiKey: globalApiKey,
WaDebug: waDebug,
LogType: logType,
WebhookFiles: webhookFiles == "true",
ConnectOnStartup: connectOnStartup == "true",
OsName: osName,
AmqpUrl: amqpUrl,
AmqpGlobalEnabled: amqpGlobalEnabled == "true",
WebhookUrl: webhookUrl,
ClientName: clientName,
ApiAudioConverter: apiAudioConverter,
ApiAudioConverterKey: apiAudioConverterKey,
PostgresHost: postgresHost,
PostgresPort: postgresPort,
PostgresUser: postgresUser,
PostgresPassword: postgresPassword,
PostgresDB: postgresDB,
WhatsappVersionMajor: major,
WhatsappVersionMinor: minor,
WhatsappVersionPatch: patch,
ProxyHost: proxyHost,
ProxyPort: proxyPort,
ProxyUsername: proxyUsername,
ProxyPassword: proxyPassword,
EventIgnoreGroup: eventIgnoreGroup == "true",
EventIgnoreStatus: eventIgnoreStatus == "true",
QrcodeMaxCount: qrMaxCount,
CheckUserExists: checkUserExists != "false", // Default true, set to false to disable
AmqpGlobalEvents: amqpGlobalEvents,
AmqpSpecificEvents: amqpSpecificEvents,
NatsUrl: natsUrl,
NatsGlobalEnabled: natsGlobalEnabled == "true",
NatsGlobalEvents: natsGlobalEvents,
LogMaxSize: logMaxSize,
LogMaxBackups: logMaxBackups,
LogMaxAge: logMaxAge,
LogDirectory: logDirectory,
LogCompress: logCompress,
}
minioEnabled := os.Getenv(config_env.MINIO_ENABLED) == "true"
if minioEnabled {
config.MinioEnabled = true
loadMinioConfig(config)
}
return config
}
func loadMinioConfig(config *Config) {
minioEndpoint := os.Getenv(config_env.MINIO_ENDPOINT)
panicIfEmpty(config_env.MINIO_ENDPOINT, minioEndpoint)
minioAccessKey := os.Getenv(config_env.MINIO_ACCESS_KEY)
panicIfEmpty(config_env.MINIO_ACCESS_KEY, minioAccessKey)
minioSecretKey := os.Getenv(config_env.MINIO_SECRET_KEY)
panicIfEmpty(config_env.MINIO_SECRET_KEY, minioSecretKey)
minioBucket := os.Getenv(config_env.MINIO_BUCKET)
panicIfEmpty(config_env.MINIO_BUCKET, minioBucket)
minioUseSSL := os.Getenv(config_env.MINIO_USE_SSL) == "true"
minioRegion := os.Getenv(config_env.MINIO_REGION)
config.MinioEndpoint = minioEndpoint
config.MinioAccessKey = minioAccessKey
config.MinioSecretKey = minioSecretKey
config.MinioBucket = minioBucket
config.MinioUseSSL = minioUseSSL
config.MinioRegion = minioRegion
}
func panicIfEmpty(key, value string) {
if value == "" {
if os.Getenv("DEBUG_ENABLED") != "1" {
logger.LogInfo("You are NOT on development mode")
}
logger.LogFatal("[CONFIG] required configuration variable is missing. Please check your environment configuration.")
}
}
// validateAMQPURL validates if the AMQP URL has the correct scheme and format
func validateAMQPURL(amqpURL string) error {
if amqpURL == "" {
return nil // Empty URL is allowed (RabbitMQ disabled)
}
// Parse the URL
parsedURL, err := url.Parse(amqpURL)
if err != nil {
return fmt.Errorf("invalid AMQP URL format: %v", err)
}
// Check if scheme is valid
if parsedURL.Scheme != "amqp" && parsedURL.Scheme != "amqps" {
return fmt.Errorf("AMQP scheme must be either 'amqp://' or 'amqps://', got: '%s://'", parsedURL.Scheme)
}
// Check if host is present
if parsedURL.Host == "" {
return fmt.Errorf("AMQP URL must include a host")
}
logger.LogInfo("[CONFIG] AMQP URL validation successful: %s://%s", parsedURL.Scheme, parsedURL.Host)
return nil
}
+54
View File
@@ -0,0 +1,54 @@
package config_env
const (
POSTGRES_AUTH_DB = "POSTGRES_AUTH_DB"
POSTGRES_USERS_DB = "POSTGRES_USERS_DB"
POSTGRES_HOST = "POSTGRES_HOST"
POSTGRES_PORT = "POSTGRES_PORT"
POSTGRES_USER = "POSTGRES_USER"
POSTGRES_PASSWORD = "POSTGRES_PASSWORD"
POSTGRES_DB = "POSTGRES_DB"
DATABASE_SAVE_MESSAGES = "DATABASE_SAVE_MESSAGES"
GLOBAL_API_KEY = "GLOBAL_API_KEY"
WA_DEBUG = "DEBUG_ENABLED"
LOGTYPE = "LOG_TYPE"
WEBHOOKFILES = "WEBHOOK_FILES"
CONNECT_ON_STARTUP = "CONNECT_ON_STARTUP"
OS_NAME = "OS_NAME"
AMQP_URL = "AMQP_URL"
AMQP_GLOBAL_ENABLED = "AMQP_GLOBAL_ENABLED"
AMQP_GLOBAL_EVENTS = "AMQP_GLOBAL_EVENTS"
AMQP_SPECIFIC_EVENTS = "AMQP_SPECIFIC_EVENTS"
WEBHOOK_URL = "WEBHOOK_URL"
CLIENT_NAME = "CLIENT_NAME"
API_AUDIO_CONVERTER = "API_AUDIO_CONVERTER"
API_AUDIO_CONVERTER_KEY = "API_AUDIO_CONVERTER_KEY"
MINIO_ENDPOINT = "MINIO_ENDPOINT"
MINIO_ACCESS_KEY = "MINIO_ACCESS_KEY"
MINIO_SECRET_KEY = "MINIO_SECRET_KEY"
MINIO_BUCKET = "MINIO_BUCKET"
MINIO_USE_SSL = "MINIO_USE_SSL"
MINIO_ENABLED = "MINIO_ENABLED"
MINIO_REGION = "MINIO_REGION"
WHATSAPP_VERSION_MAJOR = "WHATSAPP_VERSION_MAJOR"
WHATSAPP_VERSION_MINOR = "WHATSAPP_VERSION_MINOR"
WHATSAPP_VERSION_PATCH = "WHATSAPP_VERSION_PATCH"
PROXY_HOST = "PROXY_HOST"
PROXY_PORT = "PROXY_PORT"
PROXY_USERNAME = "PROXY_USERNAME"
PROXY_PASSWORD = "PROXY_PASSWORD"
NATS_URL = "NATS_URL"
NATS_GLOBAL_ENABLED = "NATS_GLOBAL_ENABLED"
NATS_GLOBAL_EVENTS = "NATS_GLOBAL_EVENTS"
EVENT_IGNORE_GROUP = "EVENT_IGNORE_GROUP"
EVENT_IGNORE_STATUS = "EVENT_IGNORE_STATUS"
QRCODE_MAX_COUNT = "QRCODE_MAX_COUNT"
CHECK_USER_EXISTS = "CHECK_USER_EXISTS"
// Logger configurations
LOG_MAX_SIZE = "LOG_MAX_SIZE"
LOG_MAX_BACKUPS = "LOG_MAX_BACKUPS"
LOG_MAX_AGE = "LOG_MAX_AGE"
LOG_DIRECTORY = "LOG_DIRECTORY"
LOG_COMPRESS = "LOG_COMPRESS"
)
+837
View File
@@ -0,0 +1,837 @@
package core
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"io"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
var (
encodedEP string
xorKey string
)
func _d0() string {
if encodedEP != "" && xorKey != "" {
return decodeXOR(encodedEP, xorKey)
}
parts := [...]string{"h", "tt", "ps", "://", "li", "ce", "nse", ".", "ev", "ol", "ut", "io", "nf", "ou", "nd", "at", "io", "n.", "co", "m.", "br"}
var s string
for _, p := range parts {
s += p
}
return s
}
func decodeXOR(enc, key string) string {
encBytes := hexDec(enc)
keyBytes := hexDec(key)
if len(keyBytes) == 0 {
return ""
}
out := make([]byte, len(encBytes))
for i, b := range encBytes {
out[i] = b ^ keyBytes[i%len(keyBytes)]
}
return string(out)
}
func hexDec(s string) []byte {
if len(s)%2 != 0 {
return nil
}
b := make([]byte, len(s)/2)
for i := 0; i < len(s); i += 2 {
b[i/2] = hexVal(s[i])<<4 | hexVal(s[i+1])
}
return b
}
func hexVal(c byte) byte {
switch {
case c >= '0' && c <= '9':
return c - '0'
case c >= 'a' && c <= 'f':
return c - 'a' + 10
case c >= 'A' && c <= 'F':
return c - 'A' + 10
}
return 0
}
var _h0 = &http.Client{Timeout: 10 * time.Second}
func _sg(body []byte, secret string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
return hex.EncodeToString(mac.Sum(nil))
}
func _ps(path string, payload interface{}, _a0 string) (*http.Response, error) {
body, err := json.Marshal(payload)
if err != nil {
return nil, err
}
url := _d0() + path
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Api-Key", _a0)
req.Header.Set("X-Signature", _sg(body, _a0))
return _h0.Do(req)
}
func _gu(path string) (*http.Response, error) {
url := _d0() + path
return _h0.Get(url)
}
func _pu(path string, payload interface{}) (*http.Response, error) {
body, err := json.Marshal(payload)
if err != nil {
return nil, err
}
url := _d0() + path
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return _h0.Do(req)
}
func _re(resp *http.Response) error {
b, _ := io.ReadAll(resp.Body)
var errBody struct {
Message string `json:"message"`
Error string `json:"error"`
}
if err := json.Unmarshal(b, &errBody); err == nil {
msg := errBody.Message
if msg == "" {
msg = errBody.Error
}
if msg != "" {
return fmt.Errorf("%s (HTTP %d)", strings.ToLower(msg), resp.StatusCode)
}
}
return fmt.Errorf("HTTP %d", resp.StatusCode)
}
type RuntimeConfig struct {
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
Key string `gorm:"uniqueIndex;size:100;not null" json:"key"`
Value string `gorm:"type:text;not null" json:"value"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (RuntimeConfig) TableName() string {
return "runtime_configs"
}
const (
_ck0 = "instance_id"
_ck1 = "api_key"
_ck2 = "_a7"
_ck3 = "customer_id"
)
var _db0 *gorm.DB
func SetDB(db *gorm.DB) {
_db0 = db
}
func MigrateDB() error {
if _db0 == nil {
return fmt.Errorf("core: database not set, call SetDB first")
}
return _db0.AutoMigrate(&RuntimeConfig{})
}
func _gc(key string) (string, error) {
if _db0 == nil {
return "", fmt.Errorf("core: database not set")
}
var cfg RuntimeConfig
result := _db0.Where("key = ?", key).First(&cfg)
if result.Error != nil {
return "", result.Error
}
return cfg.Value, nil
}
func _sc(key, value string) error {
if _db0 == nil {
return fmt.Errorf("core: database not set")
}
var cfg RuntimeConfig
result := _db0.Where("key = ?", key).First(&cfg)
if result.Error != nil {
return _db0.Create(&RuntimeConfig{Key: key, Value: value}).Error
}
return _db0.Model(&cfg).Update("value", value).Error
}
func _dc(key string) {
if _db0 == nil {
return
}
_db0.Where("key = ?", key).Delete(&RuntimeConfig{})
}
type _rtd struct {
APIKey string
Tier string
CustomerID int
}
func _lrd() (*_rtd, error) {
_a0, err := _gc(_ck1)
if err != nil || _a0 == "" {
return nil, fmt.Errorf("no license found")
}
_a7, _ := _gc(_ck2)
customerIDStr, _ := _gc(_ck3)
customerID, _ := strconv.Atoi(customerIDStr)
return &_rtd{
APIKey: _a0,
Tier: _a7,
CustomerID: customerID,
}, nil
}
func _srd(rd *_rtd) error {
if err := _sc(_ck1, rd.APIKey); err != nil {
return err
}
if err := _sc(_ck2, rd.Tier); err != nil {
return err
}
if rd.CustomerID > 0 {
if err := _sc(_ck3, strconv.Itoa(rd.CustomerID)); err != nil {
return err
}
}
return nil
}
func _rrd() {
_dc(_ck1)
_dc(_ck2)
_dc(_ck3)
}
func _lid() (string, error) {
id, err := _gc(_ck0)
if err == nil && len(id) == 36 {
return id, nil
}
id = _ghi()
if id == "" {
id, err = _uuid()
if err != nil {
return "", err
}
}
if err := _sc(_ck0, id); err != nil {
return "", err
}
return id, nil
}
func _ghi() string {
hostname, _ := os.Hostname()
macAddr := _gpm()
if hostname == "" && macAddr == "" {
return ""
}
seed := hostname + "|" + macAddr
h := make([]byte, 16)
copy(h, []byte(seed))
for i := 16; i < len(seed); i++ {
h[i%16] ^= seed[i]
}
h[6] = (h[6] & 0x0f) | 0x40 // _a8 4
h[8] = (h[8] & 0x3f) | 0x80 // variant
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
h[0:4], h[4:6], h[6:8], h[8:10], h[10:16])
}
func _gpm() string {
interfaces, err := net.Interfaces()
if err != nil {
return ""
}
for _, iface := range interfaces {
if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 {
continue
}
if len(iface.HardwareAddr) > 0 {
return iface.HardwareAddr.String()
}
}
return ""
}
func _uuid() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}
var _s0 atomic.Value // set during activation
func init() {
_s0.Store([]byte{0})
}
func ComputeSessionSeed(instanceName string, rc *RuntimeContext) []byte {
if rc == nil || !rc._a2.Load() {
return nil // Will cause panic in caller — intentional
}
h := sha256.New()
h.Write([]byte(instanceName))
h.Write([]byte(rc._a0))
salt, _ := _s0.Load().([]byte)
h.Write(salt)
return h.Sum(nil)[:16]
}
func ValidateRouteAccess(rc *RuntimeContext) uint64 {
if rc == nil {
return 0
}
h := rc.ContextHash()
return binary.LittleEndian.Uint64(h[:8])
}
func DeriveInstanceToken(_a1 string, rc *RuntimeContext) string {
if rc == nil || !rc._a2.Load() {
return ""
}
h := sha256.Sum256([]byte(_a1 + rc._a0))
return _he(h[:8])
}
func _he(b []byte) string {
const hextable = "0123456789abcdef"
dst := make([]byte, len(b)*2)
for i, v := range b {
dst[i*2] = hextable[v>>4]
dst[i*2+1] = hextable[v&0x0f]
}
return string(dst)
}
func ActivateIntegrity(rc *RuntimeContext) {
if rc == nil {
return
}
h := sha256.Sum256([]byte(rc._a0 + rc._a1 + "ev0"))
_s0.Store(h[:])
}
const (
_p2 = 30 * time.Minute
)
type RuntimeContext struct {
_a0 string
_a9 string // GLOBAL_API_KEY from .env — used as token for licensing check
_a1 string
_a2 atomic.Bool
_a3 [32]byte // Derived from activation — required by ValidateContext
mu sync.RWMutex
_a5 string // Registration URL shown to users before activation
_a6 string // Registration token for polling
_a7 string
_a8 string
}
func (rc *RuntimeContext) ContextHash() [32]byte {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc._a3
}
func (rc *RuntimeContext) IsActive() bool {
return rc._a2.Load()
}
func (rc *RuntimeContext) RegistrationURL() string {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc._a5
}
func (rc *RuntimeContext) APIKey() string {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc._a0
}
func (rc *RuntimeContext) InstanceID() string {
return rc._a1
}
func InitializeRuntime(_a7, _a8, _a9 string) *RuntimeContext {
if _a7 == "" {
_a7 = "evolution-go"
}
if _a8 == "" {
_a8 = "unknown"
}
rc := &RuntimeContext{
_a7: _a7,
_a8: _a8,
_a9: _a9,
}
id, err := _lid()
if err != nil {
log.Fatalf("[runtime] failed to initialize instance: %v", err)
}
rc._a1 = id
rd, err := _lrd()
if err == nil && rd.APIKey != "" {
rc._a0 = rd.APIKey
fmt.Printf(" ✓ License found: %s...%s\n", rd.APIKey[:8], rd.APIKey[len(rd.APIKey)-4:])
rc._a3 = sha256.Sum256([]byte(rc._a0 + rc._a1))
rc._a2.Store(true)
ActivateIntegrity(rc)
fmt.Println(" ✓ License activated successfully")
go func() {
if err := _ai(rc, _a8); err != nil {
fmt.Printf(" ⚠ Remote activation notice failed (non-blocking): %v\n", err)
}
}()
} else {
fmt.Println()
fmt.Println(" ╔══════════════════════════════════════════════════════════╗")
fmt.Println(" ║ License Registration Required ║")
fmt.Println(" ╚══════════════════════════════════════════════════════════╝")
fmt.Println()
fmt.Println(" Server starting without license.")
fmt.Println(" API endpoints will return 503 until license is activated.")
fmt.Println(" Use GET /license/register to get the registration URL.")
fmt.Println()
rc._a2.Store(false)
}
return rc
}
func (rc *RuntimeContext) _ca(authCodeOrKey, _a7 string, customerID int) error {
_a0, err := _rk(authCodeOrKey)
if err != nil {
return fmt.Errorf("key exchange failed: %w", err)
}
rc.mu.Lock()
rc._a0 = _a0
rc._a5 = ""
rc._a6 = ""
rc.mu.Unlock()
if err := _srd(&_rtd{
APIKey: _a0,
Tier: _a7,
CustomerID: customerID,
}); err != nil {
fmt.Printf(" ⚠ Warning: could not save license: %v\n", err)
}
if err := _ai(rc, rc._a8); err != nil {
return err
}
rc.mu.Lock()
rc._a3 = sha256.Sum256([]byte(rc._a0 + rc._a1))
rc.mu.Unlock()
rc._a2.Store(true)
ActivateIntegrity(rc)
fmt.Printf(" ✓ License activated! Key: %s...%s (_a7: %s)\n",
_a0[:8], _a0[len(_a0)-4:], _a7)
go func() {
if err := _hb(rc, 0); err != nil {
fmt.Printf(" ⚠ First heartbeat failed: %v\n", err)
}
}()
return nil
}
func ValidateContext(rc *RuntimeContext) (bool, string) {
if rc == nil {
return false, ""
}
if !rc._a2.Load() {
return false, rc.RegistrationURL()
}
expected := sha256.Sum256([]byte(rc._a0 + rc._a1))
actual := rc.ContextHash()
if expected != actual {
return false, ""
}
return true, ""
}
func GateMiddleware(rc *RuntimeContext) gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.Path
if path == "/health" || path == "/server/ok" || path == "/favicon.ico" ||
path == "/license/status" || path == "/license/register" || path == "/license/activate" ||
strings.HasPrefix(path, "/manager") || strings.HasPrefix(path, "/assets") ||
strings.HasPrefix(path, "/swagger") || path == "/ws" {
c.Next()
return
}
valid, _ := ValidateContext(rc)
if !valid {
scheme := "http"
if c.Request.TLS != nil {
scheme = "https"
}
managerURL := fmt.Sprintf("%s://%s/manager/login", scheme, c.Request.Host)
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{
"error": "service not activated",
"code": "LICENSE_REQUIRED",
"register_url": managerURL,
"message": "License required. Open the manager to activate your license.",
})
return
}
c.Set("_rch", rc.ContextHash())
c.Next()
}
}
func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
lic := eng.Group("/license")
{
lic.GET("/status", func(c *gin.Context) {
status := "inactive"
if rc.IsActive() {
status = "_a2"
}
resp := gin.H{
"status": status,
"instance_id": rc._a1,
}
rc.mu.RLock()
if rc._a0 != "" {
resp["api_key"] = rc._a0[:8] + "..." + rc._a0[len(rc._a0)-4:]
}
rc.mu.RUnlock()
c.JSON(http.StatusOK, resp)
})
lic.GET("/register", func(c *gin.Context) {
if rc.IsActive() {
c.JSON(http.StatusOK, gin.H{
"status": "_a2",
"message": "License is already _a2",
})
return
}
rc.mu.RLock()
existingURL := rc._a5
rc.mu.RUnlock()
if existingURL != "" {
c.JSON(http.StatusOK, gin.H{
"status": "pending",
"register_url": existingURL,
})
return
}
payload := map[string]string{
"_a7": rc._a7,
"_a8": rc._a8,
"instance_id": rc._a1,
}
if redirectURI := c.Query("redirect_uri"); redirectURI != "" {
payload["redirect_uri"] = redirectURI
}
resp, err := _pu("/v1/register/init", payload)
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{
"error": "Failed to contact licensing server",
"details": err.Error(),
})
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
errBody := _re(resp)
c.JSON(resp.StatusCode, gin.H{
"error": "Licensing server error",
"details": errBody.Error(),
})
return
}
var initResult struct {
RegisterURL string `json:"register_url"`
Token string `json:"token"`
}
json.NewDecoder(resp.Body).Decode(&initResult)
rc.mu.Lock()
rc._a5 = initResult.RegisterURL
rc._a6 = initResult.Token
rc.mu.Unlock()
fmt.Printf(" → Registration URL: %s\n", initResult.RegisterURL)
c.JSON(http.StatusOK, gin.H{
"status": "pending",
"register_url": initResult.RegisterURL,
})
})
lic.GET("/activate", func(c *gin.Context) {
if rc.IsActive() {
c.JSON(http.StatusOK, gin.H{
"status": "_a2",
"message": "License is already _a2",
})
return
}
code := c.Query("code")
if code == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Missing code parameter",
"message": "Provide ?code=AUTHORIZATION_CODE from the registration callback.",
})
return
}
exchangeResp, err := _pu("/v1/register/exchange", map[string]string{
"authorization_code": code,
"instance_id": rc._a1,
})
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{
"error": "Failed to contact licensing server",
"details": err.Error(),
})
return
}
defer exchangeResp.Body.Close()
if exchangeResp.StatusCode != http.StatusOK {
errBody := _re(exchangeResp)
c.JSON(exchangeResp.StatusCode, gin.H{
"error": "Exchange failed",
"details": errBody.Error(),
})
return
}
var result struct {
APIKey string `json:"api_key"`
Tier string `json:"_a7"`
CustomerID int `json:"customer_id"`
}
json.NewDecoder(exchangeResp.Body).Decode(&result)
if result.APIKey == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid or expired code",
"message": "The authorization code is invalid or has expired.",
})
return
}
if err := rc._ca(result.APIKey, result.Tier, result.CustomerID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Activation failed",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "_a2",
"message": "License activated successfully!",
})
})
}
}
func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time) {
go func() {
ticker := time.NewTicker(_p2)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if !rc.IsActive() {
continue
}
uptime := int64(time.Since(startTime).Seconds())
if err := _hb(rc, uptime); err != nil {
fmt.Printf(" ⚠ Heartbeat failed (non-blocking): %v\n", err)
}
}
}
}()
}
func Shutdown(rc *RuntimeContext) {
if rc == nil || rc._a0 == "" {
return
}
_sd(rc)
}
func exchangeCode(code string) (_a0 string, err error) {
resp, err := _pu("/v1/register/exchange", map[string]string{
"authorization_code": code,
})
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", _re(resp)
}
var result struct {
APIKey string `json:"api_key"`
}
json.NewDecoder(resp.Body).Decode(&result)
if result.APIKey == "" {
return "", fmt.Errorf("exchange returned empty api_key")
}
return result.APIKey, nil
}
func _rk(authCodeOrKey string) (string, error) {
_a0, err := exchangeCode(authCodeOrKey)
if err == nil && _a0 != "" {
return _a0, nil
}
return authCodeOrKey, nil
}
func _ai(rc *RuntimeContext, _a8 string) error {
resp, err := _ps("/v1/activate", map[string]string{
"instance_id": rc._a1,
"_a8": _a8,
}, rc._a0)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return _re(resp)
}
var result struct {
Status string `json:"status"`
}
json.NewDecoder(resp.Body).Decode(&result)
if result.Status != "_a2" {
return fmt.Errorf("activation returned status: %s", result.Status)
}
return nil
}
func _hb(rc *RuntimeContext, uptimeSeconds int64) error {
resp, err := _ps("/v1/heartbeat", map[string]any{
"instance_id": rc._a1,
"uptime_seconds": uptimeSeconds,
"_a8": rc._a8,
}, rc._a0)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return _re(resp)
}
return nil
}
func _sd(rc *RuntimeContext) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
body, _ := json.Marshal(map[string]string{
"instance_id": rc._a1,
})
url := _d0() + "/v1/deactivate"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Api-Key", rc._a0)
req.Header.Set("X-Signature", _sg(body, rc._a0))
_h0.Do(req)
}
+6
View File
@@ -0,0 +1,6 @@
package producer_interfaces
type Producer interface {
Produce(queueName string, payload []byte, webhookUrl string, userID string) error
CreateGlobalQueues() error
}
+81
View File
@@ -0,0 +1,81 @@
package nats_producer
import (
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/gomessguii/logger"
"github.com/nats-io/nats.go"
)
type natsProducer struct {
conn *nats.Conn
natsGlobalEnabled bool
natsGlobalEvents []string
loggerWrapper *logger_wrapper.LoggerManager
}
func NewNatsProducer(
url string,
natsGlobalEnabled bool,
natsGlobalEvents []string,
loggerWrapper *logger_wrapper.LoggerManager,
) producer_interfaces.Producer {
conn, err := nats.Connect(url)
if err != nil {
logger.LogError("Failed to connect to NATS: %v", err)
return &natsProducer{
conn: nil,
natsGlobalEnabled: false,
natsGlobalEvents: nil,
loggerWrapper: loggerWrapper,
}
}
return &natsProducer{
conn: conn,
natsGlobalEnabled: natsGlobalEnabled,
natsGlobalEvents: natsGlobalEvents,
loggerWrapper: loggerWrapper,
}
}
func (p *natsProducer) Produce(
queueName string,
payload []byte,
natsEnable string,
userID string,
) error {
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Starting produce for subject: %s", userID, queueName)
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Global enabled: %v", userID, p.natsGlobalEnabled)
if p.conn == nil {
p.loggerWrapper.GetLogger(userID).LogWarn("[%s] NATS connection is nil", userID)
return nil
}
if natsEnable == "global" {
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Publishing to global subject: %s", userID, queueName)
err := p.conn.Publish(queueName, payload)
if err != nil {
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to subject %s: %v", userID, queueName, err)
return err
}
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to subject: %s", userID, queueName)
}
if natsEnable == "enabled" {
err := p.conn.Publish(queueName, payload)
if err != nil {
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to instance subject %s: %v", userID, queueName, err)
return err
}
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to instance subject: %s", userID, queueName)
}
return nil
}
// CreateGlobalQueues não faz nada para NATS producer pois os subjects são criados dinamicamente
func (p *natsProducer) CreateGlobalQueues() error {
return nil
}
+319
View File
@@ -0,0 +1,319 @@
package rabbitmq_producer
import (
"fmt"
"net/url"
"strings"
"time"
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/gomessguii/logger"
amqp "github.com/rabbitmq/amqp091-go"
)
type rabbitMQProducer struct {
conn *amqp.Connection
amqpGlobalEnabled bool
amqpGlobalEvents []string
amqpSpecificEvents []string
connStr string
maxRetries int
loggerWrapper *logger_wrapper.LoggerManager
}
func NewRabbitMQProducer(
conn *amqp.Connection,
amqpGlobalEnabled bool,
amqpGlobalEvents []string,
amqpSpecificEvents []string,
connStr string,
loggerWrapper *logger_wrapper.LoggerManager,
) producer_interfaces.Producer {
producer := &rabbitMQProducer{
conn: conn,
amqpGlobalEnabled: amqpGlobalEnabled,
amqpGlobalEvents: amqpGlobalEvents,
amqpSpecificEvents: amqpSpecificEvents,
connStr: connStr,
maxRetries: 3,
loggerWrapper: loggerWrapper,
}
return producer
}
// maskConnectionString masks sensitive information in the connection string for logging
func (p *rabbitMQProducer) maskConnectionString(connStr string) string {
if connStr == "" {
return "empty"
}
parsedURL, err := url.Parse(connStr)
if err != nil {
return "invalid-url"
}
// Mask password if present
if parsedURL.User != nil {
if _, hasPassword := parsedURL.User.Password(); hasPassword {
parsedURL.User = url.UserPassword(parsedURL.User.Username(), "***")
}
}
return parsedURL.String()
}
// handleConnectionClose monitors connection close events and logs them
func (p *rabbitMQProducer) handleConnectionClose() {
if p.conn == nil {
return
}
closeChan := make(chan *amqp.Error)
p.conn.NotifyClose(closeChan)
closeErr := <-closeChan
if closeErr != nil {
logger.LogWarn("RabbitMQ connection closed unexpectedly: %v", closeErr)
logger.LogInfo("Connection will be re-established on next message send")
} else {
logger.LogInfo("RabbitMQ connection closed gracefully")
}
}
func (p *rabbitMQProducer) reconnect() error {
if p.connStr == "" {
return fmt.Errorf("connection string is empty - RabbitMQ URL not configured")
}
logger.LogInfo("Starting RabbitMQ reconnection process with URL: %s", p.maskConnectionString(p.connStr))
var err error
for i := 0; i < 3; i++ {
logger.LogInfo("Tentando reconectar ao RabbitMQ (tentativa %d/3)", i+1)
// Create connection with heartbeat to prevent timeouts
config := amqp.Config{
Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds
Locale: "en_US",
}
p.conn, err = amqp.DialConfig(p.connStr, config)
if err == nil {
logger.LogInfo("Reconectado com sucesso ao RabbitMQ com heartbeat de 30s")
// Set up connection close notification
go p.handleConnectionClose()
return nil
}
logger.LogError("Falha na tentativa %d/3 de reconexão: %v", i+1, err)
if i < 2 { // Don't sleep on the last attempt
time.Sleep(time.Second * 2)
}
}
return fmt.Errorf("falha ao reconectar após 3 tentativas: %v", err)
}
func (p *rabbitMQProducer) ensureConnection() error {
if p.conn == nil || p.conn.IsClosed() {
return p.reconnect()
}
return nil
}
func (p *rabbitMQProducer) publishWithRetry(
channel *amqp.Channel,
queueName string,
payload []byte,
userID string,
) error {
var err error
for i := 0; i < p.maxRetries; i++ {
err = channel.Publish(
"", // exchange
queueName, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/json",
Body: payload,
DeliveryMode: amqp.Persistent, // Garante persistência da mensagem
})
if err == nil {
return nil
}
logger.LogWarn("[%s] Falha ao publicar mensagem (tentativa %d/%d): %v",
userID, i+1, p.maxRetries, err)
// Se o erro for de conexão, tenta reconectar
if err.Error() == "Exception (504) Reason: \"channel/connection is not open\"" {
if err := p.ensureConnection(); err != nil {
continue
}
// Cria novo canal após reconexão
channel, err = p.conn.Channel()
if err != nil {
continue
}
}
time.Sleep(time.Second * time.Duration(i+1))
}
return err
}
func (p *rabbitMQProducer) Produce(
queueName string,
payload []byte,
rabbitmqEnable string,
userID string,
) error {
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] RabbitMQ Producer - Starting produce for queue: %s", userID, queueName)
if p.connStr == "" {
return fmt.Errorf("RabbitMQ connection string is empty - check AMQP_URL configuration")
}
if err := p.ensureConnection(); err != nil {
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to ensure RabbitMQ connection: %v", userID, err)
return fmt.Errorf("falha ao garantir conexão: %v", err)
}
channel, err := p.conn.Channel()
if err != nil {
return fmt.Errorf("falha ao abrir canal: %v", err)
}
defer channel.Close()
// Configura confirmação de publicação
if err := channel.Confirm(false); err != nil {
return fmt.Errorf("falha ao configurar confirms do canal: %v", err)
}
args := amqp.Table{
"x-queue-type": "quorum",
"x-ha-policy": "all", // Alta disponibilidade
}
if rabbitmqEnable == "global" || rabbitmqEnable == "enabled" {
_, err = channel.QueueDeclare(
queueName, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
args, // arguments
)
if err != nil {
return fmt.Errorf("falha ao declarar fila %s: %v", queueName, err)
}
err = p.publishWithRetry(channel, queueName, payload, userID)
if err != nil {
return fmt.Errorf("falha ao publicar mensagem após todas as tentativas: %v", err)
}
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Mensagem publicada com sucesso na fila: %s", userID, queueName)
}
return nil
}
// CreateGlobalQueues cria todas as filas globais no startup da aplicação
func (p *rabbitMQProducer) CreateGlobalQueues() error {
if !p.amqpGlobalEnabled {
return nil
}
p.loggerWrapper.GetLogger("system").LogInfo("Creating global queues for enabled events")
if err := p.ensureConnection(); err != nil {
return fmt.Errorf("failed to ensure connection: %v", err)
}
channel, err := p.conn.Channel()
if err != nil {
return fmt.Errorf("failed to open channel: %v", err)
}
defer channel.Close()
args := amqp.Table{
"x-queue-type": "quorum",
"x-ha-policy": "all", // Alta disponibilidade
}
createdQueues := 0
// AMQP_SPECIFIC_EVENTS tem prioridade sobre AMQP_GLOBAL_EVENTS
if len(p.amqpSpecificEvents) > 0 {
p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_SPECIFIC_EVENTS (priority over AMQP_GLOBAL_EVENTS)")
// Cria filas diretas para eventos específicos
for _, eventName := range p.amqpSpecificEvents {
queueName := strings.ToLower(eventName)
_, err = channel.QueueDeclare(
queueName, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
args, // arguments
)
if err != nil {
p.loggerWrapper.GetLogger("system").LogError("Failed to create specific queue %s: %v", queueName, err)
return fmt.Errorf("failed to create specific queue %s: %v", queueName, err)
}
p.loggerWrapper.GetLogger("system").LogInfo("Specific queue created: %s", queueName)
createdQueues++
}
} else {
p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_GLOBAL_EVENTS (fallback mode)")
// Mapeia eventos globais para os eventos originais que precisam de filas (modo antigo)
eventMap := map[string][]string{
"MESSAGE": {"message"},
"SEND_MESSAGE": {"sendmessage"},
"READ_RECEIPT": {"receipt"},
"PRESENCE": {"presence"},
"HISTORY_SYNC": {"historysync"},
"CHAT_PRESENCE": {"chatpresence", "archive"},
"CALL": {"calloffer", "callaccept", "callterminate", "calloffernotice", "callrelaylatency"},
"CONNECTION": {"connected", "pairsuccess", "temporaryban", "loggedout", "connectfailure", "disconnected"},
"LABEL": {"labeledit", "labelassociationchat", "labelassociationmessage"},
"CONTACT": {"contact", "pushname"},
"GROUP": {"groupinfo", "joinedgroup"},
"NEWSLETTER": {"newsletterjoin", "newsletterleave"},
"QRCODE": {"qrcode", "qrtimeout", "qrsuccess"},
}
for _, globalEvent := range p.amqpGlobalEvents {
if queueNames, exists := eventMap[globalEvent]; exists {
for _, queueName := range queueNames {
_, err = channel.QueueDeclare(
queueName, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
args, // arguments
)
if err != nil {
p.loggerWrapper.GetLogger("system").LogError("Failed to create global queue %s: %v", queueName, err)
return fmt.Errorf("failed to create global queue %s: %v", queueName, err)
}
p.loggerWrapper.GetLogger("system").LogInfo("Global queue created: %s", queueName)
createdQueues++
}
}
}
}
p.loggerWrapper.GetLogger("system").LogInfo("Successfully created %d global queues", createdQueues)
return nil
}
+97
View File
@@ -0,0 +1,97 @@
package webhook_producer
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
)
type webhookProducer struct {
url string
loggerWrapper *logger_wrapper.LoggerManager
}
func NewWebhookProducer(
url string,
loggerWrapper *logger_wrapper.LoggerManager,
) producer_interfaces.Producer {
return &webhookProducer{
url: url,
loggerWrapper: loggerWrapper,
}
}
func (p *webhookProducer) Produce(
queueName string,
payload []byte,
webhookUrl string,
userID string,
) error {
splitQueue := strings.Split(queueName, ".")
if len(splitQueue) < 2 {
return nil
}
if p.url != "" {
go p.sendWebhookWithRetry(p.url, payload, 5, 30*time.Second, userID)
}
if webhookUrl != "" {
go p.sendWebhookWithRetry(webhookUrl, payload, 5, 30*time.Second, userID)
}
return nil
}
func (p *webhookProducer) sendWebhookWithRetry(url string, body []byte, maxRetries int, retryInterval time.Duration, userID string) {
for i := 0; i < maxRetries; i++ {
err, responseBody, statusCode := p.sendWebhook(url, body, userID)
if err == nil {
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] webhook sent successfully - url: %s, status: %d, response: %s", userID, url, statusCode, string(responseBody))
return
}
p.loggerWrapper.GetLogger(userID).LogWarn("[%s] webhook failed - url: %s, attempt: %d, error: %v", userID, url, i+1, err)
time.Sleep(retryInterval)
}
p.loggerWrapper.GetLogger(userID).LogError("[%s] webhook failed after maximum retries - url: %s", userID, url)
}
func (p *webhookProducer) sendWebhook(url string, body []byte, userID string) (error, []byte, int) {
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
return err, nil, 0
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err, nil, 0
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("erro ao ler resposta: %v", err), nil, 0
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return errors.New("received non-2xx response: " + resp.Status), responseBody, resp.StatusCode
}
return nil, responseBody, resp.StatusCode
}
// CreateGlobalQueues não faz nada para webhook producer
func (p *webhookProducer) CreateGlobalQueues() error {
return nil
}
+140
View File
@@ -0,0 +1,140 @@
package websocket_producer
import (
"net/http"
"strings"
"sync"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/gomessguii/logger"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
logger.LogInfo("Verificando origem da conexão WebSocket")
return true
},
}
type websocketProducer struct {
clients map[string]*websocket.Conn // conexões específicas por instância
broadcast []*websocket.Conn // conexões que recebem todos os eventos
clientsMux sync.RWMutex
loggerWrapper *logger_wrapper.LoggerManager
}
func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {
return &websocketProducer{
clients: make(map[string]*websocket.Conn),
broadcast: make([]*websocket.Conn, 0),
clientsMux: sync.RWMutex{},
loggerWrapper: loggerWrapper,
}
}
// ServeWs lida com as requisições de upgrade para websocket
func ServeWs(w http.ResponseWriter, r *http.Request, instanceId string, producer *websocketProducer) {
logger.LogInfo("Iniciando upgrade da conexão WebSocket")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)
return
}
logger.LogInfo("Conexão WebSocket estabelecida com sucesso")
if instanceId == "" {
producer.AddBroadcastClient(conn)
} else {
producer.AddClient(instanceId, conn)
}
// Goroutine para limpar conexão quando fechada
go func() {
for {
_, _, err := conn.ReadMessage()
if err != nil {
if instanceId == "" {
producer.RemoveBroadcastClient(conn)
} else {
producer.RemoveClient(instanceId)
}
conn.Close()
break
}
}
}()
}
func (p *websocketProducer) AddBroadcastClient(conn *websocket.Conn) {
p.clientsMux.Lock()
defer p.clientsMux.Unlock()
p.broadcast = append(p.broadcast, conn)
logger.LogInfo("Cliente broadcast websocket adicionado")
}
func (p *websocketProducer) RemoveBroadcastClient(conn *websocket.Conn) {
p.clientsMux.Lock()
defer p.clientsMux.Unlock()
for i, c := range p.broadcast {
if c == conn {
p.broadcast = append(p.broadcast[:i], p.broadcast[i+1:]...)
break
}
}
logger.LogInfo("Cliente broadcast websocket removido")
}
func (p *websocketProducer) AddClient(instanceID string, conn *websocket.Conn) {
p.clientsMux.Lock()
defer p.clientsMux.Unlock()
p.clients[instanceID] = conn
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket adicionado para instância: %s", instanceID)
}
func (p *websocketProducer) RemoveClient(instanceID string) {
p.clientsMux.Lock()
defer p.clientsMux.Unlock()
delete(p.clients, instanceID)
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket removido para instância: %s", instanceID)
}
func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error {
message := map[string]interface{}{
"queue": strings.ToLower(queueName),
"payload": string(payload),
}
p.clientsMux.RLock()
defer p.clientsMux.RUnlock()
// Envia para cliente específico da instância
if client, exists := p.clients[instanceID]; exists {
err := client.WriteJSON(message)
if err != nil {
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
// Não remove o cliente aqui pois estamos com o RLock
return err
}
p.loggerWrapper.GetLogger(instanceID).LogInfo("Mensagem websocket enviada com sucesso para instância %s na fila %s", instanceID, queueName)
}
// Envia para todos os clientes broadcast
for _, conn := range p.broadcast {
err := conn.WriteJSON(message)
if err != nil {
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem broadcast websocket: %v", err)
continue
}
}
return nil
}
// CreateGlobalQueues não faz nada para websocket producer
func (p *websocketProducer) CreateGlobalQueues() error {
return nil
}
+486
View File
@@ -0,0 +1,486 @@
package group_handler
import (
"net/http"
group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
type GroupHandler interface {
ListGroups(ctx *gin.Context)
GetGroupInfo(ctx *gin.Context)
GetGroupInviteLink(ctx *gin.Context)
SetGroupPhoto(ctx *gin.Context)
SetGroupName(ctx *gin.Context)
SetGroupDescription(ctx *gin.Context)
CreateGroup(ctx *gin.Context)
UpdateParticipant(ctx *gin.Context)
GetMyGroups(ctx *gin.Context)
JoinGroupLink(ctx *gin.Context)
LeaveGroup(ctx *gin.Context)
}
type groupHandler struct {
groupService group_service.GroupService
}
// List groups
// @Summary List groups
// @Description List groups
// @Tags Group
// @Accept json
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/list [get]
func (g *groupHandler) ListGroups(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
}
resp, err := g.groupService.ListGroups(instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Get group info
// @Summary Get group info
// @Description Get group info
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.GetGroupInfoStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/info [post]
func (g *groupHandler) GetGroupInfo(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 *group_service.GetGroupInfoStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
return
}
resp, err := g.groupService.GetGroupInfo(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Get group invite link
// @Summary Get group invite link
// @Description Get group invite link
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.GetGroupInviteLinkStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/invitelink [post]
func (g *groupHandler) GetGroupInviteLink(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 *group_service.GetGroupInviteLinkStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
return
}
resp, err := g.groupService.GetGroupInviteLink(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Set group photo
// @Summary Set group photo
// @Description Set group photo
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.SetGroupPhotoStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/photo [post]
func (g *groupHandler) SetGroupPhoto(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 *group_service.SetGroupPhotoStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
return
}
if data.Image == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image is required"})
return
}
resp, err := g.groupService.SetGroupPhoto(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Set group name
// @Summary Set group name
// @Description Set group name
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.SetGroupNameStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/name [post]
func (g *groupHandler) SetGroupName(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 *group_service.SetGroupNameStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
return
}
if data.Name == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
return
}
err = g.groupService.SetGroupName(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Set group description
// @Summary Set group description
// @Description Set group description
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.SetGroupDescriptionStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/description [post]
func (g *groupHandler) SetGroupDescription(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 *group_service.SetGroupDescriptionStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
return
}
// Description can be empty to clear the group description
// No validation needed for Description field
err = g.groupService.SetGroupDescription(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Create group
// @Summary Create group
// @Description Create group
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.CreateGroupStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/create [post]
func (g *groupHandler) CreateGroup(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 *group_service.CreateGroupStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupName == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupName is required"})
return
}
if len(data.Participants) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})
return
}
group, err := g.groupService.CreateGroup(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": group})
}
// Update participant
// @Summary Update participant
// @Description Update participant
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.AddParticipantStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/participant [post]
func (g *groupHandler) UpdateParticipant(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 *group_service.AddParticipantStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID.String() == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
return
}
if data.Action == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "action is required"})
return
}
if len(data.Participants) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})
return
}
err = g.groupService.UpdateParticipant(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Get my groups
// @Summary Get my groups
// @Description Get my groups
// @Tags Group
// @Accept json
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/myall [get]
func (g *groupHandler) GetMyGroups(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
}
groups, err := g.groupService.GetMyGroups(instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": groups})
}
// Join group link
// @Summary Join group link
// @Description Join group link
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.JoinGroupStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/join [post]
func (g *groupHandler) JoinGroupLink(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 *group_service.JoinGroupStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Code == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "code is required"})
return
}
err = g.groupService.JoinGroupLink(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Leave group
// @Summary Leave group
// @Description Leave group
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.LeaveGroupStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/leave [post]
func (g *groupHandler) LeaveGroup(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 *group_service.LeaveGroupStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID.String() == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
return
}
err = g.groupService.LeaveGroup(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
func NewGroupHandler(
groupService group_service.GroupService,
) GroupHandler {
return &groupHandler{
groupService: groupService,
}
}
+654
View File
@@ -0,0 +1,654 @@
package group_service
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"github.com/gin-gonic/gin"
"github.com/vincent-petithory/dataurl"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
)
type GroupService interface {
ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error)
GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error)
GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error)
SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error)
SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error
SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error
CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error)
UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error
UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error
GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error)
UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error)
GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error)
JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error
LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error
}
type groupService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type SimpleGroupInfo struct {
JID types.JID `json:"jid"`
GroupName string `json:"groupName"`
}
type GroupCollection struct {
Groups []SimpleGroupInfo
}
type GetGroupInfoStruct struct {
GroupJID string `json:"groupJid"`
}
type GetGroupInviteLinkStruct struct {
GroupJID string `json:"groupJid"`
Reset bool `json:"reset"`
}
type SetGroupPhotoStruct struct {
GroupJID string `json:"groupJid"`
Image string `json:"image"`
}
type SetGroupNameStruct struct {
GroupJID string `json:"groupJid"`
Name string `json:"name"`
}
type SetGroupDescriptionStruct struct {
GroupJID string `json:"groupJid"`
Description string `json:"description"`
}
type CreateGroupStruct struct {
GroupName string `json:"groupName"`
Participants []string `json:"participants"`
}
type AddParticipantStruct struct {
GroupJID types.JID `json:"groupJid"`
Participants []string `json:"participants"`
Action whatsmeow.ParticipantChange `json:"action"`
}
type JoinGroupStruct struct {
Code string `json:"code"`
}
type LeaveGroupStruct struct {
GroupJID types.JID `json:"groupJid"`
}
type UpdateGroupSettingsStruct struct {
GroupJID string `json:"groupJid"`
Action string `json:"action"` // announcement, not_announcement, locked, unlocked
}
type GetGroupRequestParticipantsStruct struct {
GroupJID string `json:"groupJid"`
}
// Estrutura enriquecida com PushName
type EnrichedGroupParticipantRequest struct {
JID types.JID `json:"JID"`
RequestedAt time.Time `json:"RequestedAt"`
PushName string `json:"PushName"`
}
type UpdateGroupRequestParticipantsStruct struct {
GroupJID string `json:"groupJid"`
Action string `json:"action"` // approve, reject
Participants []string `json:"participants"`
}
func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := g.clientPointer[instanceId]
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := g.whatsmeowService.StartInstance(instanceId)
if err != nil {
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = g.clientPointer[instanceId]
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
g.loggerWrapper.GetLogger(instanceId).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() {
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (g *groupService) ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
resp, err := client.GetJoinedGroups(context.Background())
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting groups: %v", instance.Id, err)
return nil, err
}
gc := new(GroupCollection)
for _, info := range resp {
simpleGroup := SimpleGroupInfo{
JID: info.JID,
GroupName: info.GroupName.Name,
}
gc.Groups = append(gc.Groups, simpleGroup)
}
return resp, nil
}
func (g *groupService) GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return nil, errors.New("invalid group jid")
}
resp, err := client.GetGroupInfo(context.Background(), recipient)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
return nil, err
}
return resp, nil
}
func (g *groupService) GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid group jid")
}
resp, err := client.GetGroupInviteLink(context.Background(), recipient, data.Reset)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
return "", err
}
return resp, nil
}
func (g *groupService) SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid group jid")
}
var fileData []byte
if strings.HasPrefix(data.Image, "http://") || strings.HasPrefix(data.Image, "https://") {
resp, err := http.Get(data.Image)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not download image from URL", instance.Id)
return "", fmt.Errorf("failed to fetch image from URL: %v", err)
}
defer resp.Body.Close()
fileData, err = io.ReadAll(resp.Body)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not read image data from URL", instance.Id)
return "", fmt.Errorf("failed to read image data: %v", err)
}
} else if strings.HasPrefix(data.Image, "data:image/jpeg;base64,") || strings.HasPrefix(data.Image, "data:image/png;base64,") {
dataURL, err := dataurl.DecodeString(data.Image)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not decode base64 encoded data from payload", instance.Id)
return "", err
}
fileData = dataURL.Data
} else {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Image data should start with \"data:image/jpeg;base64,\" or be a valid URL", instance.Id)
return "", errors.New("image data should be a valid URL or start with \"data:image/jpeg;base64,\"")
}
pictureID, err := client.SetGroupPhoto(context.Background(), recipient, fileData)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error setting group photo: %v", instance.Id, err)
return "", err
}
return pictureID, nil
}
func (g *groupService) SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return errors.New("invalid group jid")
}
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group name for %s", instance.Id, recipient.String())
err = client.SetGroupName(context.Background(), recipient, data.Name)
if err != nil {
// Log mais detalhado para erro 409
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting name. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)
}
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group name: %v", instance.Id, err)
return err
}
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group name set successfully", instance.Id)
return nil
}
func (g *groupService) SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return errors.New("invalid group jid")
}
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group description for %s", instance.Id, recipient.String())
// Use SetGroupTopic instead of SetGroupDescription (proper WhatsApp method)
// Empty strings for previousID and newID will be auto-filled by the library
err = client.SetGroupTopic(context.Background(), recipient, "", "", data.Description)
if err != nil {
// Log mais detalhado para erro 409
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting description. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)
}
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group description: %v", instance.Id, err)
return err
}
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group description set successfully", instance.Id)
return nil
}
func (g *groupService) CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
var participants []types.JID
for _, participant := range data.Participants {
recipient, ok := utils.ParseJID(participant)
participants = append(participants, recipient)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return nil, errors.New("invalid phone number")
}
}
resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{
Name: data.GroupName,
Participants: participants,
})
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
return nil, err
}
var failed []types.JID
for _, participant := range resp.Participants {
if participant.Error != 0 {
failed = append(failed, participant.JID)
}
}
var added []types.JID
infoResp, err := client.GetGroupInfo(context.Background(), resp.JID)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error get group info: %v", instance.Id, err)
return nil, err
}
for _, add := range infoResp.Participants {
added = append(added, add.JID)
}
response := gin.H{
"jid": resp.JID,
"name": resp.Name,
"owner": resp.OwnerJID,
"added": added,
"failed": failed,
}
return response, nil
}
func (g *groupService) UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return err
}
var participants []types.JID
for _, participant := range data.Participants {
recipient, ok := utils.ParseJID(participant)
participants = append(participants, recipient)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return errors.New("invalid phone number")
}
}
_, err = client.UpdateGroupParticipants(context.Background(), data.GroupJID, participants, data.Action)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
return err
}
return nil
}
func (g *groupService) GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
resp, err := client.GetJoinedGroups(context.Background())
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
return nil, err
}
var jid string = client.Store.ID.String()
var jidClear = strings.Split(jid, ".")[0]
jidOfAdmin, ok := utils.ParseJID(jidClear)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return nil, errors.New("invalid phone number")
}
var adminGroups []types.GroupInfo
for _, group := range resp {
if group.OwnerJID == jidOfAdmin {
adminGroups = append(adminGroups, *group)
_ = adminGroups
}
}
return adminGroups, nil
}
func (g *groupService) JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return err
}
_, err = client.JoinGroupWithLink(context.Background(), data.Code)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
return err
}
return nil
}
func (g *groupService) LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return err
}
err = client.LeaveGroup(context.Background(), data.GroupJID)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error leave group: %v", instance.Id, err)
return err
}
return nil
}
func (g *groupService) UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
return errors.New("invalid group jid")
}
// Validate action
validActions := map[string]bool{
"announcement": true,
"not_announcement": true,
"locked": true,
"unlocked": true,
"approval_on": true,
"approval_off": true,
"admin_add": true,
"all_member_add": true,
}
if !validActions[data.Action] {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)
return errors.New("invalid action. Valid actions: announcement, not_announcement, locked, unlocked, approval_on, approval_off, admin_add, all_member_add")
}
// Apply settings based on action
switch data.Action {
case "announcement":
err = client.SetGroupAnnounce(context.Background(), recipient, true)
case "not_announcement":
err = client.SetGroupAnnounce(context.Background(), recipient, false)
case "locked":
err = client.SetGroupLocked(context.Background(), recipient, true)
case "unlocked":
err = client.SetGroupLocked(context.Background(), recipient, false)
case "approval_on":
err = client.SetGroupJoinApprovalMode(context.Background(), recipient, true)
case "approval_off":
err = client.SetGroupJoinApprovalMode(context.Background(), recipient, false)
case "admin_add":
err = client.SetGroupMemberAddMode(context.Background(), recipient, "admin_add")
case "all_member_add":
err = client.SetGroupMemberAddMode(context.Background(), recipient, "all_member_add")
}
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group settings: %v", instance.Id, err)
return err
}
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group settings updated successfully: %s", instance.Id, data.Action)
return nil
}
func (g *groupService) GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
return nil, errors.New("invalid group jid")
}
requests, err := client.GetGroupRequestParticipants(context.Background(), recipient)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting group request participants: %v", instance.Id, err)
return nil, err
}
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Retrieved %d pending group requests", instance.Id, len(requests))
// Enriquecer com informações de usuário (PushName)
enrichedRequests := make([]EnrichedGroupParticipantRequest, len(requests))
jidsToFetch := make([]types.JID, 0, len(requests))
for _, req := range requests {
if req.JID.User != "" {
jidsToFetch = append(jidsToFetch, req.JID)
}
}
// Buscar informações de usuário em lote
userInfoMap := make(map[types.JID]types.UserInfo)
if len(jidsToFetch) > 0 {
userInfoMap, err = client.GetUserInfo(context.Background(), jidsToFetch)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Could not fetch user info: %v", instance.Id, err)
// Continuar sem pushName se falhar
}
}
// Montar resposta enriquecida
for i, req := range requests {
enrichedRequests[i] = EnrichedGroupParticipantRequest{
JID: req.JID,
RequestedAt: req.RequestedAt,
PushName: "",
}
// Tentar obter PushName
lookupJID := req.JID
if userInfo, found := userInfoMap[lookupJID]; found {
// VerifiedName é ponteiro, verificar se não é nil
if userInfo.VerifiedName != nil && userInfo.VerifiedName.Details.GetVerifiedName() != "" {
enrichedRequests[i].PushName = userInfo.VerifiedName.Details.GetVerifiedName()
}
}
// Tentar obter do store de contatos se não tiver VerifiedName
if enrichedRequests[i].PushName == "" && client.Store.Contacts != nil {
if contactInfo, err := client.Store.Contacts.GetContact(context.Background(), lookupJID); err == nil && contactInfo.PushName != "" {
enrichedRequests[i].PushName = contactInfo.PushName
} else if contactInfo.FullName != "" {
enrichedRequests[i].PushName = contactInfo.FullName
}
}
}
return enrichedRequests, nil
}
func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error) {
client, err := g.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
recipient, ok := utils.ParseJID(data.GroupJID)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
return nil, errors.New("invalid group jid")
}
// Validate action
var action whatsmeow.ParticipantRequestChange
switch data.Action {
case "approve":
action = whatsmeow.ParticipantChangeApprove
case "reject":
action = whatsmeow.ParticipantChangeReject
default:
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)
return nil, errors.New("invalid action. Valid actions: approve, reject")
}
// Parse participants JIDs
var participants []types.JID
for _, participant := range data.Participants {
participantJID, ok := utils.ParseJID(participant)
if !ok {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating participant jid: %s", instance.Id, participant)
return nil, errors.New("invalid participant jid: " + participant)
}
participants = append(participants, participantJID)
}
results, err := client.UpdateGroupRequestParticipants(context.Background(), recipient, participants, action)
if err != nil {
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group request participants: %v", instance.Id, err)
return nil, err
}
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Successfully %sd %d participants", instance.Id, data.Action, len(participants))
return results, nil
}
func NewGroupService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) GroupService {
return &groupService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}
+644
View File
@@ -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}
}
+53
View File
@@ -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,
}
}
+854
View File
@@ -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,
}
}
+55
View File
@@ -0,0 +1,55 @@
package event_types
const (
ALL = "ALL"
MESSAGE = "MESSAGE"
SEND_MESSAGE = "SEND_MESSAGE"
READ_RECEIPT = "READ_RECEIPT"
PRESENCE = "PRESENCE"
HISTORY_SYNC = "HISTORY_SYNC"
CHAT_PRESENCE = "CHAT_PRESENCE"
CALL = "CALL"
CONNECTION = "CONNECTION"
LABEL = "LABEL"
CONTACT = "CONTACT"
GROUP = "GROUP"
NEWSLETTER = "NEWSLETTER"
QRCODE = "QRCODE"
)
var AllEventTypes = []string{
MESSAGE,
SEND_MESSAGE,
READ_RECEIPT,
PRESENCE,
HISTORY_SYNC,
CHAT_PRESENCE,
CALL,
CONNECTION,
LABEL,
CONTACT,
GROUP,
NEWSLETTER,
QRCODE,
}
var validEventTypes = map[string]bool{
ALL: true,
MESSAGE: true,
SEND_MESSAGE: true,
READ_RECEIPT: true,
PRESENCE: true,
HISTORY_SYNC: true,
CHAT_PRESENCE: true,
CALL: true,
CONNECTION: true,
LABEL: true,
CONTACT: true,
GROUP: true,
NEWSLETTER: true,
QRCODE: true,
}
func IsEventType(eventType string) bool {
return validEventTypes[eventType]
}
+297
View File
@@ -0,0 +1,297 @@
package label_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service"
"github.com/gin-gonic/gin"
)
type LabelHandler interface {
ChatLabel(ctx *gin.Context)
MessageLabel(ctx *gin.Context)
EditLabel(ctx *gin.Context)
ChatUnlabel(ctx *gin.Context)
MessageUnlabel(ctx *gin.Context)
GetLabels(ctx *gin.Context)
}
type labelHandler struct {
labelService label_service.LabelService
}
// Add label to chat
// @Summary Add label to chat
// @Description Add label to chat
// @Tags Label
// @Accept json
// @Produce json
// @Param message body label_service.ChatLabelStruct true "Label data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /label/chat [post]
func (l *labelHandler) ChatLabel(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 *label_service.ChatLabelStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.JID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
return
}
if data.LabelID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
return
}
err = l.labelService.ChatLabel(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Add label to message
// @Summary Add label to message
// @Description Add label to message
// @Tags Label
// @Accept json
// @Produce json
// @Param message body label_service.MessageLabelStruct true "Label data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /label/message [post]
func (l *labelHandler) MessageLabel(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 *label_service.MessageLabelStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.JID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
return
}
if data.LabelID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
return
}
if data.MessageID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message id is required"})
return
}
err = l.labelService.MessageLabel(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Edit label
// @Summary Edit label
// @Description Edit label
// @Tags Label
// @Accept json
// @Produce json
// @Param message body label_service.EditLabelStruct true "Label data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /label/edit [post]
func (l *labelHandler) EditLabel(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 *label_service.EditLabelStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.LabelID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
return
}
if data.Name == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
return
}
err = l.labelService.EditLabel(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Remove label from chat
// @Summary Remove label from chat
// @Description Remove label from chat
// @Tags Label
// @Accept json
// @Produce json
// @Param message body label_service.ChatLabelStruct true "Label data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /unlabel/chat [post]
func (l *labelHandler) ChatUnlabel(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 *label_service.ChatLabelStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.JID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
return
}
if data.LabelID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
return
}
err = l.labelService.ChatUnlabel(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Remove label from message
// @Summary Remove label from message
// @Description Remove label from message
// @Tags Label
// @Accept json
// @Produce json
// @Param message body label_service.MessageLabelStruct true "Label data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /unlabel/message [post]
func (l *labelHandler) MessageUnlabel(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 *label_service.MessageLabelStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.JID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
return
}
if data.LabelID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
return
}
if data.MessageID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message id is required"})
return
}
err = l.labelService.MessageUnlabel(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Get all labels
// @Summary Get all labels
// @Description Get all labels
// @Tags Label
// @Accept json
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /label [get]
func (l *labelHandler) GetLabels(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
}
labels, err := l.labelService.GetLabels(instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, labels)
}
func NewLabelHandler(
labelService label_service.LabelService,
) LabelHandler {
return &labelHandler{
labelService: labelService,
}
}
+20
View File
@@ -0,0 +1,20 @@
package label_model
import (
"github.com/google/uuid"
"gorm.io/gorm"
)
type Label struct {
Id string `json:"id" gorm:"type:uuid;primaryKey"`
InstanceID string `json:"instance_id" gorm:"type:uuid"`
LabelID string `json:"label_id"`
LabelName string `json:"label_name"`
LabelColor string `json:"label_color"`
PredefinedId string `json:"predefined_id"`
}
func (m *Label) BeforeCreate(tx *gorm.DB) (err error) {
m.Id = uuid.New().String()
return
}
+71
View File
@@ -0,0 +1,71 @@
package label_repository
import (
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type LabelRepository interface {
InsertLabel(label label_model.Label) error
UpdateLabel(label label_model.Label) error
GetLabelByID(id string) (*label_model.Label, error)
DeleteLabel(id string) error
GetAllLabelsByInstanceID(instanceID string) ([]label_model.Label, error)
UpsertLabel(label label_model.Label) error
}
type labelRepository struct {
db *gorm.DB
}
func (l *labelRepository) InsertLabel(label label_model.Label) error {
return l.db.Create(&label).Error
}
func (l *labelRepository) UpdateLabel(label label_model.Label) error {
return l.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.AssignmentColumns([]string{"label_id", "label_name", "label_color"}),
}).Create(&label).Error
}
func (l *labelRepository) GetLabelByID(id string) (*label_model.Label, error) {
var label label_model.Label
err := l.db.Where("id = ?", id).First(&label).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
return &label, nil
}
func (l *labelRepository) DeleteLabel(id string) error {
return l.db.Where("id = ?", id).Delete(&label_model.Label{}).Error
}
func (l *labelRepository) GetAllLabelsByInstanceID(instanceID string) ([]label_model.Label, error) {
var labels []label_model.Label
err := l.db.Where("instance_id = ?", instanceID).Find(&labels).Error
if err != nil {
return nil, err
}
return labels, nil
}
func (l *labelRepository) UpsertLabel(label label_model.Label) error {
return l.db.Where("instance_id = ? AND label_id = ?",
label.InstanceID,
label.LabelID,
).Assign(label_model.Label{
LabelName: label.LabelName,
LabelColor: label.LabelColor,
PredefinedId: label.PredefinedId,
}).FirstOrCreate(&label).Error
}
func NewLabelRepository(db *gorm.DB) LabelRepository {
return &labelRepository{db: db}
}
+240
View File
@@ -0,0 +1,240 @@
package label_service
import (
"context"
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/appstate"
)
type LabelService interface {
ChatLabel(data *ChatLabelStruct, instance *instance_model.Instance) error
MessageLabel(data *MessageLabelStruct, instance *instance_model.Instance) error
EditLabel(data *EditLabelStruct, instance *instance_model.Instance) error
ChatUnlabel(data *ChatLabelStruct, instance *instance_model.Instance) error
MessageUnlabel(data *MessageLabelStruct, instance *instance_model.Instance) error
GetLabels(instance *instance_model.Instance) ([]label_model.Label, error)
}
type labelService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
labelRepository label_repository.LabelRepository
loggerWrapper *logger_wrapper.LoggerManager
}
type ChatLabelStruct struct {
JID string `json:"jid"`
LabelID string `json:"labelId"`
}
type MessageLabelStruct struct {
JID string `json:"jid"`
LabelID string `json:"labelId"`
MessageID string `json:"messageId"`
}
type EditLabelStruct struct {
LabelID string `json:"labelId"`
Name string `json:"name"`
Color int `json:"color"`
Deleted bool `json:"deleted"`
}
func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := l.clientPointer[instanceId]
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := l.whatsmeowService.StartInstance(instanceId)
if err != nil {
l.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = l.clientPointer[instanceId]
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
l.loggerWrapper.GetLogger(instanceId).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() {
l.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (l *labelService) ChatLabel(data *ChatLabelStruct, instance *instance_model.Instance) error {
client, err := l.ensureClientConnected(instance.Id)
if err != nil {
return err
}
jid, ok := utils.ParseJID(data.JID)
if !ok {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return errors.New("error parse community jid")
}
err = client.SendAppState(context.Background(), appstate.BuildLabelChat(
jid,
data.LabelID,
true,
))
if err != nil {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label chat: %v", instance.Id, err)
return err
}
return nil
}
func (l *labelService) MessageLabel(data *MessageLabelStruct, instance *instance_model.Instance) error {
client, err := l.ensureClientConnected(instance.Id)
if err != nil {
return err
}
jid, ok := utils.ParseJID(data.JID)
if !ok {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return errors.New("error parse community jid")
}
err = client.SendAppState(context.Background(), appstate.BuildLabelMessage(
jid,
data.LabelID,
data.MessageID,
true,
))
if err != nil {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)
return err
}
return nil
}
func (l *labelService) EditLabel(data *EditLabelStruct, instance *instance_model.Instance) error {
client, err := l.ensureClientConnected(instance.Id)
if err != nil {
return err
}
err = client.SendAppState(context.Background(), appstate.BuildLabelEdit(
data.LabelID,
data.Name,
int32(data.Color),
data.Deleted,
))
if err != nil {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)
return err
}
return nil
}
func (l *labelService) ChatUnlabel(data *ChatLabelStruct, instance *instance_model.Instance) error {
client, err := l.ensureClientConnected(instance.Id)
if err != nil {
return err
}
jid, ok := utils.ParseJID(data.JID)
if !ok {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return errors.New("error parse community jid")
}
err = client.SendAppState(context.Background(), appstate.BuildLabelChat(
jid,
data.LabelID,
false,
))
if err != nil {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label chat: %v", instance.Id, err)
return err
}
return nil
}
func (l *labelService) MessageUnlabel(data *MessageLabelStruct, instance *instance_model.Instance) error {
client, err := l.ensureClientConnected(instance.Id)
if err != nil {
return err
}
jid, ok := utils.ParseJID(data.JID)
if !ok {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return errors.New("error parse community jid")
}
err = client.SendAppState(context.Background(), appstate.BuildLabelMessage(
jid,
data.LabelID,
data.MessageID,
false,
))
if err != nil {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)
return err
}
return nil
}
func (l *labelService) GetLabels(instance *instance_model.Instance) ([]label_model.Label, error) {
_, err := l.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
labels, err := l.labelRepository.GetAllLabelsByInstanceID(instance.Id)
if err != nil {
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error fetching labels from database: %v", instance.Id, err)
return nil, err
}
return labels, nil
}
func NewLabelService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
labelRepository label_repository.LabelRepository,
loggerWrapper *logger_wrapper.LoggerManager,
) LabelService {
return &labelService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
labelRepository: labelRepository,
loggerWrapper: loggerWrapper,
}
}
+146
View File
@@ -0,0 +1,146 @@
package logger
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/EvolutionAPI/evolution-go/pkg/config"
"github.com/gomessguii/logger"
"gopkg.in/natefinch/lumberjack.v2"
)
type LoggerManager struct {
config *config.Config
loggers map[string]*Logger
mu sync.RWMutex
}
type Logger struct {
config *config.Config
instanceId string
mu sync.Mutex
writer *lumberjack.Logger
}
type LogEntry struct {
Timestamp time.Time `json:"timestamp"`
Level string `json:"level"`
InstanceId string `json:"instance_id"`
Message string `json:"message"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
func NewLoggerManager(config *config.Config) *LoggerManager {
// Garante que o diretório base de logs existe
if err := os.MkdirAll(config.LogDirectory, 0755); err != nil {
logger.LogError("Falha ao criar diretório base de logs: %v", err)
}
return &LoggerManager{
config: config,
loggers: make(map[string]*Logger),
}
}
func (lm *LoggerManager) GetLogger(instanceId string) *Logger {
lm.mu.RLock()
logger, exists := lm.loggers[instanceId]
lm.mu.RUnlock()
if exists {
return logger
}
lm.mu.Lock()
defer lm.mu.Unlock()
// Verificar novamente após obter o lock de escrita
if logger, exists = lm.loggers[instanceId]; exists {
return logger
}
// Criar novo logger para a instância
logger = newLogger(instanceId, lm.config)
lm.loggers[instanceId] = logger
return logger
}
func newLogger(instanceId string, config *config.Config) *Logger {
// Garante que o diretório existe
logPath := filepath.Join(config.LogDirectory, instanceId)
os.MkdirAll(logPath, 0755)
logFile := filepath.Join(logPath, "instance.log")
writer := &lumberjack.Logger{
Filename: logFile,
MaxSize: config.LogMaxSize,
MaxBackups: config.LogMaxBackups,
MaxAge: config.LogMaxAge,
Compress: config.LogCompress,
}
return &Logger{
config: config,
instanceId: instanceId,
writer: writer,
}
}
func (l *Logger) LogInfo(format string, args ...interface{}) {
l.log("INFO", format, args...)
logger.LogInfo(format, args...)
}
func (l *Logger) LogError(format string, args ...interface{}) {
l.log("ERROR", format, args...)
logger.LogError(format, args...)
}
func (l *Logger) LogWarn(format string, args ...interface{}) {
l.log("WARN", format, args...)
logger.LogWarn(format, args...)
}
func (l *Logger) LogDebug(format string, args ...interface{}) {
l.log("DEBUG", format, args...)
logger.LogDebug(format, args...)
}
func (l *Logger) log(level string, format string, args ...interface{}) {
l.mu.Lock()
defer l.mu.Unlock()
entry := LogEntry{
Timestamp: time.Now(),
Level: level,
InstanceId: l.instanceId,
Message: fmt.Sprintf(format, args...),
}
jsonEntry, err := json.Marshal(entry)
if err != nil {
logger.LogError("Failed to marshal log entry: %v", err)
return
}
if _, err := l.writer.Write(append(jsonEntry, '\n')); err != nil {
logger.LogError("Failed to write log: %v", err)
}
}
func (l *Logger) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
return l.writer.Close()
}
// GetLogs retorna os logs da instância com filtros opcionais
func (l *Logger) GetLogs(startDate, endDate time.Time, level string, limit int) ([]LogEntry, error) {
// Implementação movida para o service
return nil, fmt.Errorf("método movido para instance_service")
}
+371
View File
@@ -0,0 +1,371 @@
package message_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service"
"github.com/gin-gonic/gin"
)
type MessageHandler interface {
React(ctx *gin.Context)
ChatPresence(ctx *gin.Context)
MarkRead(ctx *gin.Context)
DownloadMedia(ctx *gin.Context)
GetMessageStatus(ctx *gin.Context)
DeleteMessageEveryone(ctx *gin.Context)
EditMessage(ctx *gin.Context)
}
type messageHandler struct {
messageService message_service.MessageService
}
// React a message
// @Summary React a message
// @Description React to a message with support for fromMe field and participant field for group messages
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.ReactStruct true "React to a message with fromMe and participant fields"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/react [post]
func (m *messageHandler) React(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 *message_service.ReactStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Reaction == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message reaction is required"})
return
}
message, err := m.messageService.React(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// ChatPresence set chat presence
// @Summary Set chat presence
// @Description Set chat presence
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.ChatPresenceStruct true "Set chat presence"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/presence [post]
func (m *messageHandler) ChatPresence(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 *message_service.ChatPresenceStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.State == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "state is required"})
return
}
ts, err := m.messageService.ChatPresence(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// MarkRead mark a message as read
// @Summary Mark a message as read
// @Description Mark a message as read
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.MarkReadStruct true "Mark a message as read"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/markread [post]
func (m *messageHandler) MarkRead(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 *message_service.MarkReadStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if len(data.Id) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
return
}
ts, err := m.messageService.MarkRead(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// DownloadImage download an image
// @Summary Download an image
// @Description Download an image
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.DownloadImageStruct true "Download an image"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/downloadimage [post]
func (m *messageHandler) DownloadMedia(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 *message_service.DownloadMediaStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
dataUrl, ts, err := m.messageService.DownloadMedia(data, instance, ctx.Request)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"base64": dataUrl.String(),
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// GetMessageStatus get message status
// @Summary Get message status
// @Description Get message status
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.MessageStatusStruct true "Get message status"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/status [post]
func (m *messageHandler) GetMessageStatus(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 *message_service.MessageStatusStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Id == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
return
}
message, ts, err := m.messageService.GetMessageStatus(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"result": message,
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// DeleteMessageEveryone delete a message for everyone
// @Summary Delete a message for everyone
// @Description Delete a message for everyone
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.MessageStruct true "Delete a message for everyone"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/delete [post]
func (m *messageHandler) DeleteMessageEveryone(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 *message_service.MessageStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
if data.MessageID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "messageId is required"})
return
}
msgId, ts, err := m.messageService.DeleteMessageEveryone(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"messageId": msgId,
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// EditMessage edit a message
// @Summary Edit a message
// @Description Edit a message
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.EditMessageStruct true "Edit a message"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/edit [post]
func (m *messageHandler) EditMessage(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 *message_service.EditMessageStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Chat == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
return
}
if data.Message == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message is required"})
return
}
if data.MessageID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "messageId is required"})
return
}
msgId, ts, err := m.messageService.EditMessage(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"messageId": msgId,
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
func NewMessageHandler(
messageService message_service.MessageService,
) MessageHandler {
return &messageHandler{
messageService: messageService,
}
}
+19
View File
@@ -0,0 +1,19 @@
package message_model
import (
"github.com/google/uuid"
"gorm.io/gorm"
)
type Message struct {
Id string `json:"id" gorm:"type:uuid;primaryKey"`
MessageID string `json:"message_id" gorm:"unique"`
Timestamp string `json:"timestamp"`
Status string `json:"status"`
Source string `json:"source"`
}
func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {
m.Id = uuid.New().String()
return
}
@@ -0,0 +1,60 @@
package message_repository
import (
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type MessageRepository interface {
InsertMessage(message message_model.Message) error
GetMessageByID(messageID string) (*message_model.Message, error)
DeleteAllMessages() (int64, error)
GetLatestMessageID(source string) (string, string, error)
}
type messageRepository struct {
db *gorm.DB
}
func (m *messageRepository) InsertMessage(message message_model.Message) error {
return m.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "message_id"}},
DoUpdates: clause.AssignmentColumns([]string{"timestamp", "status", "source"}),
}).Create(&message).Error
}
func (m *messageRepository) GetMessageByID(messageID string) (*message_model.Message, error) {
var message message_model.Message
err := m.db.Where("message_id = ?", messageID).First(&message).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
return &message, nil
}
func (m *messageRepository) DeleteAllMessages() (int64, error) {
result := m.db.Exec("DELETE FROM messages")
return result.RowsAffected, result.Error
}
func (m *messageRepository) GetLatestMessageID(source string) (string, string, error) {
var message message_model.Message
err := m.db.Where("source = ?", source).Order("timestamp DESC").First(&message).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return "", "", nil
}
return "", "", err
}
return message.MessageID, message.Timestamp, nil
}
func NewMessageRepository(db *gorm.DB) MessageRepository {
return &messageRepository{db: db}
}
+440
View File
@@ -0,0 +1,440 @@
package message_service
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"github.com/vincent-petithory/dataurl"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waCommon"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
"google.golang.org/protobuf/proto"
)
type MessageService interface {
React(data *ReactStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
ChatPresence(data *ChatPresenceStruct, instance *instance_model.Instance) (string, error)
MarkRead(data *MarkReadStruct, instance *instance_model.Instance) (string, error)
DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error)
GetMessageStatus(data *MessageStatusStruct, instance *instance_model.Instance) (*message_model.Message, string, error)
DeleteMessageEveryone(data *MessageStruct, instance *instance_model.Instance) (string, string, error)
EditMessage(data *EditMessageStruct, instance *instance_model.Instance) (string, string, error)
}
type messageService struct {
clientPointer map[string]*whatsmeow.Client
messageRepository message_repository.MessageRepository
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type ReactStruct struct {
Number string `json:"number"`
Reaction string `json:"reaction"`
Id string `json:"id"`
FromMe bool `json:"fromMe"`
Participant string `json:"participant,omitempty"`
}
type ChatPresenceStruct struct {
Number string `json:"number"`
State string `json:"state"`
IsAudio bool `json:"isAudio"`
}
type MarkReadStruct struct {
Id []string `json:"id"`
Number string `json:"number"`
}
type DownloadMediaStruct struct {
Message *waE2E.Message `json:"message"`
}
type MessageStatusStruct struct {
Id string `json:"id"`
}
type MessageStruct struct {
Chat string `json:"chat"`
MessageID string `json:"messageId"`
}
type EditMessageStruct struct {
Chat string `json:"chat"`
Message string `json:"message"`
MessageID string `json:"messageId"`
}
type MessageSendStruct struct {
Info types.MessageInfo
Message *waE2E.Message
MessageContextInfo *waE2E.ContextInfo
}
func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := m.clientPointer[instanceId]
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := m.whatsmeowService.StartInstance(instanceId)
if err != nil {
m.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = m.clientPointer[instanceId]
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
m.loggerWrapper.GetLogger(instanceId).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() {
m.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (m *messageService) React(data *ReactStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
msgId := ""
recipient, ok := utils.ParseJID(data.Number)
if !ok {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return nil, errors.New("invalid phone number")
}
if data.Id == "" {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Missing Id in Payload", instance.Id)
return nil, errors.New("missing id in payload")
} else {
msgId = data.Id
}
fromMe := data.FromMe
reaction := data.Reaction
if reaction == "remove" {
reaction = ""
}
// Create MessageKey
messageKey := &waCommon.MessageKey{
RemoteJID: proto.String(recipient.String()),
FromMe: proto.Bool(fromMe),
ID: proto.String(msgId),
}
// Add participant if provided (for group messages)
if data.Participant != "" {
participantJID, ok := utils.ParseJID(data.Participant)
if ok {
messageKey.Participant = proto.String(participantJID.String())
}
}
msg := &waE2E.Message{
ReactionMessage: &waE2E.ReactionMessage{
Key: messageKey,
Text: proto.String(reaction),
// GroupingKey: proto.String(reaction),
SenderTimestampMS: proto.Int64(time.Now().UnixMilli()),
},
}
response, err := client.SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{
ID: msgId,
})
if err != nil {
return nil, err
}
isGroup := strings.Contains(data.Number, "@g.us")
messageType := "ReactionMessage"
messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{
Chat: recipient,
Sender: *client.Store.ID,
IsFromMe: true,
IsGroup: isGroup,
},
ID: msgId,
Timestamp: time.Now(),
ServerID: response.ServerID,
Type: messageType,
}
messageSent := &MessageSendStruct{
Info: messageInfo,
Message: msg,
}
return messageSent, nil
}
func (m *messageService) ChatPresence(data *ChatPresenceStruct, instance *instance_model.Instance) (string, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Number)
if !ok {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
media := ""
if data.IsAudio {
media = "audio"
}
err = client.SendChatPresence(context.Background(), recipient, types.ChatPresence(data.State), types.ChatPresenceMedia(media))
if err != nil {
return "", err
}
m.loggerWrapper.GetLogger(instance.Id).LogInfo("Message sent to %s", data.Number)
return ts.String(), nil
}
func (m *messageService) MarkRead(data *MarkReadStruct, instance *instance_model.Instance) (string, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
jid, ok := utils.ParseJID(data.Number)
if !ok {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.MarkRead(context.Background(), data.Id, time.Now(), jid, jid)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error marking message as read: %v", instance.Id, err)
return "", errors.New("error marking message as read")
}
return ts.String(), nil
}
func (m *messageService) DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
return nil, "", err
}
var ts time.Time
msg := data.Message
mimetype := ""
var mediaData []byte
img := msg.GetImageMessage()
audio := msg.GetAudioMessage()
document := msg.GetDocumentMessage()
video := msg.GetVideoMessage()
sticker := msg.GetStickerMessage()
if img == nil && audio == nil && document == nil && video == nil && sticker == nil {
return nil, "", errors.New("invalid media type")
}
userDirectory := fmt.Sprintf(`files/user_%s`, instance.Id)
_, err = os.Stat(userDirectory)
if os.IsNotExist(err) {
errDir := os.MkdirAll(userDirectory, 0751)
if errDir != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not create user directory (%s)", instance.Id, userDirectory)
return nil, "", errDir
}
}
if img != nil {
mediaData, err = client.Download(context.Background(), img)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download image", instance.Id)
msg := fmt.Sprintf("Failed to download image %v", err)
return nil, "", errors.New(msg)
}
mimetype = img.GetMimetype()
}
if audio != nil {
mediaData, err = client.Download(context.Background(), audio)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download audio", instance.Id)
msg := fmt.Sprintf("Failed to download audio %v", err)
return nil, "", errors.New(msg)
}
mimetype = audio.GetMimetype()
}
if document != nil {
mediaData, err = client.Download(context.Background(), document)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download document", instance.Id)
msg := fmt.Sprintf("Failed to download document %v", err)
return nil, "", errors.New(msg)
}
mimetype = document.GetMimetype()
}
if video != nil {
mediaData, err = client.Download(context.Background(), video)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download video", instance.Id)
msg := fmt.Sprintf("Failed to download video %v", err)
return nil, "", errors.New(msg)
}
mimetype = video.GetMimetype()
}
if sticker != nil {
mediaData, err = client.Download(context.Background(), sticker)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download sticker", instance.Id)
msg := fmt.Sprintf("Failed to download sticker %v", err)
return nil, "", errors.New(msg)
}
mimetype = sticker.GetMimetype()
}
dataURL := dataurl.New(mediaData, mimetype)
return dataURL, ts.String(), nil
}
func (m *messageService) GetMessageStatus(data *MessageStatusStruct, instance *instance_model.Instance) (*message_model.Message, string, error) {
_, err := m.ensureClientConnected(instance.Id)
if err != nil {
return nil, "", err
}
var ts time.Time
result, err := m.messageRepository.GetMessageByID(data.Id)
if err != nil {
return nil, "", err
}
return result, ts.String(), nil
}
func (m *messageService) DeleteMessageEveryone(data *MessageStruct, instance *instance_model.Instance) (string, string, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
return "", "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", "", errors.New("invalid phone number")
}
m.loggerWrapper.GetLogger(instance.Id).LogInfo("Revoking message %s from %s", data.MessageID, recipient)
resp, err := client.SendMessage(
context.Background(),
recipient,
client.BuildRevoke(recipient, types.EmptyJID, data.MessageID))
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error revoking message: %v", instance.Id, err)
return "", "", err
}
response := resp.ID
return response, ts.String(), nil
}
func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance_model.Instance) (string, string, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
return "", "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", "", errors.New("invalid phone number")
}
resp, err := client.SendMessage(
context.Background(),
recipient,
client.BuildEdit(
recipient,
data.MessageID,
&waE2E.Message{
Conversation: proto.String(data.Message),
}))
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error revoking message: %v", instance.Id, err)
return "", "", err
}
response := resp.ID
return response, ts.String(), nil
}
func NewMessageService(
clientPointer map[string]*whatsmeow.Client,
messageRepository message_repository.MessageRepository,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) MessageService {
return &messageService{
clientPointer: clientPointer,
messageRepository: messageRepository,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}
+56
View File
@@ -0,0 +1,56 @@
package auth_middleware
import (
"net/http"
"github.com/EvolutionAPI/evolution-go/pkg/config"
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
"github.com/gin-gonic/gin"
)
type Middleware interface {
Auth(ctx *gin.Context)
AuthAdmin(ctx *gin.Context)
}
type middleware struct {
config *config.Config
instanceService instance_service.InstanceService
}
func (m middleware) Auth(ctx *gin.Context) {
token := ctx.GetHeader("apikey")
if token == "" {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
return
}
instance, err := m.instanceService.GetInstanceByToken(token)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
return
}
ctx.Set("instance", instance)
ctx.Next()
}
func (m middleware) AuthAdmin(ctx *gin.Context) {
token := ctx.GetHeader("apikey")
if token == "" {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
return
}
if token != m.config.GlobalApiKey {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
return
}
ctx.Next()
}
func NewMiddleware(config *config.Config, instanceService instance_service.InstanceService) *middleware {
return &middleware{config: config, instanceService: instanceService}
}
+533
View File
@@ -0,0 +1,533 @@
package auth_middleware
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
"github.com/gin-gonic/gin"
"github.com/gomessguii/logger"
)
// JIDValidationMiddleware validates JID parameters in request bodies
type JIDValidationMiddleware struct{}
// NewJIDValidationMiddleware creates a new JID validation middleware
func NewJIDValidationMiddleware() *JIDValidationMiddleware {
return &JIDValidationMiddleware{}
}
// ValidateJIDFields validates and normalizes JID fields in request body
func (m *JIDValidationMiddleware) ValidateJIDFields(fieldNames ...string) gin.HandlerFunc {
return func(c *gin.Context) {
// Only process JSON requests
contentType := c.ContentType()
if !strings.Contains(contentType, "application/json") {
// For multipart/form-data, validate form fields
if strings.Contains(contentType, "multipart/form-data") {
m.validateFormFields(c, fieldNames...)
return
}
c.Next()
return
}
// Read the request body
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
c.Abort()
return
}
// Restore the request body for downstream handlers
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
// Parse JSON
var requestData map[string]interface{}
if err := json.Unmarshal(body, &requestData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
c.Abort()
return
}
// Validate and normalize JID fields
modified := false
for _, fieldName := range fieldNames {
if value, exists := requestData[fieldName]; exists {
if strValue, ok := value.(string); ok && strValue != "" {
// Validate and normalize the JID
normalizedJID, err := utils.CreateJID(strValue)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid %s format: %s", fieldName, err.Error()),
})
c.Abort()
return
}
// Update the value if it was normalized
if normalizedJID != strValue {
requestData[fieldName] = normalizedJID
modified = true
logger.LogDebug("Normalized %s from %s to %s", fieldName, strValue, normalizedJID)
}
} else if strValue == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("%s is required and cannot be empty", fieldName),
})
c.Abort()
return
}
}
}
// If we modified the request, update the body
if modified {
newBody, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
c.Abort()
return
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
}
c.Next()
}
}
// validateFormFields validates JID fields in multipart form data
func (m *JIDValidationMiddleware) validateFormFields(c *gin.Context, fieldNames ...string) {
for _, fieldName := range fieldNames {
value := c.PostForm(fieldName)
if value != "" {
// Validate the JID format
_, err := utils.CreateJID(value)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid %s format: %s", fieldName, err.Error()),
})
c.Abort()
return
}
} else if fieldName == "number" { // number is typically required
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("%s is required and cannot be empty", fieldName),
})
c.Abort()
return
}
}
c.Next()
}
// ValidateNumberField is a convenience method for the common "number" field
// It handles both single strings and arrays of strings
func (m *JIDValidationMiddleware) ValidateNumberField() gin.HandlerFunc {
return func(c *gin.Context) {
// Only process JSON requests
contentType := c.ContentType()
if !strings.Contains(contentType, "application/json") {
// For multipart/form-data, validate form fields
if strings.Contains(contentType, "multipart/form-data") {
m.validateFormFields(c, "number")
return
}
c.Next()
return
}
// Read the request body
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
c.Abort()
return
}
// Restore the request body for downstream handlers
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
// Parse JSON
var requestData map[string]interface{}
if err := json.Unmarshal(body, &requestData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
c.Abort()
return
}
// Validate and normalize number field (can be string or array)
modified := false
if value, exists := requestData["number"]; exists {
// Handle array of strings
if arrayValue, ok := value.([]interface{}); ok {
if len(arrayValue) == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"error": "number array cannot be empty",
})
c.Abort()
return
}
for i, item := range arrayValue {
if strValue, ok := item.(string); ok && strValue != "" {
normalizedJID, err := utils.CreateJID(strValue)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid number[%d] format: %s", i, err.Error()),
})
c.Abort()
return
}
if normalizedJID != strValue {
arrayValue[i] = normalizedJID
modified = true
logger.LogDebug("Normalized number[%d] from %s to %s", i, strValue, normalizedJID)
}
} else if strValue == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("number[%d] cannot be empty", i),
})
c.Abort()
return
}
}
} else if strValue, ok := value.(string); ok {
// Handle single string
if strValue == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "number is required and cannot be empty",
})
c.Abort()
return
}
normalizedJID, err := utils.CreateJID(strValue)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid number format: %s", err.Error()),
})
c.Abort()
return
}
if normalizedJID != strValue {
requestData["number"] = normalizedJID
modified = true
logger.LogDebug("Normalized number from %s to %s", strValue, normalizedJID)
}
} else {
c.JSON(http.StatusBadRequest, gin.H{
"error": "number must be a string or array of strings",
})
c.Abort()
return
}
}
// If we modified the request, update the body
if modified {
newBody, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
c.Abort()
return
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
}
c.Next()
}
}
// ValidateMultipleNumbers validates multiple number fields (for arrays or multiple contacts)
func (m *JIDValidationMiddleware) ValidateMultipleNumbers(fieldName string) gin.HandlerFunc {
return func(c *gin.Context) {
// Only process JSON requests
contentType := c.ContentType()
if !strings.Contains(contentType, "application/json") {
c.Next()
return
}
// Read the request body
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
c.Abort()
return
}
// Restore the request body for downstream handlers
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
// Parse JSON
var requestData map[string]interface{}
if err := json.Unmarshal(body, &requestData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
c.Abort()
return
}
// Validate array of numbers
if value, exists := requestData[fieldName]; exists {
modified := false
// Handle array of strings
if arrayValue, ok := value.([]interface{}); ok {
for i, item := range arrayValue {
if strValue, ok := item.(string); ok && strValue != "" {
normalizedJID, err := utils.CreateJID(strValue)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid %s[%d] format: %s", fieldName, i, err.Error()),
})
c.Abort()
return
}
if normalizedJID != strValue {
arrayValue[i] = normalizedJID
modified = true
}
}
}
}
// If we modified the request, update the body
if modified {
newBody, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
c.Abort()
return
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
}
}
c.Next()
}
}
// ValidateNumberFieldWithFormatJid validates number field but respects FormatJid parameter
// When FormatJid is true (default), numbers are normalized to full JID format
// When FormatJid is false, numbers are kept as received (raw format)
func (m *JIDValidationMiddleware) ValidateNumberFieldWithFormatJid() gin.HandlerFunc {
return func(c *gin.Context) {
// Only process JSON requests
contentType := c.ContentType()
if !strings.Contains(contentType, "application/json") {
c.Next()
return
}
// Read the request body
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
c.Abort()
return
}
// Restore the request body for downstream handlers
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
// Parse JSON
var requestData map[string]interface{}
if err := json.Unmarshal(body, &requestData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
c.Abort()
return
}
// Check FormatJid parameter (default is true)
formatJid := true
if formatJidValue, exists := requestData["formatJid"]; exists {
if formatJidBool, ok := formatJidValue.(bool); ok {
formatJid = formatJidBool
}
}
// Validate and optionally normalize number field based on FormatJid
modified := false
if value, exists := requestData["number"]; exists {
// Handle array of strings
if arrayValue, ok := value.([]interface{}); ok {
if len(arrayValue) == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"error": "number array cannot be empty",
})
c.Abort()
return
}
for i, item := range arrayValue {
if strValue, ok := item.(string); ok && strValue != "" {
// Only validate and normalize if FormatJid is true
if formatJid {
normalizedJID, err := utils.CreateJID(strValue)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid number[%d] format: %s", i, err.Error()),
})
c.Abort()
return
}
if normalizedJID != strValue {
arrayValue[i] = normalizedJID
modified = true
logger.LogDebug("Normalized number[%d] from %s to %s", i, strValue, normalizedJID)
}
}
// When formatJid is false, we accept numbers as received without validation
} else if strValue == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("number[%d] cannot be empty", i),
})
c.Abort()
return
}
}
} else if strValue, ok := value.(string); ok {
// Handle single string
if strValue == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "number is required and cannot be empty",
})
c.Abort()
return
}
// Only validate and normalize if FormatJid is true
if formatJid {
normalizedJID, err := utils.CreateJID(strValue)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid number format: %s", err.Error()),
})
c.Abort()
return
}
if normalizedJID != strValue {
requestData["number"] = normalizedJID
modified = true
logger.LogDebug("Normalized number from %s to %s", strValue, normalizedJID)
}
}
// When formatJid is false, we accept numbers as received without validation
} else {
c.JSON(http.StatusBadRequest, gin.H{
"error": "number must be a string or array of strings",
})
c.Abort()
return
}
}
// If we modified the request, update the body
if modified {
newBody, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
c.Abort()
return
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
}
c.Next()
}
}
// ValidateContactFields validates contact-specific fields that may contain phone numbers
func (m *JIDValidationMiddleware) ValidateContactFields() gin.HandlerFunc {
return func(c *gin.Context) {
// Only process JSON requests
contentType := c.ContentType()
if !strings.Contains(contentType, "application/json") {
c.Next()
return
}
// Read the request body
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
c.Abort()
return
}
// Restore the request body for downstream handlers
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
// Parse JSON
var requestData map[string]interface{}
if err := json.Unmarshal(body, &requestData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
c.Abort()
return
}
modified := false
// Validate main number field
if value, exists := requestData["number"]; exists {
if strValue, ok := value.(string); ok && strValue != "" {
normalizedJID, err := utils.CreateJID(strValue)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid number format: %s", err.Error()),
})
c.Abort()
return
}
if normalizedJID != strValue {
requestData["number"] = normalizedJID
modified = true
}
}
}
// Validate vcard phone field if present
if vcardValue, exists := requestData["vcard"]; exists {
if vcardMap, ok := vcardValue.(map[string]interface{}); ok {
if phoneValue, phoneExists := vcardMap["phone"]; phoneExists {
if phoneStr, ok := phoneValue.(string); ok && phoneStr != "" {
// For vcard phone, we just validate format but don't necessarily convert to JID
_, err := utils.CreateJID(phoneStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Invalid vcard phone format: %s", err.Error()),
})
c.Abort()
return
}
}
}
}
}
// If we modified the request, update the body
if modified {
newBody, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
c.Abort()
return
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
}
c.Next()
}
}
@@ -0,0 +1,262 @@
package newsletter_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service"
"github.com/gin-gonic/gin"
)
type NewsletterHandler interface {
CreateNewsletter(ctx *gin.Context)
ListNewsletter(ctx *gin.Context)
GetNewsletter(ctx *gin.Context)
GetNewsletterInvite(ctx *gin.Context)
SubscribeNewsletter(ctx *gin.Context)
GetNewsletterMessages(ctx *gin.Context)
}
type newsletterHandler struct {
newsletterService newsletter_service.NewsletterService
}
// Create newsletter
// @Summary Create newsletter
// @Description Create newsletter
// @Tags Newsletter
// @Accept json
// @Produce json
// @Param message body newsletter_service.CreateNewsletterStruct true "Newsletter data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /newsletter/create [post]
func (n *newsletterHandler) CreateNewsletter(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 *newsletter_service.CreateNewsletterStruct
err := ctx.ShouldBindBodyWithJSON(&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
}
newsletter, err := n.newsletterService.CreateNewsletter(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})
}
// List newsletters
// @Summary List newsletters
// @Description List newsletters
// @Tags Newsletter
// @Accept json
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /newsletter/list [get]
func (n *newsletterHandler) ListNewsletter(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
}
newsletters, err := n.newsletterService.ListNewsletter(instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletters})
}
// Get newsletter
// @Summary Get newsletter
// @Description Get newsletter
// @Tags Newsletter
// @Accept json
// @Produce json
// @Param message body newsletter_service.GetNewsletterStruct true "Newsletter data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /newsletter/info [post]
func (n *newsletterHandler) GetNewsletter(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 *newsletter_service.GetNewsletterStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.JID.String() == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
return
}
newsletter, err := n.newsletterService.GetNewsletter(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})
}
// Get newsletter invite
// @Summary Get newsletter invite
// @Description Get newsletter invite
// @Tags Newsletter
// @Accept json
// @Produce json
// @Param message body newsletter_service.GetNewsletterInviteStruct true "Newsletter data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /newsletter/link [post]
func (n *newsletterHandler) GetNewsletterInvite(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 *newsletter_service.GetNewsletterInviteStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Key == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "key is required"})
return
}
newsletter, err := n.newsletterService.GetNewsletterInvite(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})
}
// Subscribe newsletter
// @Summary Subscribe newsletter
// @Description Subscribe newsletter
// @Tags Newsletter
// @Accept json
// @Produce json
// @Param message body newsletter_service.GetNewsletterStruct true "Newsletter data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /newsletter/subscribe [post]
func (n *newsletterHandler) SubscribeNewsletter(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 *newsletter_service.GetNewsletterStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.JID.String() == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
return
}
err = n.newsletterService.SubscribeNewsletter(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Get newsletter messages
// @Summary Get newsletter messages
// @Description Get newsletter messages
// @Tags Newsletter
// @Accept json
// @Produce json
// @Param message body newsletter_service.GetNewsletterMessagesStruct true "Newsletter data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /newsletter/messages [post]
func (n *newsletterHandler) GetNewsletterMessages(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 *newsletter_service.GetNewsletterMessagesStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.JID.String() == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
return
}
messages, err := n.newsletterService.GetNewsletterMessages(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": messages})
}
func NewNewsletterHandler(
newsletterService newsletter_service.NewsletterService,
) NewsletterHandler {
return &newsletterHandler{
newsletterService: newsletterService,
}
}
@@ -0,0 +1,207 @@
package newsletter_service
import (
"context"
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
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 NewsletterService interface {
CreateNewsletter(data *CreateNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)
ListNewsletter(instance *instance_model.Instance) ([]*types.NewsletterMetadata, error)
GetNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)
GetNewsletterInvite(data *GetNewsletterInviteStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)
SubscribeNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) error
GetNewsletterMessages(data *GetNewsletterMessagesStruct, instance *instance_model.Instance) ([]*types.NewsletterMessage, error)
}
type newsletterService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type CreateNewsletterStruct struct {
Name string `json:"name"`
Description string `json:"description"`
}
type GetNewsletterStruct struct {
JID types.JID `json:"jid"`
}
type GetNewsletterInviteStruct struct {
Key string `json:"key"`
}
type GetNewsletterMessagesStruct struct {
JID types.JID `json:"jid"`
Count int `json:"count"`
BeforeID int `json:"before_id"`
}
func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := n.clientPointer[instanceId]
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := n.whatsmeowService.StartInstance(instanceId)
if err != nil {
n.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = n.clientPointer[instanceId]
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
n.loggerWrapper.GetLogger(instanceId).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() {
n.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (n *newsletterService) CreateNewsletter(data *CreateNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {
client, err := n.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
newsletter, err := client.CreateNewsletter(context.Background(), whatsmeow.CreateNewsletterParams{
Name: data.Name,
Description: data.Description,
})
if err != nil {
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create newsletter: %v", instance.Id, err)
return nil, err
}
return newsletter, nil
}
func (n *newsletterService) ListNewsletter(instance *instance_model.Instance) ([]*types.NewsletterMetadata, error) {
client, err := n.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
newsletters, err := client.GetSubscribedNewsletters(context.Background())
if err != nil {
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletters: %v", instance.Id, err)
return nil, err
}
// For each newsletter, fetch full info to get subscribers_count
fullNewsletters := make([]*types.NewsletterMetadata, 0, len(newsletters))
for _, newsletter := range newsletters {
fullInfo, err := client.GetNewsletterInfo(context.Background(), newsletter.ID)
if err != nil {
// If we can't get full info, use the basic one
n.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] error getting full info for newsletter %s: %v", instance.Id, newsletter.ID.String(), err)
fullNewsletters = append(fullNewsletters, newsletter)
continue
}
fullNewsletters = append(fullNewsletters, fullInfo)
}
return fullNewsletters, nil
}
func (n *newsletterService) GetNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {
client, err := n.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
newsletter, err := client.GetNewsletterInfo(context.Background(), data.JID)
if err != nil {
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
return nil, err
}
return newsletter, nil
}
func (n *newsletterService) GetNewsletterInvite(data *GetNewsletterInviteStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {
client, err := n.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
newsletter, err := client.GetNewsletterInfoWithInvite(context.Background(), data.Key)
if err != nil {
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
return nil, err
}
return newsletter, nil
}
func (n *newsletterService) SubscribeNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) error {
client, err := n.ensureClientConnected(instance.Id)
if err != nil {
return err
}
_, err = client.NewsletterSubscribeLiveUpdates(context.TODO(), data.JID)
if err != nil {
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
return err
}
return nil
}
func (n *newsletterService) GetNewsletterMessages(data *GetNewsletterMessagesStruct, instance *instance_model.Instance) ([]*types.NewsletterMessage, error) {
client, err := n.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
messages, err := client.GetNewsletterMessages(context.Background(), data.JID,
&whatsmeow.GetNewsletterMessagesParams{
Count: data.Count, Before: data.BeforeID,
})
if err != nil {
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
return nil, err
}
return messages, nil
}
func NewNewsletterService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) NewsletterService {
return &newsletterService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}
+98
View File
@@ -0,0 +1,98 @@
package poll_handler
import (
"encoding/json"
"net/http"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
poll_service "github.com/EvolutionAPI/evolution-go/pkg/poll/service"
"github.com/gin-gonic/gin"
)
type PollHandler struct {
pollService poll_service.PollService
loggerWrapper *logger_wrapper.LoggerManager
}
// NewPollHandler cria handler usando PollService existente (evita dupla inicialização)
func NewPollHandler(pollService poll_service.PollService, loggerWrapper *logger_wrapper.LoggerManager) *PollHandler {
return &PollHandler{
pollService: pollService,
loggerWrapper: loggerWrapper,
}
}
// GetPollResults retorna os resultados de uma enquete
// @Summary Get poll results
// @Description Retorna todos os votos de uma enquete específica
// @Tags Polls
// @Accept json
// @Produce json
// @Param pollMessageId path string true "ID da mensagem da enquete"
// @Success 200 {object} model.PollResults
// @Failure 400 {object} gin.H
// @Failure 404 {object} gin.H
// @Failure 500 {object} gin.H
// @Router /polls/{pollMessageId}/results [get]
func (h *PollHandler) GetPollResults(c *gin.Context) {
pollMessageID := c.Param("pollMessageId")
// Pegar instance do contexto de autenticação
instanceInterface, exists := c.Get("instance")
if !exists {
h.loggerWrapper.GetLogger("poll-handler").LogWarn("[POLL] Instance not found in context")
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Authentication required",
})
return
}
// Converter para struct Instance
type Instance struct {
Id string `json:"id"`
}
instanceBytes, _ := json.Marshal(instanceInterface)
var instance Instance
if err := json.Unmarshal(instanceBytes, &instance); err != nil {
h.loggerWrapper.GetLogger("poll-handler").LogError("[POLL] Failed to parse instance: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to get instance information",
})
return
}
instanceID := instance.Id
// Validações de segurança
if pollMessageID == "" {
h.loggerWrapper.GetLogger("poll-handler").LogWarn("[POLL] Missing pollMessageId")
c.JSON(http.StatusBadRequest, gin.H{
"error": "pollMessageId is required",
})
return
}
h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] Fetching results for poll %s (instance: %s)", pollMessageID, instanceID)
// Buscar resultados do banco
results, err := h.pollService.GetPollResults(c.Request.Context(), pollMessageID, instanceID)
if err != nil {
h.loggerWrapper.GetLogger("poll-handler").LogError("[POLL] Error fetching results: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to fetch poll results",
})
return
}
if results.TotalVotes == 0 {
h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] No votes found for poll %s", pollMessageID)
c.JSON(http.StatusNotFound, gin.H{
"error": "No votes found for this poll",
"message": "This poll has no votes yet, or the pollMessageId is incorrect",
})
return
}
h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] Returning %d votes for poll %s", results.TotalVotes, pollMessageID)
c.JSON(http.StatusOK, results)
}
+38
View File
@@ -0,0 +1,38 @@
package model
import "time"
// PollVote representa um voto em uma enquete do WhatsApp
type PollVote struct {
ID string `json:"id"`
CompanyID string `json:"companyId"`
InstanceID string `json:"instanceId"`
PollMessageID string `json:"pollMessageId"`
PollChatJid string `json:"pollChatJid"`
VoteMessageID string `json:"voteMessageId"`
VoterJid string `json:"voterJid"`
VoterPhone string `json:"voterPhone,omitempty"`
VoterName string `json:"voterName,omitempty"`
SelectedOptions []string `json:"selectedOptions"` // SHA-256 hashes
VotedAt time.Time `json:"votedAt"`
ReceivedAt time.Time `json:"receivedAt"`
}
// PollResults representa os resultados agregados de uma enquete
type PollResults struct {
PollMessageID string `json:"pollMessageId"`
PollChatJid string `json:"pollChatJid"`
TotalVotes int `json:"totalVotes"`
Votes []PollVote `json:"votes"`
OptionCounts map[string]int `json:"optionCounts"` // hash -> count
Voters []VoterInfo `json:"voters"`
}
// VoterInfo representa informações de um votante
type VoterInfo struct {
Jid string `json:"jid"`
Phone string `json:"phone,omitempty"`
Name string `json:"name,omitempty"`
SelectedOptions []string `json:"selectedOptions"`
VotedAt time.Time `json:"votedAt"`
}
+304
View File
@@ -0,0 +1,304 @@
package poll_service
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/poll/model"
"github.com/google/uuid"
waProto "go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
)
// PollService define a interface para gerenciamento de votos de enquetes
type PollService interface {
// SavePollVote salva um voto de enquete no banco de dados
SavePollVote(ctx context.Context, vote *model.PollVote) error
// GetPollResults retorna os resultados de uma enquete
GetPollResults(ctx context.Context, pollMessageID string, instanceID string) (*model.PollResults, error)
}
type pollService struct {
db *sql.DB
loggerWrapper *logger_wrapper.LoggerManager
}
// NewPollService cria uma nova instância do serviço de polls
func NewPollService(db *sql.DB, loggerWrapper *logger_wrapper.LoggerManager) PollService {
service := &pollService{
db: db,
loggerWrapper: loggerWrapper,
}
// Auto-migration: criar tabela se não existir
if err := service.autoMigrate(); err != nil {
loggerWrapper.GetLogger("poll-service").LogError("[POLL] Auto-migration failed: %v", err)
}
return service
}
// autoMigrate cria a tabela poll_votes se não existir
func (s *pollService) autoMigrate() error {
createTableSQL := `
CREATE TABLE IF NOT EXISTS poll_votes (
id VARCHAR(255) PRIMARY KEY,
company_id VARCHAR(255) NOT NULL,
instance_id VARCHAR(255) NOT NULL,
poll_message_id VARCHAR(255) NOT NULL,
poll_chat_jid VARCHAR(255) NOT NULL,
vote_message_id VARCHAR(255) NOT NULL,
voter_jid VARCHAR(255) NOT NULL,
voter_phone VARCHAR(255),
voter_name VARCHAR(255),
selected_options TEXT[] NOT NULL DEFAULT '{}',
voted_at TIMESTAMP NOT NULL DEFAULT NOW(),
received_at TIMESTAMP NOT NULL DEFAULT NOW(),
CONSTRAINT unique_vote_per_poll UNIQUE (poll_message_id, voter_jid)
);
CREATE INDEX IF NOT EXISTS idx_poll_votes_company ON poll_votes(company_id);
CREATE INDEX IF NOT EXISTS idx_poll_votes_instance ON poll_votes(instance_id);
CREATE INDEX IF NOT EXISTS idx_poll_votes_poll_message ON poll_votes(poll_message_id);
CREATE INDEX IF NOT EXISTS idx_poll_votes_chat ON poll_votes(poll_chat_jid);
CREATE INDEX IF NOT EXISTS idx_poll_votes_voter ON poll_votes(voter_jid);
`
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Running auto-migration...")
_, err := s.db.Exec(createTableSQL)
if err != nil {
return fmt.Errorf("failed to create poll_votes table: %w", err)
}
return nil
}
// SavePollVote salva um voto de enquete no banco de dados (NÃO-INVASIVO)
func (s *pollService) SavePollVote(ctx context.Context, vote *model.PollVote) error {
// Log seguro - não expõe dados sensíveis
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Saving vote for poll %s from %s", vote.PollMessageID, vote.VoterJid)
// Extrair telefone do JID de forma segura
if vote.VoterPhone == "" && strings.Contains(vote.VoterJid, "@") {
phone := strings.Split(vote.VoterJid, "@")[0]
vote.VoterPhone = phone
}
// Garantir ID único
if vote.ID == "" {
vote.ID = uuid.New().String()
}
// Query INSERT com ON CONFLICT para evitar duplicatas (SEGURO)
query := `
INSERT INTO poll_votes (
id, company_id, instance_id, poll_message_id, poll_chat_jid,
vote_message_id, voter_jid, voter_phone, voter_name,
selected_options, voted_at, received_at
) VALUES (
$1, $2, $3, $4, $5,
$6, $7, $8, $9,
$10, $11, $12
)
ON CONFLICT (poll_message_id, voter_jid)
DO UPDATE SET
selected_options = EXCLUDED.selected_options,
voted_at = EXCLUDED.voted_at,
received_at = EXCLUDED.received_at
`
_, err := s.db.ExecContext(ctx, query,
vote.ID,
vote.CompanyID,
vote.InstanceID,
vote.PollMessageID,
vote.PollChatJid,
vote.VoteMessageID,
vote.VoterJid,
vote.VoterPhone,
vote.VoterName,
stringArrayToPostgresArray(vote.SelectedOptions),
vote.VotedAt,
vote.ReceivedAt,
)
if err != nil {
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to save vote: %v", err)
return fmt.Errorf("failed to save poll vote: %w", err)
}
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Vote saved successfully for poll %s", vote.PollMessageID)
return nil
}
// GetPollResults retorna os resultados agregados de uma enquete
func (s *pollService) GetPollResults(ctx context.Context, pollMessageID string, instanceID string) (*model.PollResults, error) {
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Fetching results for poll %s", pollMessageID)
query := `
SELECT
id, company_id, instance_id, poll_message_id, poll_chat_jid,
vote_message_id, voter_jid, voter_phone, voter_name,
selected_options, voted_at, received_at
FROM poll_votes
WHERE poll_message_id = $1 AND instance_id = $2
ORDER BY voted_at ASC
`
rows, err := s.db.QueryContext(ctx, query, pollMessageID, instanceID)
if err != nil {
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to query votes: %v", err)
return nil, fmt.Errorf("failed to query poll votes: %w", err)
}
defer rows.Close()
var votes []model.PollVote
optionCounts := make(map[string]int)
for rows.Next() {
var vote model.PollVote
var selectedOptionsStr string
err := rows.Scan(
&vote.ID,
&vote.CompanyID,
&vote.InstanceID,
&vote.PollMessageID,
&vote.PollChatJid,
&vote.VoteMessageID,
&vote.VoterJid,
&vote.VoterPhone,
&vote.VoterName,
&selectedOptionsStr,
&vote.VotedAt,
&vote.ReceivedAt,
)
if err != nil {
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to scan vote: %v", err)
continue
}
// Converter array do PostgreSQL para []string
vote.SelectedOptions = postgresArrayToStringSlice(selectedOptionsStr)
// Contar opções
for _, option := range vote.SelectedOptions {
optionCounts[option]++
}
votes = append(votes, vote)
}
if err = rows.Err(); err != nil {
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Rows iteration error: %v", err)
return nil, fmt.Errorf("error iterating votes: %w", err)
}
// Verificar se há votos antes de construir resultado
if len(votes) == 0 {
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] No votes found for poll %s", pollMessageID)
return &model.PollResults{
PollMessageID: pollMessageID,
PollChatJid: "",
TotalVotes: 0,
Votes: []model.PollVote{},
OptionCounts: make(map[string]int),
Voters: []model.VoterInfo{},
}, nil
}
// Construir informações dos votantes
voters := make([]model.VoterInfo, len(votes))
for i, vote := range votes {
voters[i] = model.VoterInfo{
Jid: vote.VoterJid,
Phone: vote.VoterPhone,
Name: vote.VoterName,
SelectedOptions: vote.SelectedOptions,
VotedAt: vote.VotedAt,
}
}
results := &model.PollResults{
PollMessageID: pollMessageID,
PollChatJid: votes[0].PollChatJid,
TotalVotes: len(votes),
Votes: votes,
OptionCounts: optionCounts,
Voters: voters,
}
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Found %d votes for poll %s", len(votes), pollMessageID)
return results, nil
}
// Helper para converter []string em formato PostgreSQL array
func stringArrayToPostgresArray(arr []string) string {
if len(arr) == 0 {
return "{}"
}
return fmt.Sprintf("{%s}", strings.Join(arr, ","))
}
// Helper para converter array PostgreSQL de volta para []string
func postgresArrayToStringSlice(s string) []string {
// Remove { e }
s = strings.TrimPrefix(s, "{")
s = strings.TrimSuffix(s, "}")
if s == "" {
return []string{}
}
return strings.Split(s, ",")
}
// BuildPollVoteFromEvent constrói um model.PollVote a partir de eventos do WhatsApp (HELPER SEGURO)
// NOTA: Espera que voteInfo já tenha passado pelo JID swap (Sender = número real)
func BuildPollVoteFromEvent(
pollInfo *types.MessageInfo,
voteInfo *types.MessageInfo,
decryptedVote *waProto.PollVoteMessage,
companyID string,
instanceID string,
) *model.PollVote {
// Extrair opções selecionadas (hashes SHA-256)
selectedOptions := make([]string, len(decryptedVote.SelectedOptions))
for i, option := range decryptedVote.SelectedOptions {
selectedOptions[i] = fmt.Sprintf("%x", option) // Converte bytes para hex
}
// Extrair telefone do votante
// NOTA: O JID swap já foi feito antes de chegar aqui!
// Se havia LID+WhatsApp, o Sender JÁ É o número real (@s.whatsapp.net) e SenderAlt é o LID
voterPhone := voteInfo.Sender.User
voterJid := voteInfo.Sender.String()
fmt.Printf("[POLL DEBUG] ==========================================\n")
fmt.Printf("[POLL DEBUG] Voter JID: %s\n", voterJid)
fmt.Printf("[POLL DEBUG] Sender.Server: %s\n", voteInfo.Sender.Server)
fmt.Printf("[POLL DEBUG] Sender.User: %s\n", voteInfo.Sender.User)
fmt.Printf("[POLL DEBUG] FINAL voterPhone: %s\n", voterPhone)
fmt.Printf("[POLL DEBUG] ==========================================\n")
return &model.PollVote{
ID: uuid.New().String(),
CompanyID: companyID,
InstanceID: instanceID,
PollMessageID: pollInfo.ID,
PollChatJid: pollInfo.Chat.String(),
VoteMessageID: voteInfo.ID,
VoterJid: voteInfo.Sender.String(),
VoterPhone: voterPhone,
VoterName: voteInfo.PushName,
SelectedOptions: selectedOptions,
VotedAt: voteInfo.Timestamp,
ReceivedAt: time.Now(),
}
}
+277
View File
@@ -0,0 +1,277 @@
package routes
import (
"net/http"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/EvolutionAPI/evolution-go/docs"
call_handler "github.com/EvolutionAPI/evolution-go/pkg/call/handler"
chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler"
community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler"
group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler"
instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler"
label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler"
message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler"
auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware"
newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler"
poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler"
send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler"
server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler"
user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler"
)
type Routes struct {
authMiddleware auth_middleware.Middleware
jidValidationMiddleware *auth_middleware.JIDValidationMiddleware
instanceHandler instance_handler.InstanceHandler
userHandler user_handler.UserHandler
sendHandler send_handler.SendHandler
messageHandler message_handler.MessageHandler
chatHandler chat_handler.ChatHandler
groupHandler group_handler.GroupHandler
callHandler call_handler.CallHandler
communityHandler community_handler.CommunityHandler
labelHandler label_handler.LabelHandler
newsletterHandler newsletter_handler.NewsletterHandler
pollHandler *poll_handler.PollHandler
serverHandler server_handler.ServerHandler
}
func (r *Routes) AssignRoutes(eng *gin.Engine) {
// Configuração do CORS
eng.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()
})
eng.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
eng.GET("/favicon.ico", func(c *gin.Context) {
c.Status(http.StatusNoContent)
})
// Rotas para o gerenciador React (sem autenticação)
eng.Static("/assets", "./manager/dist/assets")
// Ajuste nas rotas do manager para suportar client-side routing do React
eng.GET("/manager/*any", func(c *gin.Context) {
c.File("manager/dist/index.html")
})
eng.GET("/manager", func(c *gin.Context) {
c.File("manager/dist/index.html")
})
eng.GET("/server/ok", r.serverHandler.ServerOk)
routes := eng.Group("/instance")
{
routes.Use(r.authMiddleware.AuthAdmin)
{
routes.POST("/create", r.instanceHandler.Create)
routes.GET("/all", r.instanceHandler.All)
routes.GET("/info/:instanceId", r.instanceHandler.Info)
routes.DELETE("/delete/:instanceId", r.instanceHandler.Delete)
routes.POST("/proxy/:instanceId", r.instanceHandler.SetProxy)
routes.DELETE("/proxy/:instanceId", r.instanceHandler.DeleteProxy)
routes.POST("/forcereconnect/:instanceId", r.instanceHandler.ForceReconnect)
routes.GET("/logs/:instanceId", r.instanceHandler.GetLogs)
}
}
routes = eng.Group("/instance")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/connect", r.instanceHandler.Connect)
routes.GET("/status", r.instanceHandler.Status)
routes.GET("/qr", r.instanceHandler.Qr)
routes.POST("/pair", r.jidValidationMiddleware.ValidateNumberField(), r.instanceHandler.Pair)
routes.POST("/disconnect", r.instanceHandler.Disconnect)
routes.POST("/reconnect", r.instanceHandler.Reconnect)
routes.DELETE("/logout", r.instanceHandler.Logout)
routes.GET("/:instanceId/advanced-settings", r.instanceHandler.GetAdvancedSettings)
routes.PUT("/:instanceId/advanced-settings", r.instanceHandler.UpdateAdvancedSettings)
}
}
routes = eng.Group("/send")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/text", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendText)
routes.POST("/link", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendLink)
routes.POST("/media", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendMedia)
routes.POST("/poll", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendPoll)
routes.POST("/sticker", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendSticker)
routes.POST("/location", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendLocation)
routes.POST("/contact", r.jidValidationMiddleware.ValidateContactFields(), r.sendHandler.SendContact) // TODO: send multiple contacts
routes.POST("/button", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendButton)
routes.POST("/list", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendList)
// TODO: send status
}
}
routes = eng.Group("/user")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/info", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.GetUser)
routes.POST("/check", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.userHandler.CheckUser)
routes.POST("/avatar", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.GetAvatar)
routes.GET("/contacts", r.userHandler.GetContacts)
routes.GET("/privacy", r.userHandler.GetPrivacy)
routes.POST("/privacy", r.userHandler.SetPrivacy)
routes.POST("/block", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.BlockContact)
routes.POST("/unblock", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.UnblockContact)
routes.GET("/blocklist", r.userHandler.GetBlockList)
routes.POST("/profilePicture", r.userHandler.SetProfilePicture)
routes.POST("/profileName", r.userHandler.SetProfileName)
routes.POST("/profileStatus", r.userHandler.SetProfileStatus)
}
}
routes = eng.Group("/message")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/react", r.jidValidationMiddleware.ValidateJIDFields("number"), r.messageHandler.React)
routes.POST("/presence", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.ChatPresence)
routes.POST("/markread", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.MarkRead)
routes.POST("/downloadmedia", r.messageHandler.DownloadMedia)
routes.POST("/status", r.messageHandler.GetMessageStatus)
routes.POST("/delete", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.DeleteMessageEveryone)
routes.POST("/edit", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.EditMessage) // TODO: edit MediaMessage too
}
}
routes = eng.Group("/chat")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/pin", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatPin) // TODO: not working
routes.POST("/unpin", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnpin) // TODO: not working
routes.POST("/archive", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatArchive) // TODO: not working
routes.POST("/unarchive", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnarchive) // TODO: not working
routes.POST("/mute", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatMute) // TODO: not working
routes.POST("/unmute", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnmute) // TODO: not working
routes.POST("/history-sync", r.chatHandler.HistorySyncRequest)
}
}
routes = eng.Group("/group")
{
routes.Use(r.authMiddleware.Auth)
{
routes.GET("/list", r.groupHandler.ListGroups)
routes.POST("/info", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.GetGroupInfo)
routes.POST("/invitelink", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.GetGroupInviteLink)
routes.POST("/photo", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupPhoto)
routes.POST("/name", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupName)
routes.POST("/description", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupDescription)
routes.POST("/create", r.jidValidationMiddleware.ValidateMultipleNumbers("participants"), r.groupHandler.CreateGroup)
routes.POST("/participant", r.jidValidationMiddleware.ValidateJIDFields("number", "participants"), r.groupHandler.UpdateParticipant)
routes.GET("/myall", r.groupHandler.GetMyGroups) // TODO: not working
routes.POST("/join", r.groupHandler.JoinGroupLink)
routes.POST("/leave", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.LeaveGroup)
}
}
routes = eng.Group("/call")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/reject", r.jidValidationMiddleware.ValidateNumberField(), r.callHandler.RejectCall)
}
}
routes = eng.Group("/community")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/create", r.communityHandler.CreateCommunity)
routes.POST("/add", r.jidValidationMiddleware.ValidateJIDFields("number", "communityId"), r.communityHandler.CommunityAdd)
routes.POST("/remove", r.jidValidationMiddleware.ValidateJIDFields("number", "communityId"), r.communityHandler.CommunityRemove)
}
}
routes = eng.Group("/label")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/chat", r.jidValidationMiddleware.ValidateNumberField(), r.labelHandler.ChatLabel)
routes.POST("/message", r.labelHandler.MessageLabel)
routes.POST("/edit", r.labelHandler.EditLabel)
routes.GET("/list", r.labelHandler.GetLabels)
}
}
routes = eng.Group("/unlabel")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/chat", r.jidValidationMiddleware.ValidateNumberField(), r.labelHandler.ChatUnlabel)
routes.POST("/message", r.labelHandler.MessageUnlabel)
}
}
routes = eng.Group("/newsletter")
{
routes.Use(r.authMiddleware.Auth)
{
routes.POST("/create", r.newsletterHandler.CreateNewsletter)
routes.GET("/list", r.newsletterHandler.ListNewsletter)
routes.POST("/info", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletter)
routes.POST("/link", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletterInvite)
routes.POST("/subscribe", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.SubscribeNewsletter)
routes.POST("/messages", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletterMessages)
}
}
// NOVO: Rotas de Enquetes (Polls)
routes = eng.Group("/polls")
{
routes.Use(r.authMiddleware.Auth)
{
routes.GET("/:pollMessageId/results", r.pollHandler.GetPollResults)
}
}
}
func NewRouter(
authMiddleware auth_middleware.Middleware,
instanceHandler instance_handler.InstanceHandler,
userHandler user_handler.UserHandler,
sendHandler send_handler.SendHandler,
messageHandler message_handler.MessageHandler,
chatHandler chat_handler.ChatHandler,
groupHandler group_handler.GroupHandler,
callHandler call_handler.CallHandler,
communityHandler community_handler.CommunityHandler,
labelHandler label_handler.LabelHandler,
newsletterHandler newsletter_handler.NewsletterHandler,
pollHandler *poll_handler.PollHandler,
serverHandler server_handler.ServerHandler,
) *Routes {
return &Routes{
authMiddleware: authMiddleware,
jidValidationMiddleware: auth_middleware.NewJIDValidationMiddleware(),
instanceHandler: instanceHandler,
userHandler: userHandler,
sendHandler: sendHandler,
messageHandler: messageHandler,
chatHandler: chatHandler,
groupHandler: groupHandler,
callHandler: callHandler,
communityHandler: communityHandler,
labelHandler: labelHandler,
newsletterHandler: newsletterHandler,
pollHandler: pollHandler,
serverHandler: serverHandler,
}
}
+579
View File
@@ -0,0 +1,579 @@
package send_handler
import (
"io"
"net/http"
"strconv"
"strings"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service"
"github.com/gin-gonic/gin"
)
type SendHandler interface {
SendText(ctx *gin.Context)
SendLink(ctx *gin.Context)
SendMedia(ctx *gin.Context)
SendPoll(ctx *gin.Context)
SendSticker(ctx *gin.Context)
SendLocation(ctx *gin.Context)
SendContact(ctx *gin.Context)
SendButton(ctx *gin.Context)
SendList(ctx *gin.Context)
}
type sendHandler struct {
sendMessageService send_service.SendService
}
// Send a text message
// @Summary Send a text message
// @Description Send a text message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.TextStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/text [post]
func (s *sendHandler) SendText(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 *send_service.TextStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Text == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message body is required"})
return
}
message, err := s.sendMessageService.SendText(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a link message
// @Summary Send a link message
// @Description Send a link message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.LinkStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/link [post]
func (s *sendHandler) SendLink(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 *send_service.LinkStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Text == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message body is required"})
return
}
message, err := s.sendMessageService.SendLink(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a media message
// @Summary Send a media message
// @Description Send a media message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.MediaStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/media [post]
func (s *sendHandler) SendMedia(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
}
contentType := ctx.ContentType()
var data *send_service.MediaStruct
if strings.HasPrefix(contentType, "multipart/form-data") {
// Handle form-data
number := ctx.PostForm("number")
if number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
mediaType := ctx.PostForm("type")
if mediaType == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "media type is required"})
return
}
caption := ctx.PostForm("caption")
filename := ctx.PostForm("filename")
id := ctx.PostForm("id")
delayStr := ctx.PostForm("delay")
delay := int32(0)
if delayStr != "" {
delay64, err := strconv.ParseInt(delayStr, 10, 32)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid delay"})
return
}
delay = int32(delay64)
}
// Get file
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
// Open file
fileData, err := file.Open()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
return
}
defer fileData.Close()
fileBytes, err := io.ReadAll(fileData)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "cannot read file"})
return
}
// Create MediaStruct
data = &send_service.MediaStruct{
Number: number,
Type: mediaType,
Caption: caption,
Filename: filename,
Id: id,
Delay: delay,
// Other fields as necessary
}
// Pass fileBytes to the send service
message, err := s.sendMessageService.SendMediaFile(data, fileBytes, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
} else {
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Url == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "URL is required"})
return
}
if data.Type == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "media type is required"})
return
}
message, err := s.sendMessageService.SendMediaUrl(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
}
// Send a poll message
// @Summary Send a poll message
// @Description Send a poll message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.PollStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/poll [post]
func (s *sendHandler) SendPoll(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 *send_service.PollStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Question == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "question is required"})
return
}
if len(data.Options) < 2 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "minimum 2 options are required"})
return
}
message, err := s.sendMessageService.SendPoll(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a sticker message
// @Summary Send a sticker message
// @Description Send a sticker message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.StickerStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/sticker [post]
func (s *sendHandler) SendSticker(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 *send_service.StickerStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Sticker == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "sticker is required"})
return
}
message, err := s.sendMessageService.SendSticker(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a location message
// @Summary Send a location message
// @Description Send a location message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.LocationStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/location [post]
func (s *sendHandler) SendLocation(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 *send_service.LocationStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Latitude == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "latitude is required"})
return
}
if data.Longitude == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "longitude is required"})
return
}
if data.Address == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "address is required"})
return
}
if data.Name == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
return
}
message, err := s.sendMessageService.SendLocation(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a contact message
// @Summary Send a contact message
// @Description Send a contact message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.ContactStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/contact [post]
func (s *sendHandler) SendContact(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 *send_service.ContactStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Vcard.Phone == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "contact phone number is required"})
return
}
if data.Vcard.FullName == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "contact full name is required"})
return
}
message, err := s.sendMessageService.SendContact(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a button message
// @Summary Send a button message
// @Description Send a button message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.ContactStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/button [post]
func (s *sendHandler) SendButton(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 *send_service.ButtonStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Title == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})
return
}
if data.Description == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "description is required"})
return
}
if data.Footer == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "footer is required"})
return
}
message, err := s.sendMessageService.SendButton(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a list message
// @Summary Send a list message
// @Description Send a list message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.ContactStruct true "Message data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/list [post]
func (s *sendHandler) SendList(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 *send_service.ListStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Title == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})
return
}
if data.Description == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "description is required"})
return
}
if data.FooterText == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "footer is required"})
return
}
if data.ButtonText == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "button text is required"})
return
}
message, err := s.sendMessageService.SendList(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
func NewSendHandler(
sendMessageService send_service.SendService,
) SendHandler {
return &sendHandler{
sendMessageService: sendMessageService,
}
}
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
package server_handler
import "github.com/gin-gonic/gin"
type ServerHandler interface {
ServerOk(ctx *gin.Context)
}
type serverHandler struct {
}
// ServerOk implements ServerHandler.
func (s *serverHandler) ServerOk(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"status": "ok",
})
}
func NewServerHandler() ServerHandler {
return &serverHandler{}
}
+15
View File
@@ -0,0 +1,15 @@
package storage_interfaces
import "context"
// MediaStorage defines the contract for storing and retrieving media files
type MediaStorage interface {
// Store saves the media data and returns a public URL to access it
Store(ctx context.Context, data []byte, fileName string, contentType string) (string, error)
// Delete removes the stored media
Delete(ctx context.Context, fileName string) error
// GetURL returns the public URL for accessing the media
GetURL(ctx context.Context, fileName string) (string, error)
}
+155
View File
@@ -0,0 +1,155 @@
package minio_storage
import (
"bytes"
"context"
"fmt"
"net/url"
"strings"
"time"
storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type MinioMediaStorage struct {
client *minio.Client
bucketName string
baseURL string
}
func setBucketPolicy(client *minio.Client, bucketName string) error {
policy := `{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::` + bucketName + `/*"]
}
]
}`
return client.SetBucketPolicy(context.Background(), bucketName, policy)
}
// generateFilePath creates a simple media folder structure
// Format: evolution-go-medias/{filename}
func generateFilePath(fileName string) string {
return fmt.Sprintf("evolution-go-medias/%s", fileName)
}
// resolveFilePath determines if the input is a full path or just a filename
// If it's just a filename, it assumes it's in the evolution-go-medias folder
// If it's a full path, it returns it as-is
func (m *MinioMediaStorage) resolveFilePath(ctx context.Context, fileNameOrPath string) (string, error) {
// If the input already contains path separators, assume it's a full path
if strings.Contains(fileNameOrPath, "/") {
return fileNameOrPath, nil
}
// If it's just a filename, assume it's in the evolution-go-medias folder
return fmt.Sprintf("evolution-go-medias/%s", fileNameOrPath), nil
}
func NewMinioMediaStorage(
endpoint,
accessKeyID,
secretAccessKey,
bucketName,
region string,
useSSL bool,
) (storage_interfaces.MediaStorage, error) {
client, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: useSSL,
Region: region,
})
if err != nil {
return nil, fmt.Errorf("failed to create MinIO client: %w", err)
}
// Try to set bucket policy to allow public access (optional for some providers)
err = setBucketPolicy(client, bucketName)
if err != nil {
// Some providers (like Backblaze B2) don't support SetBucketPolicy
// Log warning but continue - files can still be accessed via presigned URLs
fmt.Printf("Warning: Failed to set bucket policy (provider may not support it): %v\n", err)
}
baseURL := fmt.Sprintf("https://%s/%s", endpoint, bucketName)
if !useSSL {
baseURL = fmt.Sprintf("http://%s/%s", endpoint, bucketName)
}
return &MinioMediaStorage{
client: client,
bucketName: bucketName,
baseURL: baseURL,
}, nil
}
func (m *MinioMediaStorage) Store(ctx context.Context, data []byte, fileName string, contentType string) (string, error) {
// Generate organized file path
filePath := generateFilePath(fileName)
reader := bytes.NewReader(data)
_, err := m.client.PutObject(ctx, m.bucketName, filePath, reader, int64(len(data)), minio.PutObjectOptions{
ContentType: contentType,
})
if err != nil {
return "", fmt.Errorf("failed to store object: %w", err)
}
// Gerando URL assinada com validade de 7 dias
reqParams := make(url.Values)
presignedURL, err := m.client.PresignedGetObject(ctx, m.bucketName, filePath, time.Hour*24*7, reqParams)
if err != nil {
return "", fmt.Errorf("failed to generate presigned URL: %w", err)
}
fmt.Println(presignedURL.String())
return presignedURL.String(), nil
}
func (m *MinioMediaStorage) Delete(ctx context.Context, fileName string) error {
// Resolve the full path for the file
filePath, err := m.resolveFilePath(ctx, fileName)
if err != nil {
return fmt.Errorf("failed to resolve file path: %w", err)
}
err = m.client.RemoveObject(ctx, m.bucketName, filePath, minio.RemoveObjectOptions{})
if err != nil {
return fmt.Errorf("failed to delete object: %w", err)
}
return nil
}
func (m *MinioMediaStorage) GetURL(ctx context.Context, fileName string) (string, error) {
// Resolve the full path for the file
filePath, err := m.resolveFilePath(ctx, fileName)
if err != nil {
return "", fmt.Errorf("failed to resolve file path: %w", err)
}
// Check if object exists
_, err = m.client.StatObject(ctx, m.bucketName, filePath, minio.StatObjectOptions{})
if err != nil {
return "", fmt.Errorf("failed to get object stats: %w", err)
}
// Gerando URL assinada com validade de 7 dias
reqParams := make(url.Values)
presignedURL, err := m.client.PresignedGetObject(ctx, m.bucketName, filePath, time.Hour*24*7, reqParams)
if err != nil {
return "", fmt.Errorf("failed to generate presigned URL: %w", err)
}
fmt.Println(presignedURL.String())
return presignedURL.String(), nil
}
+62
View File
@@ -0,0 +1,62 @@
package telemetry
import (
"bytes"
"encoding/json"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
type TelemetryData struct {
Route string `json:"route"`
APIVersion string `json:"apiVersion"`
Timestamp time.Time `json:"timestamp"`
}
type telemetryService struct{}
func (t *telemetryService) TelemetryMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
route := c.FullPath()
go SendTelemetry(route)
c.Next()
}
}
type TelemetryService interface {
TelemetryMiddleware() gin.HandlerFunc
}
func SendTelemetry(route string) {
if route == "/" {
return
}
telemetry := TelemetryData{
Route: route,
APIVersion: "evo-go",
Timestamp: time.Now(),
}
url := "https://log.evolution-api.com/telemetry"
data, err := json.Marshal(telemetry)
if err != nil {
log.Println("Erro ao serializar telemetria:", err)
return
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))
if err != nil {
log.Println("Erro ao enviar telemetria:", err)
return
}
defer resp.Body.Close()
}
func NewTelemetryService() TelemetryService {
return &telemetryService{}
}
+551
View File
@@ -0,0 +1,551 @@
package user_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service"
"github.com/gin-gonic/gin"
)
type UserHandler interface {
GetUser(ctx *gin.Context)
CheckUser(ctx *gin.Context)
GetAvatar(ctx *gin.Context)
GetContacts(ctx *gin.Context)
GetPrivacy(ctx *gin.Context)
SetPrivacy(ctx *gin.Context)
BlockContact(ctx *gin.Context)
UnblockContact(ctx *gin.Context)
GetBlockList(ctx *gin.Context)
SetProfilePicture(ctx *gin.Context)
SetProfileName(ctx *gin.Context)
SetProfileStatus(ctx *gin.Context)
}
type userHandler struct {
userService user_service.UserService
}
// Get a user
// @Summary Get a user
// @Description Get a user
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.CheckUserStruct true "User data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/info [post]
func (u *userHandler) GetUser(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 *user_service.CheckUserStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(data.Number) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
uc, err := u.userService.GetUser(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": uc})
}
// Check a user
// @Summary Check a user
// @Description Check a user
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.CheckUserStruct true "User data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/check [post]
func (u *userHandler) CheckUser(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 *user_service.CheckUserStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(data.Number) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
uc, err := u.userService.CheckUser(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": uc})
}
// Get a user's avatar
// @Summary Get a user's avatar
// @Description Get a user's avatar
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.GetAvatarStruct true "Avatar data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/avatar [post]
func (u *userHandler) GetAvatar(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 *user_service.GetAvatarStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(data.Number) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
pic, err := u.userService.GetAvatar(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": pic})
}
// Get a user's contacts
// @Summary Get a user's contacts
// @Description Get a user's contacts
// @Tags User
// @Accept json
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/contacts [get]
func (u *userHandler) GetContacts(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
}
contacts, err := u.userService.GetContacts(instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": contacts})
}
// Get a user's privacy settings
// @Summary Get a user's privacy settings
// @Description Get a user's privacy settings
// @Tags User
// @Accept json
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/privacy [get]
func (u *userHandler) GetPrivacy(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
}
privacy, err := u.userService.GetPrivacy(instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": privacy})
}
// Set a user's privacy settings
// @Summary Set a user's privacy settings
// @Description Set a user's privacy settings
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.PrivacyStruct true "Privacy data"
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/privacy [post]
func (u *userHandler) SetPrivacy(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 *user_service.PrivacyStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.CallAdd == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "call add is required"})
return
}
if data.GroupAdd == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "group add is required"})
return
}
if data.LastSeen == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "last seen is required"})
return
}
if data.Online == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "online is required"})
return
}
if data.Profile == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "profile is required"})
return
}
if data.ReadReceipts == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "read receipts is required"})
return
}
if data.Status == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "status is required"})
return
}
privacy, err := u.userService.SetPrivacy(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": privacy})
}
// Block a contact
// @Summary Block a contact
// @Description Block a contact
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.BlockStruct true "Block data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/block [post]
func (u *userHandler) BlockContact(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 *user_service.BlockStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(data.Number) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
resp, err := u.userService.BlockContact(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Unblock a contact
// @Summary Unblock a contact
// @Description Unblock a contact
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.BlockStruct true "Block data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/unblock [post]
func (u *userHandler) UnblockContact(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 *user_service.BlockStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(data.Number) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
resp, err := u.userService.UnlockContact(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Get a user's block list
// @Summary Get a user's block list
// @Description Get a user's block list
// @Tags User
// @Accept json
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/blocklist [get]
func (u *userHandler) GetBlockList(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
}
resp, err := u.userService.GetBlockList(instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
// Set a user's profile picture
// @Summary Set a user's profile picture
// @Description Set a user's profile picture
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.SetProfilePictureStruct true "Profile picture data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/profilePicture [post]
func (u *userHandler) SetProfilePicture(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 *user_service.SetProfilePictureStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Image == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image is required"})
return
}
resp, err := u.userService.SetProfilePicture(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !resp {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set profile picture"})
return
}
responseData := gin.H{"image": data.Image}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// Set a user's profile name
// @Summary Set a user's profile name
// @Description Set a user's profile name
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.SetProfilePictureStruct true "Profile name data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/profileName [post]
func (u *userHandler) SetProfileName(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 *user_service.SetProfileNameStruct
err := ctx.ShouldBindBodyWithJSON(&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
}
resp, err := u.userService.SetProfileName(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !resp {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set profile picture"})
return
}
responseData := gin.H{"name": data.Name}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// Set a user's profile status
// @Summary Set a user's profile status
// @Description Set a user's profile status
// @Tags User
// @Accept json
// @Produce json
// @Param message body user_service.SetProfilePictureStruct true "Profile status data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /user/profileStatus [post]
func (u *userHandler) SetProfileStatus(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 *user_service.SetProfileStatusStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Status == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
return
}
resp, err := u.userService.SetProfileStatus(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !resp {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set profile picture"})
return
}
responseData := gin.H{"status": data.Status}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
func NewUserHandler(
userService user_service.UserService,
) UserHandler {
return &userHandler{
userService: userService,
}
}
+553
View File
@@ -0,0 +1,553 @@
package user_service
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
)
type UserService interface {
GetUser(data *CheckUserStruct, instance *instance_model.Instance) (*UserCollection, error)
CheckUser(data *CheckUserStruct, instance *instance_model.Instance) (*CheckUserCollection, error)
GetAvatar(data *GetAvatarStruct, instance *instance_model.Instance) (*types.ProfilePictureInfo, error)
GetContacts(instance *instance_model.Instance) ([]ContactInfo, error)
GetPrivacy(instance *instance_model.Instance) (types.PrivacySettings, error)
SetPrivacy(data *PrivacyStruct, instance *instance_model.Instance) (*types.PrivacySettings, error)
BlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error)
UnlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error)
GetBlockList(instance *instance_model.Instance) (*types.Blocklist, error)
SetProfilePicture(data *SetProfilePictureStruct, instance *instance_model.Instance) (bool, error)
SetProfileName(data *SetProfileNameStruct, instance *instance_model.Instance) (bool, error)
SetProfileStatus(data *SetProfileStatusStruct, instance *instance_model.Instance) (bool, error)
}
type userService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type ContactInfo struct {
Jid string `json:"Jid"`
Found bool `json:"Found"`
FirstName string `json:"FirstName"`
FullName string `json:"FullName"`
PushName string `json:"PushName"`
BusinessName string `json:"BusinessName"`
}
type UserInfo struct {
VerifiedName *types.VerifiedName
Status string
PictureID string
Devices []types.JID
LID *string // The local ID (if available)
}
type UserCollection struct {
Users map[types.JID]UserInfo
}
type User struct {
Query string
IsInWhatsapp bool
JID string
RemoteJID string
LID *string
VerifiedName string
}
type CheckUserCollection struct {
Users []User
}
type CheckUserStruct struct {
Number []string `json:"number"`
FormatJid *bool `json:"formatJid,omitempty"`
}
type GetAvatarStruct struct {
Number string `json:"number"`
Preview bool `json:"preview"`
}
type BlockStruct struct {
Number string `json:"number"`
}
type SetProfilePictureStruct struct {
Image string `json:"image"`
}
type SetProfileNameStruct struct {
Name string `json:"name"`
}
type SetProfileStatusStruct struct {
Status string `json:"status"`
}
type PrivacyStruct struct {
GroupAdd types.PrivacySetting `json:"groupAdd"`
LastSeen types.PrivacySetting `json:"lastSeen"`
Status types.PrivacySetting `json:"status"`
Profile types.PrivacySetting `json:"profile"`
ReadReceipts types.PrivacySetting `json:"readReceipts"`
CallAdd types.PrivacySetting `json:"callAdd"`
Online types.PrivacySetting `json:"online"`
}
func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := u.clientPointer[instanceId]
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := u.whatsmeowService.StartInstance(instanceId)
if err != nil {
u.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = u.clientPointer[instanceId]
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
u.loggerWrapper.GetLogger(instanceId).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() {
u.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (u *userService) GetUser(data *CheckUserStruct, instance *instance_model.Instance) (*UserCollection, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
var jids []types.JID
for _, arg := range data.Number {
jid, ok := utils.ParseJID(arg)
if !ok {
return nil, errors.New("invalid phone number")
}
jids = append(jids, jid)
}
resp, err := client.GetUserInfo(context.Background(), jids)
if err != nil {
return nil, err
}
uc := new(UserCollection)
uc.Users = make(map[types.JID]UserInfo)
for jid, whatsmeowInfo := range resp {
// Consultar LID Store para obter LID associado ao JID
var lidStr *string
if client.Store.LIDs != nil {
if lid, err := client.Store.LIDs.GetLIDForPN(context.TODO(), jid); err == nil && !lid.IsEmpty() {
lidString := fmt.Sprintf("%v", lid)
lidStr = &lidString
}
}
// Converter para nossa estrutura UserInfo que inclui LID
info := UserInfo{
VerifiedName: whatsmeowInfo.VerifiedName,
Status: whatsmeowInfo.Status,
PictureID: whatsmeowInfo.PictureID,
Devices: whatsmeowInfo.Devices,
LID: lidStr,
}
uc.Users[jid] = info
}
return uc, nil
}
func (u *userService) CheckUser(data *CheckUserStruct, instance *instance_model.Instance) (*CheckUserCollection, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
// Set formatJid to false by default for CheckUser
formatJid := false
if data.FormatJid != nil {
formatJid = *data.FormatJid
}
// First attempt with the requested formatJid setting
uc, shouldRetry := u.performCheckUser(client, data.Number, formatJid, instance.Id)
if !shouldRetry {
return uc, nil
}
// If formatJid was true and we got false results, retry with formatJid=false
if formatJid {
u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Some users not found with formatJid=true, retrying with formatJid=false", instance.Id)
ucRetry, _ := u.performCheckUser(client, data.Number, false, instance.Id)
// Merge results: use retry results for users that weren't found in first attempt
return u.mergeCheckUserResults(uc, ucRetry), nil
}
return uc, nil
}
// performCheckUser executes the actual user check with specified formatJid
func (u *userService) performCheckUser(client *whatsmeow.Client, numbers []string, formatJid bool, instanceId string) (*CheckUserCollection, bool) {
// Use centralized function to prepare numbers for WhatsApp check
phoneNumbers, err := utils.PrepareNumbersForWhatsAppCheck(numbers, &formatJid)
if err != nil {
u.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to prepare numbers for WhatsApp check: %v", instanceId, err)
return nil, false
}
resp, err := client.IsOnWhatsApp(context.Background(), phoneNumbers)
if err != nil {
u.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to check users on WhatsApp: %v", instanceId, err)
return nil, false
}
uc := new(CheckUserCollection)
shouldRetry := false
for _, item := range resp {
// Consultar LID Store para obter LID associado ao JID
var lidStr *string
if client.Store.LIDs != nil {
if lid, err := client.Store.LIDs.GetLIDForPN(context.TODO(), item.JID); err == nil && !lid.IsEmpty() {
lidString := fmt.Sprintf("%v", lid)
lidStr = &lidString
}
}
// Determine the RemoteJID to use for messaging
remoteJID := item.Query // Default to original query
if item.IsIn {
// When user exists on WhatsApp, use the JID returned by WhatsApp
remoteJID = fmt.Sprintf("%v", item.JID)
} else if formatJid {
// If user not found and we used formatJid=true, we should retry with formatJid=false
shouldRetry = true
}
if item.VerifiedName != nil {
var msg = User{
Query: item.Query,
IsInWhatsapp: item.IsIn,
JID: fmt.Sprintf("%v", item.JID),
RemoteJID: remoteJID,
LID: lidStr,
VerifiedName: item.VerifiedName.Details.GetVerifiedName(),
}
uc.Users = append(uc.Users, msg)
} else {
var msg = User{
Query: item.Query,
IsInWhatsapp: item.IsIn,
JID: fmt.Sprintf("%v", item.JID),
RemoteJID: remoteJID,
LID: lidStr,
VerifiedName: "",
}
uc.Users = append(uc.Users, msg)
}
}
return uc, shouldRetry
}
// mergeCheckUserResults merges results from two CheckUser attempts
// Priority: if a user is found in retry (formatJid=false), use that result
func (u *userService) mergeCheckUserResults(original, retry *CheckUserCollection) *CheckUserCollection {
if retry == nil {
return original
}
// Create a map of retry results by original query for quick lookup
retryMap := make(map[string]User)
for _, user := range retry.Users {
retryMap[user.Query] = user
}
// Merge results
merged := &CheckUserCollection{}
for _, originalUser := range original.Users {
if retryUser, exists := retryMap[originalUser.Query]; exists && retryUser.IsInWhatsapp && !originalUser.IsInWhatsapp {
// Use retry result if it found the user and original didn't
merged.Users = append(merged.Users, retryUser)
} else {
// Use original result
merged.Users = append(merged.Users, originalUser)
}
}
return merged
}
func (u *userService) GetAvatar(data *GetAvatarStruct, instance *instance_model.Instance) (*types.ProfilePictureInfo, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
// 🔒 FIX: Verificar se o cliente está conectado antes de fazer a requisição
if !client.IsConnected() {
return nil, errors.New("client is not connected to WhatsApp")
}
// 🔒 FIX: Verificar se o cliente está autenticado
if !client.IsLoggedIn() {
return nil, errors.New("client is not logged in to WhatsApp")
}
jid, ok := utils.ParseJID(data.Number)
if !ok {
return nil, errors.New("invalid phone number")
}
u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Requesting avatar for JID: %s, Preview: %v", instance.Id, jid, data.Preview)
var pic *types.ProfilePictureInfo
// 🔒 FIX: Adicionar timeout ao contexto para evitar que a requisição trave indefinidamente
// Usar timeout maior que o padrão do sendIQ (75s) para dar tempo suficiente
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Second)
defer cancel()
u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting GetProfilePictureInfo request...", instance.Id)
pic, err = client.GetProfilePictureInfo(ctx, jid, &whatsmeow.GetProfilePictureParams{
Preview: data.Preview,
})
if err != nil {
u.loggerWrapper.GetLogger(instance.Id).LogError("[%s] GetProfilePictureInfo failed: %v", instance.Id, err)
return nil, err
}
if pic == nil {
return nil, errors.New("no profile picture found")
}
u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Got avatar %s", instance.Id, pic.URL)
return pic, nil
}
func (u *userService) GetContacts(instance *instance_model.Instance) ([]ContactInfo, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
contacts, err := client.Store.Contacts.GetAllContacts(context.Background())
if err != nil {
return nil, err
}
var contactsArray []ContactInfo
for jid, contact := range contacts {
contactsArray = append(contactsArray, ContactInfo{
Jid: jid.String(),
Found: contact.Found,
FirstName: contact.FirstName,
FullName: contact.FullName,
PushName: contact.PushName,
BusinessName: contact.BusinessName,
})
}
return contactsArray, nil
}
func (u *userService) GetPrivacy(instance *instance_model.Instance) (types.PrivacySettings, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return types.PrivacySettings{}, err
}
privacy := client.GetPrivacySettings(context.Background())
return privacy, nil
}
func (u *userService) SetPrivacy(data *PrivacyStruct, instance *instance_model.Instance) (*types.PrivacySettings, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
privacySettings := []struct {
name types.PrivacySettingType
value types.PrivacySetting
}{
{types.PrivacySettingTypeGroupAdd, data.GroupAdd},
{types.PrivacySettingTypeLastSeen, data.LastSeen},
{types.PrivacySettingTypeStatus, data.Status},
{types.PrivacySettingTypeProfile, data.Profile},
{types.PrivacySettingTypeReadReceipts, data.ReadReceipts},
{types.PrivacySettingTypeCallAdd, data.CallAdd},
{types.PrivacySettingTypeOnline, data.Online},
}
for _, setting := range privacySettings {
_, err := client.SetPrivacySetting(context.Background(), setting.name, setting.value)
if err != nil {
return nil, err
}
}
privacy := client.GetPrivacySettings(context.Background())
return &privacy, nil
}
func (u *userService) BlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
jid, ok := utils.ParseJID(data.Number)
if !ok {
return nil, errors.New("invalid phone number")
}
resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionBlock)
if err != nil {
return nil, err
}
return resp, nil
}
func (u *userService) UnlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
jid, ok := utils.ParseJID(data.Number)
if !ok {
return nil, errors.New("invalid phone number")
}
resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionUnblock)
if err != nil {
return nil, err
}
return resp, nil
}
func (u *userService) GetBlockList(instance *instance_model.Instance) (*types.Blocklist, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
resp, err := client.GetBlocklist(context.Background())
if err != nil {
return nil, err
}
return resp, nil
}
func (u *userService) SetProfilePicture(data *SetProfilePictureStruct, instance *instance_model.Instance) (bool, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return false, err
}
var filedata []byte
resp, err := http.Get(data.Image)
if err != nil {
return false, fmt.Errorf("failed to fetch image from URL: %v", err)
}
defer resp.Body.Close()
filedata, err = io.ReadAll(resp.Body)
if err != nil {
return false, fmt.Errorf("failed to read image data: %v", err)
}
_, err = client.SetGroupPhoto(context.Background(), types.EmptyJID, filedata)
if err != nil {
return false, err
}
return true, nil
}
func (u *userService) SetProfileName(data *SetProfileNameStruct, instance *instance_model.Instance) (bool, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return false, err
}
err = client.SetGroupName(context.Background(), types.EmptyJID, data.Name)
if err != nil {
return false, err
}
return true, nil
}
func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *instance_model.Instance) (bool, error) {
client, err := u.ensureClientConnected(instance.Id)
if err != nil {
return false, err
}
err = client.SetStatusMessage(context.Background(), data.Status)
if err != nil {
return false, err
}
return true, nil
}
func NewUserService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) UserService {
return &userService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}
+575
View File
@@ -0,0 +1,575 @@
package utils
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"time"
"github.com/gomessguii/logger"
"go.mau.fi/whatsmeow/proto/waCompanionReg"
"go.mau.fi/whatsmeow/proto/waE2E"
whatsmeow_types "go.mau.fi/whatsmeow/types"
"golang.org/x/exp/rand"
"golang.org/x/net/proxy"
)
type Values struct {
m map[string]string
}
type VCardStruct struct {
FullName string `json:"fullName"`
Organization string `json:"organization"`
Phone string `json:"phone"`
}
func GenerateRandomString(length int) string {
characters := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, length)
for i := range b {
b[i] = characters[rand.Intn(len(characters))]
}
return string(b)
}
func Find(slice []string, val string) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
// CreateJID creates a properly formatted WhatsApp JID from a number string
// This function matches the TypeScript createJid functionality with enhanced validation
func CreateJID(number string) (string, error) {
if number == "" {
return "", fmt.Errorf("number cannot be empty")
}
// Remove timestamp suffix if present
// number = strings.Split(number, ":")[0]
// Check if already a valid JID format
if strings.Contains(number, "@g.us") ||
strings.Contains(number, "@s.whatsapp.net") ||
strings.Contains(number, "@lid") ||
strings.Contains(number, "@broadcast") ||
strings.Contains(number, "@newsletter") {
return number, nil
}
// Clean the number
number = strings.ReplaceAll(number, " ", "")
number = strings.ReplaceAll(number, "+", "")
number = strings.ReplaceAll(number, "(", "")
number = strings.ReplaceAll(number, ")", "")
number = strings.Split(number, ":")[0]
// Check if it's a group by hyphen and length
if strings.Contains(number, "-") && len(number) >= 24 {
// Remove non-digit and non-hyphen characters
groupID := strings.Map(func(r rune) rune {
if (r >= '0' && r <= '9') || r == '-' {
return r
}
return -1
}, number)
return groupID + "@g.us", nil
}
// Check if it's a group by length (18+ digits)
if len(number) >= 18 {
// Remove non-digit and non-hyphen characters
groupID := strings.Map(func(r rune) rune {
if (r >= '0' && r <= '9') || r == '-' {
return r
}
return -1
}, number)
return groupID + "@g.us", nil
}
// Remove all non-numeric characters for phone numbers
number = strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return r
}
return -1
}, number)
if number == "" {
return "", fmt.Errorf("invalid number format")
}
// Format MX (52) or AR (54) numbers
number = formatMXOrARNumber(number)
// Format BR (55) numbers
number = formatBRNumber(number)
// Add + prefix for international format
if !strings.HasPrefix(number, "+") {
number = "+" + number
}
return number + "@s.whatsapp.net", nil
}
// formatMXOrARNumber formats Mexican (52) or Argentine (54) numbers
func formatMXOrARNumber(jid string) string {
if len(jid) < 2 {
return jid
}
countryCode := jid[:2]
// Check if it's MX (52) or AR (54)
if countryCode == "52" && len(jid) == 13 {
// Mexico: remove 2 digits (positions 2-3)
// 5215551234567 -> 52 + 551234567 = 52551234567
return countryCode + jid[4:]
} else if countryCode == "54" && len(jid) == 13 {
// Argentina: remove 1 digit (position 2)
// 5411123456789 -> 54 + 11123456789 = 5411123456789
return countryCode + jid[3:]
}
return jid
}
// formatBRNumber formats Brazilian (55) numbers according to the mobile number rules
func formatBRNumber(jid string) string {
// Only process if it's exactly 13 digits and starts with "55"
if len(jid) != 13 || !strings.HasPrefix(jid, "55") {
return jid
}
// Extract DDD (area code) - should be between 11-99 for Brazil
ddd := jid[2:4]
// Convert DDD to integer for validation
dddNum, err := strconv.Atoi(ddd)
if err != nil {
return jid
}
// Brazilian DDD codes are between 11-99, if it's outside this range, it's not Brazil
if dddNum < 11 || dddNum > 99 {
return jid
}
// Extract the first digit after DDD
if len(jid) < 6 {
return jid
}
firstDigit := jid[4:5]
firstDigitNum, err := strconv.Atoi(firstDigit)
if err != nil {
return jid
}
// Check if it's a mobile number (9 prefix) and DDD >= 31
if firstDigitNum >= 7 && dddNum >= 31 {
// Remove the 9 prefix for mobile numbers with DDD >= 31
return jid[:4] + jid[5:]
}
// Keep the number as is (landline or special case)
return jid
}
// ParseJID parses a number string into a WhatsApp JID with validation
func ParseJID(arg string) (whatsmeow_types.JID, bool) {
if arg == "" {
return whatsmeow_types.NewJID("", whatsmeow_types.DefaultUserServer), false
}
// Use CreateJID for consistent formatting
jidString, err := CreateJID(arg)
if err != nil {
logger.LogWarn("Failed to create JID: %s", err.Error())
return whatsmeow_types.NewJID("", whatsmeow_types.DefaultUserServer), false
}
// Parse the formatted JID
recipient, err := whatsmeow_types.ParseJID(jidString)
if err != nil {
logger.LogWarn("Invalid JID: %s", err.Error())
return recipient, false
}
if recipient.User == "" && !strings.Contains(jidString, "@broadcast") {
logger.LogError("Invalid JID. No user specified: %s", jidString)
return recipient, false
}
return recipient, true
}
func CreateHTTPProxy(httpHost, httpPort, user, password string) (func(*http.Request) (*url.URL, error), error) {
address := fmt.Sprintf("http://%s:%s@%s:%s", user, password, httpHost, httpPort)
parsed, err := url.Parse(address)
if err != nil {
return nil, err
}
return http.ProxyURL(parsed), nil
}
func CreateSocks5Proxy(socks5Host, socks5Port, user, password string) (proxy.Dialer, error) {
auth := &proxy.Auth{
User: user,
Password: password,
}
dialer, err := proxy.SOCKS5("tcp", fmt.Sprintf("%s:%s", socks5Host, socks5Port), auth, proxy.Direct)
if err != nil {
return nil, err
}
return dialer, nil
// return func(req *http.Request) (*url.URL, error) {
// host := req.URL.Host
// if !strings.Contains(host, ":") {
// host = fmt.Sprintf("%s:443", host) // Adiciona porta padrão 443 se não especificada
// }
// conn, err := dialer.Dial("tcp", host)
// if err != nil {
// return nil, err
// }
// defer conn.Close()
// return nil, nil
// }, nil
}
func UpdateUserInfo(values interface{}, field string, value string) interface{} {
v, ok := values.(Values)
if !ok {
logger.LogError("Failed to cast values to Values type")
return values
}
logger.LogDebug("User info updated field: %s value: %s", field, value)
v.m[field] = value
return v
}
func TimestampToUnixInt(timestamp string) (int64, error) {
layout := "2006-01-02 15:04:05"
t, err := time.Parse(layout, timestamp)
if err != nil {
return 0, err
}
unixTimestamp := t.Unix()
return unixTimestamp, nil
}
func GenerateVC(data VCardStruct) string {
result := `
BEGIN:VCARD
VERSION:3.0
FN:` + data.FullName + `
ORG:` + data.Organization + `;
TEL;type=CELL;type=VOICE;waid=` + data.Phone + `:` + data.Phone + `
END:VCARD`
return result
}
func GetObject(message []byte, keyFind string) string {
var messageMap map[string]interface{}
err := json.Unmarshal(message, &messageMap)
if err != nil {
logger.LogError("failed to unmarshal message: %s", err)
return ""
}
for key, value := range messageMap {
if key == keyFind {
if captionStr, ok := value.(string); ok {
return captionStr
}
}
if nestedMap, ok := value.(map[string]interface{}); ok {
nestedMapBytes, err := json.Marshal(nestedMap)
if err != nil {
logger.LogError("failed to marshal nestedMap: %s", err)
continue
}
if caption := GetObject(nestedMapBytes, keyFind); caption != "" {
return caption
}
}
}
return ""
}
func WhatsAppGetUserOS() string {
switch runtime.GOOS {
case "windows":
return "Windows"
case "darwin":
return "macOS"
default:
return "Linux"
}
}
func WhatsAppGetUserAgent(agentType string) waCompanionReg.DeviceProps_PlatformType {
switch strings.ToLower(agentType) {
case "desktop":
return waCompanionReg.DeviceProps_DESKTOP
case "mac":
return waCompanionReg.DeviceProps_CATALINA
case "android":
return waCompanionReg.DeviceProps_ANDROID_AMBIGUOUS
case "android-phone":
return waCompanionReg.DeviceProps_ANDROID_PHONE
case "andorid-tablet":
return waCompanionReg.DeviceProps_ANDROID_TABLET
case "ios-phone":
return waCompanionReg.DeviceProps_IOS_PHONE
case "ios-catalyst":
return waCompanionReg.DeviceProps_IOS_CATALYST
case "ipad":
return waCompanionReg.DeviceProps_IPAD
case "wearos":
return waCompanionReg.DeviceProps_WEAR_OS
case "ie":
return waCompanionReg.DeviceProps_IE
case "edge":
return waCompanionReg.DeviceProps_EDGE
case "chrome":
return waCompanionReg.DeviceProps_CHROME
case "safari":
return waCompanionReg.DeviceProps_SAFARI
case "firefox":
return waCompanionReg.DeviceProps_FIREFOX
case "opera":
return waCompanionReg.DeviceProps_OPERA
case "uwp":
return waCompanionReg.DeviceProps_UWP
case "aloha":
return waCompanionReg.DeviceProps_ALOHA
case "tv-tcl":
return waCompanionReg.DeviceProps_TCL_TV
default:
return waCompanionReg.DeviceProps_UNKNOWN
}
}
func GetMessageType(waMsg *waE2E.Message) string {
switch {
case waMsg == nil:
return "ignore"
case waMsg.Conversation != nil, waMsg.ExtendedTextMessage != nil:
return "text"
case waMsg.ImageMessage != nil:
return fmt.Sprintf("image %s", waMsg.GetImageMessage().GetMimetype())
case waMsg.StickerMessage != nil:
return fmt.Sprintf("sticker %s", waMsg.GetStickerMessage().GetMimetype())
case waMsg.VideoMessage != nil:
return fmt.Sprintf("video %s", waMsg.GetVideoMessage().GetMimetype())
case waMsg.PtvMessage != nil:
return fmt.Sprintf("round video %s", waMsg.GetPtvMessage().GetMimetype())
case waMsg.AudioMessage != nil:
return fmt.Sprintf("audio %s", waMsg.GetAudioMessage().GetMimetype())
case waMsg.DocumentMessage != nil:
return fmt.Sprintf("document %s", waMsg.GetDocumentMessage().GetMimetype())
case waMsg.ContactMessage != nil:
return "contact"
case waMsg.ContactsArrayMessage != nil:
return "contact array"
case waMsg.LocationMessage != nil:
return "location"
case waMsg.LiveLocationMessage != nil:
return "live location start"
case waMsg.GroupInviteMessage != nil:
return "group invite"
case waMsg.GroupMentionedMessage != nil:
return "group mention"
case waMsg.ScheduledCallCreationMessage != nil:
return "scheduled call create"
case waMsg.ScheduledCallEditMessage != nil:
return "scheduled call edit"
case waMsg.ReactionMessage != nil:
if waMsg.ReactionMessage.GetText() == "" {
return "reaction remove"
}
return "reaction"
case waMsg.EncReactionMessage != nil:
return "encrypted reaction"
case waMsg.PollCreationMessage != nil || waMsg.PollCreationMessageV2 != nil || waMsg.PollCreationMessageV3 != nil:
return "poll create"
case waMsg.PollUpdateMessage != nil:
return "poll update"
case waMsg.ProtocolMessage != nil:
switch waMsg.GetProtocolMessage().GetType() {
case waE2E.ProtocolMessage_REVOKE:
if waMsg.GetProtocolMessage().GetKey() == nil {
return "ignore"
}
return "revoke"
case waE2E.ProtocolMessage_MESSAGE_EDIT:
return "edit"
case waE2E.ProtocolMessage_EPHEMERAL_SETTING:
return "disappearing timer change"
case waE2E.ProtocolMessage_APP_STATE_SYNC_KEY_SHARE,
waE2E.ProtocolMessage_HISTORY_SYNC_NOTIFICATION,
waE2E.ProtocolMessage_INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC:
return "ignore"
default:
return fmt.Sprintf("unknown_protocol_%d", waMsg.GetProtocolMessage().GetType())
}
case waMsg.ButtonsMessage != nil:
return "buttons"
case waMsg.ButtonsResponseMessage != nil:
return "buttons response"
case waMsg.TemplateMessage != nil:
return "template"
case waMsg.HighlyStructuredMessage != nil:
return "highly structured template"
case waMsg.TemplateButtonReplyMessage != nil:
return "template button reply"
case waMsg.InteractiveMessage != nil:
return "interactive"
case waMsg.ListMessage != nil:
return "list"
case waMsg.ProductMessage != nil:
return "product"
case waMsg.ListResponseMessage != nil:
return "list response"
case waMsg.OrderMessage != nil:
return "order"
case waMsg.InvoiceMessage != nil:
return "invoice"
case waMsg.BotInvokeMessage != nil:
return "bot invoke"
case waMsg.EventMessage != nil:
return "event"
case waMsg.EventCoverImage != nil:
return "event cover image"
case waMsg.EncEventResponseMessage != nil:
return "ignore" // these are ignored for now as they're not meant to be shown as new messages
//return "encrypted event response"
case waMsg.CommentMessage != nil:
return "comment"
case waMsg.EncCommentMessage != nil:
return "encrypted comment"
case waMsg.NewsletterAdminInviteMessage != nil:
return "newsletter admin invite"
case waMsg.SecretEncryptedMessage != nil:
return "secret encrypted"
case waMsg.PollResultSnapshotMessage != nil:
return "poll result snapshot"
case waMsg.MessageHistoryBundle != nil:
return "message history bundle"
case waMsg.RequestPhoneNumberMessage != nil:
return "request phone number"
case waMsg.KeepInChatMessage != nil:
return "keep in chat"
case waMsg.StatusMentionMessage != nil:
return "status mention"
case waMsg.StickerPackMessage != nil:
return "sticker pack"
case waMsg.AlbumMessage != nil:
return "album" // or maybe these should be ignored?
case waMsg.SendPaymentMessage != nil, waMsg.RequestPaymentMessage != nil,
waMsg.DeclinePaymentRequestMessage != nil, waMsg.CancelPaymentRequestMessage != nil,
waMsg.PaymentInviteMessage != nil:
return "payment"
case waMsg.Call != nil:
return "call"
case waMsg.Chat != nil:
return "chat"
case waMsg.PlaceholderMessage != nil:
return "placeholder"
case waMsg.SenderKeyDistributionMessage != nil, waMsg.StickerSyncRmrMessage != nil:
return "ignore"
default:
return "unknown"
}
}
func GetStringValue(s *string) string {
if s == nil {
return ""
}
return *s
}
// PrepareNumbersForWhatsAppCheck prepares phone numbers for IsOnWhatsApp call
// based on formatJid flag. This centralizes the logic used by both CheckUser and SendText.
func PrepareNumbersForWhatsAppCheck(numbers []string, formatJid *bool) ([]string, error) {
// Default formatJid to true if not specified
shouldFormat := true
if formatJid != nil {
shouldFormat = *formatJid
}
var phoneNumbers []string
if shouldFormat {
// Normalize numbers using CreateJID for consistent formatting
for _, number := range numbers {
// First, extract the raw number if it's already a JID
rawNumber := number
if strings.Contains(number, "@s.whatsapp.net") {
rawNumber = strings.Split(number, "@")[0]
}
// Use CreateJID to normalize the raw number format
normalizedJID, err := CreateJID(rawNumber)
if err != nil {
// Continue with original number if normalization fails
phoneNumbers = append(phoneNumbers, number)
continue
}
// Extract the phone number part from the JID for IsOnWhatsApp call
// e.g., "[email protected]" -> "+5511999999999" (keep + for IsOnWhatsApp)
if strings.Contains(normalizedJID, "@s.whatsapp.net") {
phoneNumber := strings.Split(normalizedJID, "@")[0]
phoneNumbers = append(phoneNumbers, phoneNumber)
} else if strings.Contains(normalizedJID, "@g.us") || strings.Contains(normalizedJID, "@broadcast") || strings.Contains(normalizedJID, "@lid") {
// For groups, broadcasts, and LIDs, use the full JID
phoneNumbers = append(phoneNumbers, normalizedJID)
} else {
phoneNumbers = append(phoneNumbers, normalizedJID)
}
}
} else {
// Use numbers exactly as received (raw format)
phoneNumbers = append(phoneNumbers, numbers...)
}
return phoneNumbers, nil
}
// PrepareNumberForWhatsAppCheck prepares a single phone number for IsOnWhatsApp call
// This is used by SendText which works with single numbers
func PrepareNumberForWhatsAppCheck(phone string, formatJid bool) (string, error) {
formatJidPtr := &formatJid
numbers, err := PrepareNumbersForWhatsAppCheck([]string{phone}, formatJidPtr)
if err != nil {
return "", err
}
if len(numbers) == 0 {
return "", fmt.Errorf("no valid number processed")
}
return numbers[0], nil
}
+327
View File
@@ -0,0 +1,327 @@
package utils
import (
"testing"
)
func TestCreateJID(t *testing.T) {
tests := []struct {
name string
input string
expected string
hasError bool
}{
// Basic phone numbers
{
name: "Simple US number",
input: "15551234567",
expected: "[email protected]",
hasError: false,
},
{
name: "Number with spaces and parentheses",
input: "+1 (555) 123-4567",
expected: "[email protected]",
hasError: false,
},
// Brazilian numbers (55)
{
name: "BR mobile number with 9 prefix - should remove 9",
input: "5531987654321",
expected: "[email protected]",
hasError: false,
},
{
name: "BR landline number - should keep as is",
input: "5531123456789",
expected: "[email protected]",
hasError: false,
},
{
name: "BR number with DDD < 31 - should keep as is",
input: "5521987654321",
expected: "[email protected]",
hasError: false,
},
{
name: "BR number with first digit < 7 - should keep as is",
input: "5531687654321",
expected: "[email protected]",
hasError: false,
},
// Portuguese numbers (351) - should not be treated as Brazilian
{
name: "Portugal number - should not apply BR formatting",
input: "351932933862",
expected: "[email protected]",
hasError: false,
},
{
name: "Portugal number with + - should not apply BR formatting",
input: "+351932933862",
expected: "[email protected]",
hasError: false,
},
// Mexican numbers (52)
{
name: "MX number with extra digit - should remove",
input: "5215551234567",
expected: "[email protected]",
hasError: false,
},
{
name: "MX number without extra digit",
input: "525551234567",
expected: "[email protected]",
hasError: false,
},
// Argentine numbers (54)
{
name: "AR number with extra digit - should remove",
input: "5411123456789",
expected: "[email protected]",
hasError: false,
},
// Group IDs
{
name: "Group ID with hyphen",
input: "[email protected]",
expected: "[email protected]",
hasError: false,
},
{
name: "Group ID by length",
input: "120363123456789012345",
expected: "[email protected]",
hasError: false,
},
{
name: "Group ID with hyphen and extra chars",
input: "120363-123456789012-345abc",
expected: "[email protected]",
hasError: false,
},
// Already formatted JIDs
{
name: "Already formatted user JID",
input: "[email protected]",
expected: "[email protected]",
hasError: false,
},
{
name: "Already formatted group JID",
input: "[email protected]",
expected: "[email protected]",
hasError: false,
},
{
name: "Broadcast JID",
input: "status@broadcast",
expected: "status@broadcast",
hasError: false,
},
{
name: "LID JID",
input: "12345@lid",
expected: "12345@lid",
hasError: false,
},
// Error cases
{
name: "Empty string",
input: "",
expected: "",
hasError: true,
},
{
name: "Only special characters",
input: "+-()@#$%",
expected: "",
hasError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := CreateJID(tt.input)
if tt.hasError {
if err == nil {
t.Errorf("Expected error for input %q, but got none", tt.input)
}
return
}
if err != nil {
t.Errorf("Unexpected error for input %q: %v", tt.input, err)
return
}
if result != tt.expected {
t.Errorf("For input %q, expected %q, but got %q", tt.input, tt.expected, result)
}
})
}
}
func TestFormatMXOrARNumber(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "MX number with 13 digits",
input: "5215551234567",
expected: "52551234567",
},
{
name: "MX number with 12 digits",
input: "525551234567",
expected: "525551234567",
},
{
name: "AR number with 13 digits",
input: "5411123456789",
expected: "541123456789",
},
{
name: "Non-MX/AR number",
input: "5511987654321",
expected: "5511987654321",
},
{
name: "Short number",
input: "52",
expected: "52",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := formatMXOrARNumber(tt.input)
if result != tt.expected {
t.Errorf("For input %q, expected %q, but got %q", tt.input, tt.expected, result)
}
})
}
}
func TestFormatBRNumber(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "BR mobile number with DDD >= 31 and 9 prefix",
input: "5531987654321",
expected: "553187654321",
},
{
name: "BR number with DDD < 31",
input: "5521987654321",
expected: "5521987654321",
},
{
name: "BR number with first digit < 7",
input: "5531687654321",
expected: "5531687654321",
},
{
name: "Non-BR number",
input: "15551234567",
expected: "15551234567",
},
{
name: "BR number with wrong length",
input: "551198765432",
expected: "551198765432",
},
{
name: "BR landline number",
input: "5531123456789",
expected: "5531123456789",
},
{
name: "Portugal number starting with 55 - should not be treated as BR",
input: "351932933862",
expected: "351932933862",
},
{
name: "Number starting with 55 but invalid DDD - should not be treated as BR",
input: "5509987654321",
expected: "5509987654321",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := formatBRNumber(tt.input)
if result != tt.expected {
t.Errorf("For input %q, expected %q, but got %q", tt.input, tt.expected, result)
}
})
}
}
func TestParseJID(t *testing.T) {
tests := []struct {
name string
input string
expectOk bool
expectJID string
}{
{
name: "Valid phone number",
input: "15551234567",
expectOk: true,
expectJID: "[email protected]",
},
{
name: "Valid BR number",
input: "5531987654321",
expectOk: true,
expectJID: "[email protected]",
},
{
name: "Valid group ID",
input: "[email protected]",
expectOk: true,
expectJID: "[email protected]",
},
{
name: "Empty string",
input: "",
expectOk: false,
expectJID: "@s.whatsapp.net",
},
{
name: "Invalid format",
input: "+-()@#$%",
expectOk: false,
expectJID: "@s.whatsapp.net",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jid, ok := ParseJID(tt.input)
if ok != tt.expectOk {
t.Errorf("For input %q, expected ok=%v, but got ok=%v", tt.input, tt.expectOk, ok)
}
if tt.expectOk && jid.String() != tt.expectJID {
t.Errorf("For input %q, expected JID %q, but got %q", tt.input, tt.expectJID, jid.String())
}
})
}
}
File diff suppressed because it is too large. Load diff