sync: 0.7.0 from main (3f0d10f172101035f4e0f736695e1700ee1ec967)

This commit is contained in:
github-actions[bot] committed 2026-04-17 18:41:28 +00:00
1 parent 182a719053
commit fdf612350a
34 files changed
+2032 -430

No files matched your search

+3
View File
@@ -47,6 +47,7 @@ type Config struct {
WhatsappVersionMajor int
WhatsappVersionMinor int
WhatsappVersionPatch int
ProxyProtocol string
ProxyHost string
ProxyPort string
ProxyUsername string
@@ -265,6 +266,7 @@ func Load() *Config {
whatsappVersionMinor := os.Getenv(config_env.WHATSAPP_VERSION_MINOR)
whatsappVersionPatch := os.Getenv(config_env.WHATSAPP_VERSION_PATCH)
proxyProtocol := os.Getenv(config_env.PROXY_PROTOCOL)
proxyHost := os.Getenv(config_env.PROXY_HOST)
proxyPort := os.Getenv(config_env.PROXY_PORT)
proxyUsername := os.Getenv(config_env.PROXY_USERNAME)
@@ -365,6 +367,7 @@ func Load() *Config {
WhatsappVersionMajor: major,
WhatsappVersionMinor: minor,
WhatsappVersionPatch: patch,
ProxyProtocol: proxyProtocol,
ProxyHost: proxyHost,
ProxyPort: proxyPort,
ProxyUsername: proxyUsername,
+1
View File
@@ -33,6 +33,7 @@ const (
WHATSAPP_VERSION_MAJOR = "WHATSAPP_VERSION_MAJOR"
WHATSAPP_VERSION_MINOR = "WHATSAPP_VERSION_MINOR"
WHATSAPP_VERSION_PATCH = "WHATSAPP_VERSION_PATCH"
PROXY_PROTOCOL = "PROXY_PROTOCOL"
PROXY_HOST = "PROXY_HOST"
PROXY_PORT = "PROXY_PORT"
PROXY_USERNAME = "PROXY_USERNAME"
+257 -209
View File
@@ -24,17 +24,17 @@ import (
"time"
)
var _k1 = []byte{0x92, 0x8a, 0x16, 0xa6, 0xfe, 0xe4, 0x09, 0xeb, 0xf6, 0x25, 0xd6, 0xf3, 0x94, 0x0f, 0x76, 0xef, 0x38, 0x68, 0xe0, 0x52, 0x4e, 0xca, 0x54, 0x25, 0x4b, 0x93, 0x52, 0xc6, 0x5a, 0x59, 0x4e, 0x64, 0xa7, 0xce, 0x48, 0x22, 0x7f, 0x04, 0x3c, 0x59, 0x0e, 0x3b}
var _k0 = []byte{0xfa, 0xfe, 0x62, 0xd6, 0x8d, 0xde, 0x26, 0xc4, 0x9a, 0x4c, 0xb5, 0x96, 0xfa, 0x7c, 0x13, 0xc1, 0x5d, 0x1e, 0x8f, 0x3e, 0x3b, 0xbe, 0x3d, 0x4a, 0x25, 0xf5, 0x3d, 0xb3, 0x34, 0x3d, 0x2f, 0x10, 0xce, 0xa1, 0x26, 0x0c, 0x1c, 0x6b, 0x51, 0x77, 0x6c, 0x49}
var _k1 = []byte{0x88, 0xe1, 0xd0, 0x50, 0x74, 0x8f, 0xb5, 0x64, 0x84, 0xbe, 0xa9, 0xbe, 0xeb, 0x45, 0xc1, 0x4d, 0x11, 0x75, 0xc3, 0xc4, 0x4a, 0x51, 0x4b, 0xdf, 0x50, 0xb6, 0x83, 0xd2, 0x07, 0xbe, 0x67, 0x27, 0xdc, 0x03, 0xe7, 0x2e, 0x50, 0xad, 0xbb, 0x50, 0x40, 0x55}
var _k0 = []byte{0xe0, 0x95, 0xa4, 0x20, 0x07, 0xb5, 0x9a, 0x4b, 0xe8, 0xd7, 0xca, 0xdb, 0x85, 0x36, 0xa4, 0x63, 0x74, 0x03, 0xac, 0xa8, 0x3f, 0x25, 0x22, 0xb0, 0x3e, 0xd0, 0xec, 0xa7, 0x69, 0xda, 0x06, 0x53, 0xb5, 0x6c, 0x89, 0x00, 0x33, 0xc2, 0xd6, 0x7e, 0x22, 0x27}
var (
_w3s9 string
_jl7 string
_jyou string
_1h string
)
func _rmo() string {
if _w3s9 != "" && _jl7 != "" {
return _4drn(_w3s9, _jl7)
func _c0u() string {
if _jyou != "" && _1h != "" {
return _dv(_jyou, _1h)
}
parts := [...]string{"h", "tt", "ps", "://", "li", "ce", "nse", ".", "ev", "ol", "ut", "io", "nf", "ou", "nd", "at", "io", "n.", "co", "m.", "br"}
var s string
@@ -44,9 +44,9 @@ func _rmo() string {
return s
}
func _4drn(enc, key string) string {
encBytes := _iz6(enc)
keyBytes := _iz6(key)
func _dv(enc, key string) string {
encBytes := _3z(enc)
keyBytes := _3z(key)
if len(keyBytes) == 0 {
return ""
}
@@ -57,18 +57,18 @@ func _4drn(enc, key string) string {
return string(out)
}
func _iz6(s string) []byte {
func _3z(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] = _xtts(s[i])<<4 | _xtts(s[i+1])
b[i/2] = _323(s[i])<<4 | _323(s[i+1])
}
return b
}
func _xtts(c byte) byte {
func _323(c byte) byte {
switch {
case c >= '0' && c <= '9':
return c - '0'
@@ -80,62 +80,62 @@ func _xtts(c byte) byte {
return 0
}
var _ls61 = &http.Client{Timeout: 10 * time.Second}
var _e97 = &http.Client{Timeout: 10 * time.Second}
func _t5d(body []byte, secret string) string {
func _48bz(body []byte, secret string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
return hex.EncodeToString(mac.Sum(nil))
}
func _rkb(path string, payload interface{}, _jpwr string) (*http.Response, error) {
func _i9r(path string, payload interface{}, _94b string) (*http.Response, error) {
body, err := json.Marshal(payload)
if err != nil {
return nil, err
}
url := _rmo() + path
url := _c0u() + 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", _jpwr)
req.Header.Set("X-Signature", _t5d(body, _jpwr))
req.Header.Set("X-Api-Key", _94b)
req.Header.Set("X-Signature", _48bz(body, _94b))
return _ls61.Do(req)
return _e97.Do(req)
}
func _qfhm(path string) (*http.Response, error) {
url := _rmo() + path
return _ls61.Get(url)
func _3r(path string) (*http.Response, error) {
url := _c0u() + path
return _e97.Get(url)
}
func _pzi6(path string, payload interface{}) (*http.Response, error) {
func _7n05(path string, payload interface{}) (*http.Response, error) {
body, err := json.Marshal(payload)
if err != nil {
return nil, err
}
url := _rmo() + path
url := _c0u() + 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 _ls61.Do(req)
return _e97.Do(req)
}
func _2l4(resp *http.Response) error {
func _39pp(resp *http.Response) error {
b, _ := io.ReadAll(resp.Body)
var _28 struct {
var _p2d struct {
Message string `json:"message"`
Error string `json:"error"`
}
if err := json.Unmarshal(b, &_28); err == nil {
msg := _28.Message
if err := json.Unmarshal(b, &_p2d); err == nil {
msg := _p2d.Message
if msg == "" {
msg = _28.Error
msg = _p2d.Error
}
if msg != "" {
return fmt.Errorf("%s (HTTP %d)", strings.ToLower(msg), resp.StatusCode)
@@ -163,48 +163,48 @@ const (
ConfigKeyCustomerID = "customer_id"
)
var _4k *gorm.DB
var _wd83 *gorm.DB
func SetDB(db *gorm.DB) {
_4k = db
_wd83 = db
}
func MigrateDB() error {
if _4k == nil {
if _wd83 == nil {
return fmt.Errorf("core: database not set, call SetDB first")
}
return _4k.AutoMigrate(&RuntimeConfig{})
return _wd83.AutoMigrate(&RuntimeConfig{})
}
func _di(key string) (string, error) {
if _4k == nil {
func _2z(key string) (string, error) {
if _wd83 == nil {
return "", fmt.Errorf("core: database not set")
}
var _lac RuntimeConfig
_x1 := _4k.Where("key = ?", key).First(&_lac)
if _x1.Error != nil {
return "", _x1.Error
var _hh54 RuntimeConfig
_ve := _wd83.Where("key = ?", key).First(&_hh54)
if _ve.Error != nil {
return "", _ve.Error
}
return _lac.Value, nil
return _hh54.Value, nil
}
func _o35(key, value string) error {
if _4k == nil {
func _7pe(key, value string) error {
if _wd83 == nil {
return fmt.Errorf("core: database not set")
}
var _lac RuntimeConfig
_x1 := _4k.Where("key = ?", key).First(&_lac)
if _x1.Error != nil {
return _4k.Create(&RuntimeConfig{Key: key, Value: value}).Error
var _hh54 RuntimeConfig
_ve := _wd83.Where("key = ?", key).First(&_hh54)
if _ve.Error != nil {
return _wd83.Create(&RuntimeConfig{Key: key, Value: value}).Error
}
return _4k.Model(&_lac).Update("value", value).Error
return _wd83.Model(&_hh54).Update("value", value).Error
}
func _nre(key string) {
if _4k == nil {
func _5i(key string) {
if _wd83 == nil {
return
}
_4k.Where("key = ?", key).Delete(&RuntimeConfig{})
_wd83.Where("key = ?", key).Delete(&RuntimeConfig{})
}
type RuntimeData struct {
@@ -213,67 +213,67 @@ type RuntimeData struct {
CustomerID int
}
func _8ftv() (*RuntimeData, error) {
_jpwr, err := _di(ConfigKeyAPIKey)
if err != nil || _jpwr == "" {
func _vk() (*RuntimeData, error) {
_94b, err := _2z(ConfigKeyAPIKey)
if err != nil || _94b == "" {
return nil, fmt.Errorf("no license found")
}
_y6, _ := _di(ConfigKeyTier)
customerIDStr, _ := _di(ConfigKeyCustomerID)
_pkj, _ := _2z(ConfigKeyTier)
customerIDStr, _ := _2z(ConfigKeyCustomerID)
customerID, _ := strconv.Atoi(customerIDStr)
return &RuntimeData{
APIKey: _jpwr,
Tier: _y6,
APIKey: _94b,
Tier: _pkj,
CustomerID: customerID,
}, nil
}
func _nk7y(rd *RuntimeData) error {
if err := _o35(ConfigKeyAPIKey, rd.APIKey); err != nil {
func _b7mk(rd *RuntimeData) error {
if err := _7pe(ConfigKeyAPIKey, rd.APIKey); err != nil {
return err
}
if err := _o35(ConfigKeyTier, rd.Tier); err != nil {
if err := _7pe(ConfigKeyTier, rd.Tier); err != nil {
return err
}
if rd.CustomerID > 0 {
if err := _o35(ConfigKeyCustomerID, strconv.Itoa(rd.CustomerID)); err != nil {
if err := _7pe(ConfigKeyCustomerID, strconv.Itoa(rd.CustomerID)); err != nil {
return err
}
}
return nil
}
func _9s() {
_nre(ConfigKeyAPIKey)
_nre(ConfigKeyTier)
_nre(ConfigKeyCustomerID)
func _q2pm() {
_5i(ConfigKeyAPIKey)
_5i(ConfigKeyTier)
_5i(ConfigKeyCustomerID)
}
func _viat() (string, error) {
id, err := _di(ConfigKeyInstanceID)
func _ix() (string, error) {
id, err := _2z(ConfigKeyInstanceID)
if err == nil && len(id) == 36 {
return id, nil
}
id = _ead()
id = _d6()
if id == "" {
id, err = _hxo()
id, err = _yb7k()
if err != nil {
return "", err
}
}
if err := _o35(ConfigKeyInstanceID, id); err != nil {
if err := _7pe(ConfigKeyInstanceID, id); err != nil {
return "", err
}
return id, nil
}
func _ead() string {
func _d6() string {
hostname, _ := os.Hostname()
macAddr := _g9n9()
macAddr := _efr()
if hostname == "" && macAddr == "" {
return ""
}
@@ -284,13 +284,13 @@ func _ead() string {
for i := 16; i < len(seed); i++ {
h[i%16] ^= seed[i]
}
h[6] = (h[6] & 0x0f) | 0x40 // _h7 4
h[6] = (h[6] & 0x0f) | 0x40 // _an 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 _g9n9() string {
func _efr() string {
interfaces, err := net.Interfaces()
if err != nil {
return ""
@@ -306,7 +306,7 @@ func _g9n9() string {
return ""
}
func _hxo() (string, error) {
func _yb7k() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
@@ -317,20 +317,20 @@ func _hxo() (string, error) {
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}
var _l3rh atomic.Value // set during activation
var _2p6 atomic.Value // set during activation
func init() {
_l3rh.Store([]byte{0})
_2p6.Store([]byte{0})
}
func ComputeSessionSeed(instanceName string, rc *RuntimeContext) []byte {
if rc == nil || !rc._xk65.Load() {
if rc == nil || !rc._6l.Load() {
return nil // Will cause panic in caller — intentional
}
h := sha256.New()
h.Write([]byte(instanceName))
h.Write([]byte(rc._jpwr))
salt, _ := _l3rh.Load().([]byte)
h.Write([]byte(rc._94b))
salt, _ := _2p6.Load().([]byte)
h.Write(salt)
return h.Sum(nil)[:16]
}
@@ -343,20 +343,20 @@ func ValidateRouteAccess(rc *RuntimeContext) uint64 {
return binary.LittleEndian.Uint64(h[:8])
}
func DeriveInstanceToken(_645 string, rc *RuntimeContext) string {
if rc == nil || !rc._xk65.Load() {
func DeriveInstanceToken(_32d string, rc *RuntimeContext) string {
if rc == nil || !rc._6l.Load() {
return ""
}
h := sha256.Sum256([]byte(_645 + rc._jpwr))
return _yls(h[:8])
h := sha256.Sum256([]byte(_32d + rc._94b))
return _w5(h[:8])
}
func _yls(b []byte) string {
const _5swh = "0123456789abcdef"
func _w5(b []byte) string {
const _0q2 = "0123456789abcdef"
dst := make([]byte, len(b)*2)
for i, v := range b {
dst[i*2] = _5swh[v>>4]
dst[i*2+1] = _5swh[v&0x0f]
dst[i*2] = _0q2[v>>4]
dst[i*2+1] = _0q2[v&0x0f]
}
return string(dst)
}
@@ -365,8 +365,8 @@ func ActivateIntegrity(rc *RuntimeContext) {
if rc == nil {
return
}
h := sha256.Sum256([]byte(rc._jpwr + rc._645 + "ev0"))
_l3rh.Store(h[:])
h := sha256.Sum256([]byte(rc._94b + rc._32d + "ev0"))
_2p6.Store(h[:])
}
const (
@@ -374,101 +374,129 @@ const (
)
type RuntimeContext struct {
_jpwr string
_444 string // GLOBAL_API_KEY from .env — used as token for licensing check
_645 string
_xk65 atomic.Bool
_uw [32]byte // Derived from activation — required by ValidateContext
_94b string
_lt8 string // GLOBAL_API_KEY from .env — used as token for licensing check
_32d string
_6l atomic.Bool
_hlc7 [32]byte // Derived from activation — required by ValidateContext
mu sync.RWMutex
_yf6 string // Registration URL shown to users before activation
_s09 string // Registration token for polling
_y6 string
_h7 string
_lmo string // Registration URL shown to users before activation
_k5 string // Registration token for polling
_pkj string
_an string
_jpz atomic.Int64 // Messages sent since last heartbeat
_9n3 atomic.Int64 // Messages received since last heartbeat
}
var _ipo atomic.Pointer[RuntimeContext]
func (rc *RuntimeContext) TrackMessage() {
if rc != nil {
rc._jpz.Add(1)
}
}
func TrackMessageSent() {
if rc := _ipo.Load(); rc != nil {
rc._jpz.Add(1)
}
}
func TrackMessageRecv() {
if rc := _ipo.Load(); rc != nil {
rc._9n3.Add(1)
}
}
func (rc *RuntimeContext) _wf() int64 {
return rc._jpz.Swap(0)
}
func (rc *RuntimeContext) ContextHash() [32]byte {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc._uw
return rc._hlc7
}
func (rc *RuntimeContext) IsActive() bool {
return rc._xk65.Load()
return rc._6l.Load()
}
func (rc *RuntimeContext) RegistrationURL() string {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc._yf6
return rc._lmo
}
func (rc *RuntimeContext) APIKey() string {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc._jpwr
return rc._94b
}
func (rc *RuntimeContext) InstanceID() string {
return rc._645
return rc._32d
}
func InitializeRuntime(_y6, _h7, _444 string) *RuntimeContext {
if _y6 == "" {
_y6 = "evolution-go"
func InitializeRuntime(_pkj, _an, _lt8 string) *RuntimeContext {
if _pkj == "" {
_pkj = "evolution-go"
}
if _h7 == "" {
_h7 = "unknown"
if _an == "" {
_an = "unknown"
}
rc := &RuntimeContext{
_y6: _y6,
_h7: _h7,
_444: _444,
_pkj: _pkj,
_an: _an,
_lt8: _lt8,
}
id, err := _viat()
id, err := _ix()
if err != nil {
log.Fatalf("[runtime] failed to initialize instance: %v", err)
}
rc._645 = id
rc._32d = id
rd, err := _8ftv()
rd, err := _vk()
if err == nil && rd.APIKey != "" {
rc._jpwr = rd.APIKey
rc._94b = rd.APIKey
fmt.Printf(" ✓ License found: %s...%s\n", rd.APIKey[:8], rd.APIKey[len(rd.APIKey)-4:])
rc._uw = sha256.Sum256([]byte(rc._jpwr + rc._645))
rc._xk65.Store(true)
rc._hlc7 = sha256.Sum256([]byte(rc._94b + rc._32d))
rc._6l.Store(true)
ActivateIntegrity(rc)
fmt.Println(" ✓ License activated successfully")
go func() {
if err := _2a2d(rc, _h7); err != nil {
if err := _vrz(rc, _an); err != nil {
fmt.Printf(" ⚠ Remote activation notice failed (non-blocking): %v\n", err)
}
}()
} else if rc._444 != "" {
rc._jpwr = rc._444
if err := _2a2d(rc, _h7); err == nil {
_nk7y(&RuntimeData{APIKey: rc._444, Tier: _y6})
rc._uw = sha256.Sum256([]byte(rc._jpwr + rc._645))
rc._xk65.Store(true)
} else if rc._lt8 != "" {
rc._94b = rc._lt8
if err := _vrz(rc, _an); err == nil {
_b7mk(&RuntimeData{APIKey: rc._lt8, Tier: _pkj})
rc._hlc7 = sha256.Sum256([]byte(rc._94b + rc._32d))
rc._6l.Store(true)
ActivateIntegrity(rc)
fmt.Printf(" ✓ GLOBAL_API_KEY accepted — license saved and activated\n")
} else {
rc._jpwr = ""
_p3()
rc._xk65.Store(false)
rc._94b = ""
_c56()
rc._6l.Store(false)
}
} else {
_p3()
rc._xk65.Store(false)
_c56()
rc._6l.Store(false)
}
_ipo.Store(rc)
return rc
}
func _p3() {
func _c56() {
fmt.Println()
fmt.Println(" ╔══════════════════════════════════════════════════════════╗")
fmt.Println(" ║ License Registration Required ║")
@@ -480,41 +508,41 @@ func _p3() {
fmt.Println()
}
func (rc *RuntimeContext) _fbk(authCodeOrKey, _y6 string, customerID int) error {
_jpwr, err := _kc1(authCodeOrKey)
func (rc *RuntimeContext) _upx4(authCodeOrKey, _pkj string, customerID int) error {
_94b, err := _gd97(authCodeOrKey)
if err != nil {
return fmt.Errorf("key exchange failed: %w", err)
}
rc.mu.Lock()
rc._jpwr = _jpwr
rc._yf6 = ""
rc._s09 = ""
rc._94b = _94b
rc._lmo = ""
rc._k5 = ""
rc.mu.Unlock()
if err := _nk7y(&RuntimeData{
APIKey: _jpwr,
Tier: _y6,
if err := _b7mk(&RuntimeData{
APIKey: _94b,
Tier: _pkj,
CustomerID: customerID,
}); err != nil {
fmt.Printf(" ⚠ Warning: could not save license: %v\n", err)
}
if err := _2a2d(rc, rc._h7); err != nil {
if err := _vrz(rc, rc._an); err != nil {
return err
}
rc.mu.Lock()
rc._uw = sha256.Sum256([]byte(rc._jpwr + rc._645))
rc._hlc7 = sha256.Sum256([]byte(rc._94b + rc._32d))
rc.mu.Unlock()
rc._xk65.Store(true)
rc._6l.Store(true)
ActivateIntegrity(rc)
fmt.Printf(" ✓ License activated! Key: %s...%s (_y6: %s)\n",
_jpwr[:8], _jpwr[len(_jpwr)-4:], _y6)
fmt.Printf(" ✓ License activated! Key: %s...%s (_pkj: %s)\n",
_94b[:8], _94b[len(_94b)-4:], _pkj)
go func() {
if err := _b1h(rc, 0); err != nil {
if err := _fjl1(rc, 0); err != nil {
fmt.Printf(" ⚠ First heartbeat failed: %v\n", err)
}
}()
@@ -526,10 +554,10 @@ func ValidateContext(rc *RuntimeContext) (bool, string) {
if rc == nil {
return false, ""
}
if !rc._xk65.Load() {
if !rc._6l.Load() {
return false, rc.RegistrationURL()
}
expected := sha256.Sum256([]byte(rc._jpwr + rc._645))
expected := sha256.Sum256([]byte(rc._94b + rc._32d))
actual := rc.ContextHash()
if expected != actual {
return false, ""
@@ -586,12 +614,12 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
resp := gin.H{
"status": status,
"instance_id": rc._645,
"instance_id": rc._32d,
}
rc.mu.RLock()
if rc._jpwr != "" {
resp["api_key"] = rc._jpwr[:8] + "..." + rc._jpwr[len(rc._jpwr)-4:]
if rc._94b != "" {
resp["api_key"] = rc._94b[:8] + "..." + rc._94b[len(rc._94b)-4:]
}
rc.mu.RUnlock()
@@ -608,7 +636,7 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
}
rc.mu.RLock()
existingURL := rc._yf6
existingURL := rc._lmo
rc.mu.RUnlock()
if existingURL != "" {
@@ -620,15 +648,15 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
}
payload := map[string]string{
"tier": rc._y6,
"version": rc._h7,
"instance_id": rc._645,
"tier": rc._pkj,
"version": rc._an,
"instance_id": rc._32d,
}
if redirectURI := c.Query("redirect_uri"); redirectURI != "" {
payload["redirect_uri"] = redirectURI
}
resp, err := _pzi6("/v1/register/init", payload)
resp, err := _7n05("/v1/register/init", payload)
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{
"error": "Failed to contact licensing server",
@@ -639,30 +667,30 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
_28 := _2l4(resp)
_p2d := _39pp(resp)
c.JSON(resp.StatusCode, gin.H{
"error": "Licensing server error",
"details": _28.Error(),
"details": _p2d.Error(),
})
return
}
var _fy4y struct {
var _hs struct {
RegisterURL string `json:"register_url"`
Token string `json:"token"`
}
json.NewDecoder(resp.Body).Decode(&_fy4y)
json.NewDecoder(resp.Body).Decode(&_hs)
rc.mu.Lock()
rc._yf6 = _fy4y.RegisterURL
rc._s09 = _fy4y.Token
rc._lmo = _hs.RegisterURL
rc._k5 = _hs.Token
rc.mu.Unlock()
fmt.Printf(" → Registration URL: %s\n", _fy4y.RegisterURL)
fmt.Printf(" → Registration URL: %s\n", _hs.RegisterURL)
c.JSON(http.StatusOK, gin.H{
"status": "pending",
"register_url": _fy4y.RegisterURL,
"register_url": _hs.RegisterURL,
})
})
@@ -684,9 +712,9 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
return
}
exchangeResp, err := _pzi6("/v1/register/exchange", map[string]string{
exchangeResp, err := _7n05("/v1/register/exchange", map[string]string{
"authorization_code": code,
"instance_id": rc._645,
"instance_id": rc._32d,
})
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{
@@ -698,22 +726,22 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
defer exchangeResp.Body.Close()
if exchangeResp.StatusCode != http.StatusOK {
_28 := _2l4(exchangeResp)
_p2d := _39pp(exchangeResp)
c.JSON(exchangeResp.StatusCode, gin.H{
"error": "Exchange failed",
"details": _28.Error(),
"details": _p2d.Error(),
})
return
}
var _x1 struct {
var _ve struct {
APIKey string `json:"api_key"`
Tier string `json:"tier"`
CustomerID int `json:"customer_id"`
}
json.NewDecoder(exchangeResp.Body).Decode(&_x1)
json.NewDecoder(exchangeResp.Body).Decode(&_ve)
if _x1.APIKey == "" {
if _ve.APIKey == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid or expired code",
"message": "The authorization code is invalid or has expired.",
@@ -721,7 +749,7 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
return
}
if err := rc._fbk(_x1.APIKey, _x1.Tier, _x1.CustomerID); err != nil {
if err := rc._upx4(_ve.APIKey, _ve.Tier, _ve.CustomerID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Activation failed",
"details": err.Error(),
@@ -751,7 +779,7 @@ func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time
continue
}
uptime := int64(time.Since(startTime).Seconds())
if err := _b1h(rc, uptime); err != nil {
if err := _fjl1(rc, uptime); err != nil {
fmt.Printf(" ⚠ Heartbeat failed (non-blocking): %v\n", err)
}
}
@@ -760,14 +788,14 @@ func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time
}
func Shutdown(rc *RuntimeContext) {
if rc == nil || rc._jpwr == "" {
if rc == nil || rc._94b == "" {
return
}
_uht(rc)
_gy(rc)
}
func _kms(code string) (_jpwr string, err error) {
resp, err := _pzi6("/v1/register/exchange", map[string]string{
func _z6rh(code string) (_94b string, err error) {
resp, err := _7n05("/v1/register/exchange", map[string]string{
"authorization_code": code,
})
if err != nil {
@@ -776,84 +804,104 @@ func _kms(code string) (_jpwr string, err error) {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", _2l4(resp)
return "", _39pp(resp)
}
var _x1 struct {
var _ve struct {
APIKey string `json:"api_key"`
}
json.NewDecoder(resp.Body).Decode(&_x1)
if _x1.APIKey == "" {
json.NewDecoder(resp.Body).Decode(&_ve)
if _ve.APIKey == "" {
return "", fmt.Errorf("exchange returned empty api_key")
}
return _x1.APIKey, nil
return _ve.APIKey, nil
}
func _kc1(authCodeOrKey string) (string, error) {
_jpwr, err := _kms(authCodeOrKey)
if err == nil && _jpwr != "" {
return _jpwr, nil
func _gd97(authCodeOrKey string) (string, error) {
_94b, err := _z6rh(authCodeOrKey)
if err == nil && _94b != "" {
return _94b, nil
}
return authCodeOrKey, nil
}
func _2a2d(rc *RuntimeContext, _h7 string) error {
resp, err := _rkb("/v1/activate", map[string]string{
"instance_id": rc._645,
"version": _h7,
}, rc._jpwr)
func _vrz(rc *RuntimeContext, _an string) error {
resp, err := _i9r("/v1/activate", map[string]string{
"instance_id": rc._32d,
"version": _an,
}, rc._94b)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return _2l4(resp)
return _39pp(resp)
}
var _x1 struct {
var _ve struct {
Status string `json:"status"`
}
json.NewDecoder(resp.Body).Decode(&_x1)
json.NewDecoder(resp.Body).Decode(&_ve)
if _x1.Status != "active" {
return fmt.Errorf("activation returned status: %s", _x1.Status)
if _ve.Status != "active" {
return fmt.Errorf("activation returned status: %s", _ve.Status)
}
return nil
}
func _b1h(rc *RuntimeContext, uptimeSeconds int64) error {
resp, err := _rkb("/v1/heartbeat", map[string]any{
"instance_id": rc._645,
func _fjl1(rc *RuntimeContext, uptimeSeconds int64) error {
_jpz := rc._wf()
_9n3 := rc._9n3.Swap(0)
payload := map[string]any{
"instance_id": rc._32d,
"uptime_seconds": uptimeSeconds,
"version": rc._h7,
}, rc._jpwr)
"version": rc._an,
}
if _jpz > 0 || _9n3 > 0 {
bundle := map[string]any{}
if _jpz > 0 {
bundle["messages_sent"] = _jpz
}
if _9n3 > 0 {
bundle["messages_recv"] = _9n3
}
payload["telemetry_bundle"] = bundle
}
resp, err := _i9r("/v1/heartbeat", payload, rc._94b)
if err != nil {
rc._jpz.Add(_jpz)
rc._9n3.Add(_9n3)
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return _2l4(resp)
rc._jpz.Add(_jpz)
rc._9n3.Add(_9n3)
return _39pp(resp)
}
return nil
}
func _uht(rc *RuntimeContext) {
func _gy(rc *RuntimeContext) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
body, _ := json.Marshal(map[string]string{
"instance_id": rc._645,
"instance_id": rc._32d,
})
url := _rmo() + "/v1/deactivate"
url := _c0u() + "/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._jpwr)
req.Header.Set("X-Signature", _t5d(body, rc._jpwr))
_ls61.Do(req)
req.Header.Set("X-Api-Key", rc._94b)
req.Header.Set("X-Signature", _48bz(body, rc._94b))
_e97.Do(req)
}
+5 -3
View File
@@ -9,6 +9,7 @@ import (
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"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
)
type InstanceHandler interface {
@@ -449,9 +450,10 @@ func (i *instanceHandler) SetProxy(ctx *gin.Context) {
}
responseData := gin.H{
"host": data.Host,
"port": data.Port,
"hasAuth": data.Username != "" && data.Password != "",
"protocol": utils.NormalizeProxyProtocol(data.Protocol, data.Port),
"host": data.Host,
"port": data.Port,
"hasAuth": data.Username != "" && data.Password != "",
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
+11 -1
View File
@@ -18,6 +18,7 @@ import (
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"
"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"
@@ -55,6 +56,7 @@ type instances struct {
}
type ProxyConfig struct {
Protocol string `json:"protocol,omitempty"`
Port string `json:"port"`
Password string `json:"password"`
Username string `json:"username"`
@@ -101,6 +103,7 @@ type PairReturnStruct struct {
}
type SetProxyStruct struct {
Protocol string `json:"protocol,omitempty"`
Host string `json:"host" validate:"required"`
Port string `json:"port" validate:"required"`
Username string `json:"username"`
@@ -152,6 +155,10 @@ func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client,
}
func (i instances) Create(data *CreateStruct) (*instance_model.Instance, error) {
if data.Proxy != nil {
data.Proxy.Protocol = utils.NormalizeProxyProtocol(data.Proxy.Protocol, data.Proxy.Port)
}
proxyJson, err := json.Marshal(data.Proxy)
if err != nil {
return nil, err
@@ -562,6 +569,8 @@ func (i instances) SetProxy(id string, proxyConfig *ProxyConfig) error {
return fmt.Errorf("proxy port is required")
}
proxyConfig.Protocol = utils.NormalizeProxyProtocol(proxyConfig.Protocol, proxyConfig.Port)
// Convert proxy config to JSON
proxyJSON, err := json.Marshal(proxyConfig)
if err != nil {
@@ -578,7 +587,7 @@ func (i instances) SetProxy(id string, proxyConfig *ProxyConfig) error {
return err
}
i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration updated: %s:%s", id, proxyConfig.Host, proxyConfig.Port)
i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration updated: %s://%s:%s", id, proxyConfig.Protocol, proxyConfig.Host, proxyConfig.Port)
// Reconnect to apply proxy changes
go i.Reconnect(instance)
@@ -592,6 +601,7 @@ func (i instances) SetProxyFromStruct(id string, data *SetProxyStruct) error {
}
proxyConfig := &ProxyConfig{
Protocol: data.Protocol,
Host: data.Host,
Port: data.Port,
Username: data.Username,
+3
View File
@@ -15,6 +15,7 @@ const (
GROUP = "GROUP"
NEWSLETTER = "NEWSLETTER"
QRCODE = "QRCODE"
BUTTON_CLICK = "BUTTON_CLICK"
)
var AllEventTypes = []string{
@@ -31,6 +32,7 @@ var AllEventTypes = []string{
GROUP,
NEWSLETTER,
QRCODE,
BUTTON_CLICK,
}
var validEventTypes = map[string]bool{
@@ -48,6 +50,7 @@ var validEventTypes = map[string]bool{
GROUP: true,
NEWSLETTER: true,
QRCODE: true,
BUTTON_CLICK: true,
}
func IsEventType(eventType string) bool {
+4 -6
View File
@@ -398,8 +398,6 @@ func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance
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)
@@ -413,16 +411,16 @@ func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance
recipient,
data.MessageID,
&waE2E.Message{
Conversation: proto.String(data.Message),
ExtendedTextMessage: &waE2E.ExtendedTextMessage{
Text: &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
return resp.ID, resp.Timestamp.String(), nil
}
func NewMessageService(
+3 -1
View File
@@ -121,7 +121,9 @@ func (r *Routes) AssignRoutes(eng *gin.Engine) {
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.POST("/carousel", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendCarousel)
routes.POST("/status/text", r.sendHandler.SendStatusText)
routes.POST("/status/media", r.sendHandler.SendStatusMedia)
}
}
routes = eng.Group("/user")
+239 -11
View File
@@ -1,6 +1,7 @@
package send_handler
import (
"encoding/base64"
"io"
"net/http"
"strconv"
@@ -21,6 +22,9 @@ type SendHandler interface {
SendContact(ctx *gin.Context)
SendButton(ctx *gin.Context)
SendList(ctx *gin.Context)
SendCarousel(ctx *gin.Context)
SendStatusText(ctx *gin.Context)
SendStatusMedia(ctx *gin.Context)
}
type sendHandler struct {
@@ -171,6 +175,23 @@ func (s *sendHandler) SendMedia(ctx *gin.Context) {
delay = int32(delay64)
}
mentionAll := ctx.PostForm("mentionAll") == "true"
var mentionedJID []string
// Accept multiple values (mentionedJid=x&mentionedJid=y) or a single
// comma-separated string (mentionedJid=x,y).
for _, raw := range ctx.PostFormArray("mentionedJid") {
for _, v := range strings.Split(raw, ",") {
if trimmed := strings.TrimSpace(v); trimmed != "" {
mentionedJID = append(mentionedJID, trimmed)
}
}
}
var quoted send_service.QuotedStruct
quoted.MessageID = ctx.PostForm("quoted.messageId")
quoted.Participant = ctx.PostForm("quoted.participant")
// Get file
file, err := ctx.FormFile("file")
if err != nil {
@@ -193,13 +214,15 @@ func (s *sendHandler) SendMedia(ctx *gin.Context) {
// Create MediaStruct
data = &send_service.MediaStruct{
Number: number,
Type: mediaType,
Caption: caption,
Filename: filename,
Id: id,
Delay: delay,
// Other fields as necessary
Number: number,
Type: mediaType,
Caption: caption,
Filename: filename,
Id: id,
Delay: delay,
MentionAll: mentionAll,
MentionedJID: mentionedJID,
Quoted: quoted,
}
// Pass fileBytes to the send service
@@ -234,10 +257,26 @@ func (s *sendHandler) SendMedia(ctx *gin.Context) {
return
}
message, err := s.sendMessageService.SendMediaUrl(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
var message *send_service.MessageSendStruct
if !strings.HasPrefix(data.Url, "http://") && !strings.HasPrefix(data.Url, "https://") {
// Treat as base64-encoded media
fileBytes, err := base64.StdEncoding.DecodeString(data.Url)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid base64 encoding"})
return
}
message, err = s.sendMessageService.SendMediaFile(data, fileBytes, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
} else {
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})
@@ -570,6 +609,195 @@ func (s *sendHandler) SendList(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
}
// Send a carousel message
// @Summary Send a carousel message
// @Description Send a carousel message
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.CarouselStruct 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/carousel [post]
func (s *sendHandler) SendCarousel(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.CarouselStruct
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.Cards) == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "at least one card is required"})
return
}
message, err := s.sendMessageService.SendCarousel(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 text status message
// @Summary Send a WhatsApp text status
// @Description Send a WhatsApp text status to status@broadcast
// @Tags Send Message
// @Accept json
// @Produce json
// @Param message body send_service.StatusTextStruct true "Status text 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/status/text [post]
func (s *sendHandler) SendStatusText(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
}
data := new(send_service.StatusTextStruct)
err := ctx.ShouldBindBodyWithJSON(data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Text == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "text is required"})
return
}
message, err := s.sendMessageService.SendStatusText(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 status message (image or video)
// @Summary Send a WhatsApp media status (image/video)
// @Description Send an image or video status to status@broadcast. Supports JSON (URL) or multipart/form-data (file upload)
// @Tags Send Message
// @Accept json, multipart/form-data
// @Produce json
// @Param type formData string true "Media type: image or video"
// @Param file formData file false "Media file (for multipart upload)"
// @Param url formData string false "Media URL (for JSON upload)"
// @Param caption formData string false "Caption for the media"
// @Param id formData string false "Custom message ID"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /send/status/media [post]
func (s *sendHandler) SendStatusMedia(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()
data := new(send_service.StatusMediaStruct)
if strings.HasPrefix(contentType, "multipart/form-data") {
mediaType := ctx.PostForm("type")
if mediaType == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "media type is required"})
return
}
if mediaType != "image" && mediaType != "video" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "type must be 'image' or 'video'"})
return
}
caption := ctx.PostForm("caption")
id := ctx.PostForm("id")
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
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
}
data = &send_service.StatusMediaStruct{
Type: mediaType,
Caption: caption,
Id: id,
}
message, err := s.sendMessageService.SendStatusMediaFile(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})
return
}
err := ctx.ShouldBindBodyWithJSON(data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Url == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url is required"})
return
}
if data.Type != "image" && data.Type != "video" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "type must be 'image' or 'video'"})
return
}
message, err := s.sendMessageService.SendStatusMediaUrl(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 {
+437 -137
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"mime/multipart"
@@ -43,6 +44,10 @@ type SendService interface {
SendContact(data *ContactStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendButton(data *ButtonStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendList(data *ListStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendCarousel(data *CarouselStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendStatusText(data *StatusTextStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendStatusMediaUrl(data *StatusMediaStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendStatusMediaFile(data *StatusMediaStruct, fileData []byte, instance *instance_model.Instance) (*MessageSendStruct, error)
}
type sendService struct {
@@ -243,6 +248,18 @@ type CarouselStruct struct {
Cards []CarouselCardStruct `json:"cards"`
}
type StatusTextStruct struct {
Text string `json:"text"`
Id string `json:"id"`
}
type StatusMediaStruct struct {
Type string `json:"type"`
Url string `json:"url"`
Caption string `json:"caption"`
Id string `json:"id"`
}
type MessageSendStruct struct {
Info types.MessageInfo
Message *waE2E.Message
@@ -1666,24 +1683,38 @@ func (s *sendService) SendButton(data *ButtonStruct, instance *instance_model.In
return t
}()
msg = &waE2E.Message{ViewOnceMessage: &waE2E.FutureProofMessage{
Message: &waE2E.Message{
InteractiveMessage: &waE2E.InteractiveMessage{
Body: &waE2E.InteractiveMessage_Body{
Text: &body,
},
Footer: &waE2E.InteractiveMessage_Footer{
Text: &data.Footer,
},
InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{
NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
Buttons: buttons,
MessageParamsJSON: &messageParamsJSON,
},
},
interactiveMsg := &waE2E.InteractiveMessage{
Body: &waE2E.InteractiveMessage_Body{
Text: &body,
},
InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{
NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
Buttons: buttons,
MessageParamsJSON: &messageParamsJSON,
MessageVersion: proto.Int32(1),
},
},
}}
ContextInfo: &waE2E.ContextInfo{},
}
// Footer conditional - only add if not empty (iOS compatibility)
if data.Footer != "" {
interactiveMsg.Footer = &waE2E.InteractiveMessage_Footer{
Text: &data.Footer,
}
}
// Header with title
if data.Title != "" {
interactiveMsg.Header = &waE2E.InteractiveMessage_Header{
Title: proto.String(data.Title),
HasMediaAttachment: proto.Bool(false),
}
}
msg = &waE2E.Message{
InteractiveMessage: interactiveMsg,
}
}
recipient, err := s.validateAndCheckUserExists(data.Number, data.FormatJid, &data.Quoted.MessageID, &data.Quoted.MessageID, instance)
@@ -1743,15 +1774,16 @@ func stringPointer(s string) *string {
func sectionsToString(data *ListStruct) (string, error) {
type row struct {
Header *string `json:"header,omitempty"`
Title string `json:"title"`
Description *string `json:"description,omitempty"`
ID string `json:"id"`
Header string `json:"header"`
Title string `json:"title"`
Description string `json:"description"`
ID string `json:"id"`
}
type listSection struct {
Title string `json:"title"`
Rows []row `json:"rows"`
Title string `json:"title"`
HighlightLabel string `json:"highlight_label"`
Rows []row `json:"rows"`
}
type list struct {
@@ -1762,26 +1794,49 @@ func sectionsToString(data *ListStruct) (string, error) {
sections := []listSection{}
for _, s := range data.Sections {
sectionTitle := s.Title
if sectionTitle == "" {
sectionTitle = " "
}
rows := []row{}
for _, r := range s.Rows {
rowTitle := r.Title
if rowTitle == "" {
rowTitle = " "
}
rowDesc := r.Description
if rowDesc == "" {
rowDesc = " "
}
rowId := r.RowId
if rowId == "" {
rowId = fmt.Sprintf("row_%d", len(rows))
}
rows = append(rows, row{
Title: r.Title,
Description: stringPointer(r.Description),
ID: r.RowId,
Header: rowTitle,
Title: rowTitle,
Description: rowDesc,
ID: rowId,
})
}
section := listSection{
Title: s.Title,
Rows: rows,
Title: sectionTitle,
HighlightLabel: "",
Rows: rows,
}
sections = append(sections, section)
}
buttonText := data.ButtonText
if buttonText == "" {
buttonText = "Ver Menu"
}
listData := list{
Title: data.ButtonText,
Title: buttonText,
Sections: sections,
}
@@ -1794,105 +1849,70 @@ func sectionsToString(data *ListStruct) (string, error) {
}
func (s *sendService) SendList(data *ListStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {
client, err := s.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
// Legacy ListMessage format - works on iOS, Android and Web
// Matching PAPI Node.js default (non-modern) path exactly
buttonText := data.ButtonText
if buttonText == "" {
buttonText = "Ver Menu"
}
messageId := client.GenerateMessageID()
templateId := strconv.FormatInt(time.Now().UnixNano()/1000000, 10)
messageParamsJSON := `{"from":"api","templateId":` + templateId + `}`
buttons := []*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{}
sectionString, err := sectionsToString(data)
if err != nil {
return nil, err
// Build sections in legacy ListMessage format
var sections []*waE2E.ListMessage_Section
for _, sec := range data.Sections {
sectionTitle := sec.Title
if sectionTitle == "" {
sectionTitle = " "
}
var rows []*waE2E.ListMessage_Row
for i, r := range sec.Rows {
rowTitle := r.Title
if rowTitle == "" {
rowTitle = " "
}
rowId := r.RowId
if rowId == "" {
rowId = fmt.Sprintf("row_%d_%d", i, len(rows))
}
rows = append(rows, &waE2E.ListMessage_Row{
Title: proto.String(rowTitle),
Description: proto.String(r.Description),
RowID: proto.String(rowId),
})
}
sections = append(sections, &waE2E.ListMessage_Section{
Title: proto.String(sectionTitle),
Rows: rows,
})
}
buttons = append(buttons, &waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{
Name: proto.String("single_select"),
ButtonParamsJSON: proto.String(sectionString),
listType := waE2E.ListMessage_SINGLE_SELECT
listMessage := &waE2E.ListMessage{
Title: proto.String(data.Title),
Description: proto.String(data.Description),
ButtonText: proto.String(buttonText),
FooterText: proto.String(data.FooterText),
ListType: &listType,
Sections: sections,
}
// Send as plain ListMessage (NO ViewOnceMessage wrapper) - matching PAPI Node.js
msg := &waE2E.Message{
ListMessage: listMessage,
}
message, err := s.SendMessage(instance, msg, "ListMessage", &SendDataStruct{
Number: data.Number,
Delay: data.Delay,
})
body := func() string {
t := "*" + data.Title + "*"
if data.Description != "" {
t += "\n\n" + data.Description + "\n"
}
return t
}()
msg := &waE2E.Message{ViewOnceMessage: &waE2E.FutureProofMessage{
Message: &waE2E.Message{
InteractiveMessage: &waE2E.InteractiveMessage{
Body: &waE2E.InteractiveMessage_Body{
Text: &body,
},
Footer: &waE2E.InteractiveMessage_Footer{
Text: &data.FooterText,
},
InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{
NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
Buttons: buttons,
MessageParamsJSON: &messageParamsJSON,
},
},
},
},
}}
recipient, err := s.validateAndCheckUserExists(data.Number, data.FormatJid, &data.Quoted.MessageID, &data.Quoted.MessageID, instance)
if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields or user check: %v", instance.Id, err)
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending list: %v", instance.Id, err)
return nil, err
}
if data.Delay > 0 {
err := client.SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(""))
if err != nil {
return nil, err
}
time.Sleep(time.Duration(data.Delay) * time.Millisecond)
err = s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(""))
if err != nil {
return nil, err
}
}
response, err := s.clientPointer[instance.Id].SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{ID: messageId})
if err != nil {
return nil, err
}
messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{
Chat: recipient,
Sender: *s.clientPointer[instance.Id].Store.ID,
IsFromMe: true,
IsGroup: false,
},
ID: messageId,
Timestamp: time.Now(),
ServerID: response.ServerID,
Type: "ListMessage",
}
messageSent := &MessageSendStruct{
Info: messageInfo,
Message: msg,
MessageContextInfo: &waE2E.ContextInfo{
StanzaID: proto.String(data.Quoted.MessageID),
Participant: proto.String(data.Quoted.Participant),
QuotedMessage: &waE2E.Message{Conversation: proto.String("")},
},
}
return messageSent, nil
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] List sent to %s", instance.Id, data.Number)
return message, nil
}
func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.Message, messageType string, data *SendDataStruct) (*MessageSendStruct, error) {
@@ -2010,6 +2030,22 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
Participant: proto.String(data.Quoted.Participant),
QuotedMessage: &waE2E.Message{Conversation: proto.String("")},
}
case "InteractiveMessage":
if msg.InteractiveMessage != nil {
msg.InteractiveMessage.ContextInfo = &waE2E.ContextInfo{
StanzaID: proto.String(data.Quoted.MessageID),
Participant: proto.String(data.Quoted.Participant),
QuotedMessage: &waE2E.Message{Conversation: proto.String("")},
}
}
case "ListMessage":
if msg.ListMessage != nil {
msg.ListMessage.ContextInfo = &waE2E.ContextInfo{
StanzaID: proto.String(data.Quoted.MessageID),
Participant: proto.String(data.Quoted.Participant),
QuotedMessage: &waE2E.Message{Conversation: proto.String("")},
}
}
default:
return nil, fmt.Errorf("invalid messageType: %s", messageType)
}
@@ -2044,6 +2080,10 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
msg.LocationMessage.ContextInfo = &waE2E.ContextInfo{}
case "ContactMessage":
msg.ContactMessage.ContextInfo = &waE2E.ContextInfo{}
case "InteractiveMessage":
// ContextInfo already set in SendCarousel/SendButton/SendList
case "ListMessage":
// ContextInfo already set in SendList
default:
return nil, fmt.Errorf("invalid messageType: %s", messageType)
}
@@ -2362,9 +2402,8 @@ func (s *sendService) SendCarousel(data *CarouselStruct, instance *instance_mode
if card.Header.ImageUrl != "" || card.Header.VideoUrl != "" {
header := interactiveCard.Header
// Add media to header if URL provided
if card.Header.ImageUrl != "" {
// Download and upload image
// Download image
resp, err := http.Get(card.Header.ImageUrl)
if err == nil {
defer resp.Body.Close()
@@ -2372,16 +2411,42 @@ func (s *sendService) SendCarousel(data *CarouselStruct, instance *instance_mode
if err == nil {
uploaded, err := client.Upload(context.Background(), fileData, whatsmeow.MediaImage)
if err == nil {
// Generate JPEG thumbnail for iOS compatibility
var jpegThumb []byte
img, _, decErr := image.Decode(bytes.NewReader(fileData))
if decErr == nil {
// Resize to 72px thumbnail
bounds := img.Bounds()
thumbWidth := 72
thumbHeight := int(float64(bounds.Dy()) * float64(thumbWidth) / float64(bounds.Dx()))
if thumbHeight < 1 {
thumbHeight = 1
}
thumbImg := image.NewRGBA(image.Rect(0, 0, thumbWidth, thumbHeight))
for y := 0; y < thumbHeight; y++ {
for x := 0; x < thumbWidth; x++ {
srcX := x * bounds.Dx() / thumbWidth
srcY := y * bounds.Dy() / thumbHeight
thumbImg.Set(x, y, img.At(srcX+bounds.Min.X, srcY+bounds.Min.Y))
}
}
var thumbBuf bytes.Buffer
if jpeg.Encode(&thumbBuf, thumbImg, &jpeg.Options{Quality: 50}) == nil {
jpegThumb = thumbBuf.Bytes()
}
}
header.HasMediaAttachment = proto.Bool(true)
header.Media = &waE2E.InteractiveMessage_Header_ImageMessage{
ImageMessage: &waE2E.ImageMessage{
URL: proto.String(uploaded.URL),
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String("image/jpeg"),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(fileData))),
URL: proto.String(uploaded.URL),
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String("image/jpeg"),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(fileData))),
JPEGThumbnail: jpegThumb,
},
}
}
@@ -2460,14 +2525,11 @@ func (s *sendService) SendCarousel(data *CarouselStruct, instance *instance_mode
}
}
// messageParamsJSON is REQUIRED for NativeFlowMessage with buttons
messageParamsJSON := fmt.Sprintf(`{"from":"api","templateId":"%d"}`, time.Now().UnixNano()/1000000)
// Cards in carousel: do NOT set MessageParamsJSON or MessageVersion
// (matching PAPI Node.js behavior for iOS compatibility)
interactiveCard.InteractiveMessage = &waE2E.InteractiveMessage_NativeFlowMessage_{
NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
Buttons: buttons,
MessageParamsJSON: proto.String(messageParamsJSON),
MessageVersion: proto.Int32(1),
Buttons: buttons,
},
}
}
@@ -2475,14 +2537,12 @@ func (s *sendService) SendCarousel(data *CarouselStruct, instance *instance_mode
cards[i] = interactiveCard
}
// Build carousel message
carouselCardType := waE2E.InteractiveMessage_CarouselMessage_HSCROLL_CARDS
// Build carousel message (do NOT set CarouselCardType - matching PAPI Node.js for iOS)
interactiveMsg := &waE2E.InteractiveMessage{
InteractiveMessage: &waE2E.InteractiveMessage_CarouselMessage_{
CarouselMessage: &waE2E.InteractiveMessage_CarouselMessage{
Cards: cards,
MessageVersion: &messageVersion,
CarouselCardType: &carouselCardType,
Cards: cards,
MessageVersion: &messageVersion,
},
},
}
@@ -2541,6 +2601,246 @@ func (s *sendService) SendCarousel(data *CarouselStruct, instance *instance_mode
return message, nil
}
func (s *sendService) SendStatusText(data *StatusTextStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {
client, err := s.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
if data.Text == "" {
return nil, errors.New("text is required")
}
msg := &waE2E.Message{
ExtendedTextMessage: &waE2E.ExtendedTextMessage{
Text: &data.Text,
},
}
messageID := data.Id
if messageID == "" {
messageID = client.GenerateMessageID()
}
recipient := types.NewJID("status", "broadcast")
response, err := client.SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{ID: messageID})
if err != nil {
return nil, err
}
messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{
Chat: recipient,
Sender: *client.Store.ID,
IsFromMe: true,
IsGroup: false,
},
ID: messageID,
Timestamp: time.Now(),
ServerID: response.ServerID,
Type: "StatusTextMessage",
}
messageSent := &MessageSendStruct{
Info: messageInfo,
Message: msg,
MessageContextInfo: &waE2E.ContextInfo{
StanzaID: proto.String(""),
Participant: proto.String(""),
QuotedMessage: &waE2E.Message{Conversation: proto.String("")},
},
}
s.sendStatusWebhook(messageSent, instance, "text")
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Status text sent successfully", instance.Id)
return messageSent, nil
}
func (s *sendService) SendStatusMediaUrl(data *StatusMediaStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {
client, err := s.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
if data.Url == "" {
return nil, errors.New("url is required")
}
if data.Type != "image" && data.Type != "video" {
return nil, errors.New("type must be 'image' or 'video'")
}
req, err := http.NewRequest("GET", data.Url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Evolution-GO/1.0")
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to download file from URL: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("failed to download file: HTTP status %d", resp.StatusCode)
}
fileData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return s.sendStatusMedia(client, data, fileData, instance)
}
func (s *sendService) SendStatusMediaFile(data *StatusMediaStruct, fileData []byte, instance *instance_model.Instance) (*MessageSendStruct, error) {
client, err := s.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
if data.Type != "image" && data.Type != "video" {
return nil, errors.New("type must be 'image' or 'video'")
}
return s.sendStatusMedia(client, data, fileData, instance)
}
func (s *sendService) sendStatusMedia(client *whatsmeow.Client, data *StatusMediaStruct, fileData []byte, instance *instance_model.Instance) (*MessageSendStruct, error) {
mime, _ := mimetype.DetectReader(bytes.NewReader(fileData))
mimeType := mime.String()
var uploadType whatsmeow.MediaType
switch data.Type {
case "image":
if mimeType != "image/jpeg" && mimeType != "image/png" && mimeType != "image/webp" {
return nil, fmt.Errorf("invalid file format: '%s'. Only 'image/jpeg', 'image/png' and 'image/webp' are accepted", mimeType)
}
if mimeType == "image/webp" {
mimeType = "image/jpeg"
}
uploadType = whatsmeow.MediaImage
case "video":
if mimeType != "video/mp4" {
return nil, fmt.Errorf("invalid file format: '%s'. Only 'video/mp4' is accepted", mimeType)
}
uploadType = whatsmeow.MediaVideo
default:
return nil, errors.New("invalid media type")
}
uploaded, err := client.Upload(context.Background(), fileData, uploadType)
if err != nil {
return nil, err
}
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Status media uploaded, size: %d", instance.Id, uploaded.FileLength)
var media *waE2E.Message
var mediaType string
switch data.Type {
case "image":
media = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{
Caption: proto.String(data.Caption),
URL: proto.String(uploaded.URL),
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String(mimeType),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(fileData))),
}}
mediaType = "ImageMessage"
case "video":
media = &waE2E.Message{VideoMessage: &waE2E.VideoMessage{
Caption: proto.String(data.Caption),
URL: proto.String(uploaded.URL),
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String(mimeType),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(fileData))),
}}
mediaType = "VideoMessage"
}
messageID := data.Id
if messageID == "" {
messageID = client.GenerateMessageID()
}
recipient := types.NewJID("status", "broadcast")
response, err := client.SendMessage(context.Background(), recipient, media, whatsmeow.SendRequestExtra{ID: messageID})
if err != nil {
return nil, err
}
messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{
Chat: recipient,
Sender: *client.Store.ID,
IsFromMe: true,
IsGroup: false,
},
ID: messageID,
Timestamp: time.Now(),
ServerID: response.ServerID,
Type: mediaType,
}
messageSent := &MessageSendStruct{
Info: messageInfo,
Message: media,
MessageContextInfo: &waE2E.ContextInfo{
StanzaID: proto.String(""),
Participant: proto.String(""),
QuotedMessage: &waE2E.Message{Conversation: proto.String("")},
},
}
s.sendStatusWebhook(messageSent, instance, "media")
return messageSent, nil
}
func (s *sendService) sendStatusWebhook(messageSent *MessageSendStruct, instance *instance_model.Instance, messageType string) {
postMap := make(map[string]interface{})
postMap["event"] = "SendStatus"
messageData := make(map[string]interface{})
messageData["Info"] = messageSent.Info
msgBytes, err := json.Marshal(messageSent.Message)
if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to marshal status message: %v", instance.Id, err)
return
}
var msgMap map[string]interface{}
if err := json.Unmarshal(msgBytes, &msgMap); err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to unmarshal status message: %v", instance.Id, err)
return
}
messageData["Message"] = msgMap
messageData["MessageContextInfo"] = messageSent.MessageContextInfo
postMap["data"] = messageData
postMap["instanceToken"] = instance.Token
postMap["instanceId"] = instance.Id
postMap["instanceName"] = instance.Name
values, err := json.Marshal(postMap)
if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to marshal webhook payload: %v", instance.Id, err)
return
}
go s.whatsmeowService.CallWebhook(instance, "sendstatus", values)
if s.config.AmqpGlobalEnabled || s.config.NatsGlobalEnabled {
go s.whatsmeowService.SendToGlobalQueues("SendStatus", values, instance.Id)
}
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Status %s sent successfully", instance.Id, messageType)
}
func NewSendService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
+63
View File
@@ -3,6 +3,7 @@ package utils
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"runtime"
@@ -253,6 +254,66 @@ func CreateSocks5Proxy(socks5Host, socks5Port, user, password string) (proxy.Dia
// }, nil
}
// NormalizeProxyProtocol returns the proxy protocol normalized to one of
// http/https/socks5. If not supplied, it is inferred from the port — ports
// 1080, 2080, and 42000-43000 map to socks5; everything else defaults to http.
func NormalizeProxyProtocol(protocol, port string) string {
normalized := strings.ToLower(strings.TrimSpace(protocol))
switch normalized {
case "socks":
return "socks5"
case "http", "https", "socks5":
return normalized
}
switch strings.TrimSpace(port) {
case "1080", "2080":
return "socks5"
}
portNum, err := strconv.Atoi(strings.TrimSpace(port))
if err == nil && portNum >= 42000 && portNum <= 43000 {
return "socks5"
}
return "http"
}
// BuildProxyAddress builds a proxy URL string suitable for whatsmeow's
// client.SetProxyAddress — it supports http, https, and socks5 with optional
// basic auth credentials.
func BuildProxyAddress(protocol, host, port, user, password string) (string, error) {
if strings.TrimSpace(host) == "" {
return "", fmt.Errorf("proxy host is required")
}
if strings.TrimSpace(port) == "" {
return "", fmt.Errorf("proxy port is required")
}
normalizedProtocol := NormalizeProxyProtocol(protocol, port)
if normalizedProtocol != "http" && normalizedProtocol != "https" && normalizedProtocol != "socks5" {
return "", fmt.Errorf("unsupported proxy protocol %q", protocol)
}
proxyURL := &url.URL{
Scheme: normalizedProtocol,
Host: net.JoinHostPort(strings.TrimSpace(host), strings.TrimSpace(port)),
}
if user != "" {
if password != "" {
proxyURL.User = url.UserPassword(user, password)
} else {
proxyURL.User = url.User(user)
}
}
return proxyURL.String(), nil
}
func UpdateUserInfo(values interface{}, field string, value string) interface{} {
v, ok := values.(Values)
if !ok {
@@ -447,6 +508,8 @@ func GetMessageType(waMsg *waE2E.Message) string {
return "template button reply"
case waMsg.InteractiveMessage != nil:
return "interactive"
case waMsg.GetInteractiveResponseMessage() != nil:
return "interactive response"
case waMsg.ListMessage != nil:
return "list"
case waMsg.ProductMessage != nil:
+215 -33
View File
@@ -15,6 +15,7 @@ import (
"regexp"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/image/webp"
@@ -141,6 +142,7 @@ type UserCollection struct {
}
type ProxyConfig struct {
Protocol string `json:"protocol,omitempty"`
Host string `json:"host"`
Password string `json:"password"`
Port string `json:"port"`
@@ -398,6 +400,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
return
}
proxyProtocol := proxyConfig.Protocol
proxyHost := proxyConfig.Host
proxyPort := proxyConfig.Port
proxyUsername := proxyConfig.Username
@@ -411,6 +414,10 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
proxyPort = w.config.ProxyPort
}
if proxyConfig.Protocol == "" {
proxyProtocol = w.config.ProxyProtocol
}
if proxyConfig.Username == "" {
proxyUsername = w.config.ProxyUsername
}
@@ -419,12 +426,16 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
proxyPassword = w.config.ProxyPassword
}
proxy, err := utils.CreateSocks5Proxy(proxyHost, proxyPort, proxyUsername, proxyPassword)
proxyAddress, err := utils.BuildProxyAddress(proxyProtocol, proxyHost, proxyPort, proxyUsername, proxyPassword)
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Proxy error, continuing without proxy: %v", cd.Instance.Id, err)
} else {
client.SetSOCKSProxy(proxy)
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Proxy enabled", cd.Instance.Id)
err = client.SetProxyAddress(proxyAddress)
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Proxy error, continuing without proxy: %v", cd.Instance.Id, err)
} else {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Proxy enabled (%s)", cd.Instance.Id, utils.NormalizeProxyProtocol(proxyProtocol, proxyPort))
}
}
}
@@ -1337,20 +1348,21 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
if err == nil {
webpReader := bytes.NewReader(data)
img, err := webp.Decode(webpReader)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decode webp image: %v", mycli.userID, err)
return
img, decErr := webp.Decode(webpReader)
if decErr != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to decode webp sticker, keeping raw webp: %v", mycli.userID, decErr)
extension = ".webp"
mimeType = "image/webp"
} else {
var pngBuffer bytes.Buffer
if encErr := png.Encode(&pngBuffer, img); encErr != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to encode png from sticker, keeping raw webp: %v", mycli.userID, encErr)
extension = ".webp"
mimeType = "image/webp"
} else {
data = pngBuffer.Bytes()
}
}
var pngBuffer bytes.Buffer
err = png.Encode(&pngBuffer, img)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to encode png image: %v", mycli.userID, err)
return
}
data = pngBuffer.Bytes()
}
// Handle associated child media messages
} else if associatedImg != nil {
@@ -1379,21 +1391,24 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
mimeType = "image/png"
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing associated child sticker message", mycli.userID)
webpReader := bytes.NewReader(data)
img, err := webp.Decode(webpReader)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decode webp image: %v", mycli.userID, err)
return
if err == nil {
webpReader := bytes.NewReader(data)
img, decErr := webp.Decode(webpReader)
if decErr != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to decode webp sticker, keeping raw webp: %v", mycli.userID, decErr)
extension = ".webp"
mimeType = "image/webp"
} else {
var pngBuffer bytes.Buffer
if encErr := png.Encode(&pngBuffer, img); encErr != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to encode png from associated sticker, keeping raw webp: %v", mycli.userID, encErr)
extension = ".webp"
mimeType = "image/webp"
} else {
data = pngBuffer.Bytes()
}
}
}
var pngBuffer bytes.Buffer
err = png.Encode(&pngBuffer, img)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to encode png image: %v", mycli.userID, err)
return
}
data = pngBuffer.Bytes()
}
downloadDuration := time.Since(downloadStart)
@@ -1499,6 +1514,97 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
postMap["data"] = dataMap
// ===== BUTTON CLICK EVENT DETECTION =====
// Detecta cliques em botões e emite evento separado "ButtonClick"
// Suporta 3 formatos: ButtonsResponseMessage, InteractiveResponseMessage (NativeFlow), TemplateButtonReplyMessage
var buttonClickData map[string]interface{}
if resp := evt.Message.GetButtonsResponseMessage(); resp != nil {
// Legacy buttons response
buttonClickData = map[string]interface{}{
"buttonId": resp.GetSelectedButtonID(),
"buttonText": resp.GetSelectedDisplayText(),
"type": "buttons_response",
}
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Button click detected (legacy): buttonId=%s, buttonText=%s", mycli.userID, resp.GetSelectedButtonID(), resp.GetSelectedDisplayText())
} else if resp := evt.Message.GetInteractiveResponseMessage(); resp != nil {
// NativeFlow interactive response (quick_reply, cta_url, cta_call, cta_copy)
if nf := resp.GetNativeFlowResponseMessage(); nf != nil {
buttonId := ""
buttonText := ""
// Parse paramsJSON to extract id and display_text
if nf.GetParamsJSON() != "" {
var params map[string]interface{}
if err := json.Unmarshal([]byte(nf.GetParamsJSON()), &params); err == nil {
if id, ok := params["id"].(string); ok {
buttonId = id
}
if dt, ok := params["display_text"].(string); ok {
buttonText = dt
}
}
}
buttonClickData = map[string]interface{}{
"buttonId": buttonId,
"buttonText": buttonText,
"type": "native_flow_response",
"name": nf.GetName(),
"paramsJSON": nf.GetParamsJSON(),
}
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Button click detected (native_flow): name=%s, buttonId=%s, buttonText=%s", mycli.userID, nf.GetName(), buttonId, buttonText)
}
} else if resp := evt.Message.GetTemplateButtonReplyMessage(); resp != nil {
// Template button reply
buttonClickData = map[string]interface{}{
"buttonId": resp.GetSelectedID(),
"buttonText": resp.GetSelectedDisplayText(),
"type": "template_button_reply",
}
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Button click detected (template): buttonId=%s, buttonText=%s", mycli.userID, resp.GetSelectedID(), resp.GetSelectedDisplayText())
} else if resp := evt.Message.GetListResponseMessage(); resp != nil {
// List response (single select)
buttonClickData = map[string]interface{}{
"buttonId": resp.GetSingleSelectReply().GetSelectedRowID(),
"buttonText": resp.GetTitle(),
"type": "list_response",
"description": resp.GetDescription(),
}
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] List selection detected: rowId=%s, title=%s", mycli.userID, resp.GetSingleSelectReply().GetSelectedRowID(), resp.GetTitle())
}
// Se detectou clique em botão, emite evento separado "ButtonClick"
if buttonClickData != nil {
buttonClickMap := map[string]interface{}{
"event": "ButtonClick",
"data": map[string]interface{}{
"buttonId": buttonClickData["buttonId"],
"buttonText": buttonClickData["buttonText"],
"type": buttonClickData["type"],
"phone": dataMap["Sender"],
"jid": dataMap["Sender"],
"pushName": dataMap["PushName"],
"messageId": dataMap["ID"],
"chat": dataMap["Chat"],
"fromMe": dataMap["FromMe"],
"timestamp": evt.Info.Timestamp.Unix(),
"extraData": buttonClickData,
},
"instanceToken": mycli.token,
"instanceId": mycli.userID,
"instanceName": mycli.Instance.Name,
}
buttonClickJSON, err := json.Marshal(buttonClickMap)
if err == nil {
buttonClickQueue := strings.ToLower(fmt.Sprintf("%s.buttonclick", userID))
go mycli.service.CallWebhook(mycli.Instance, buttonClickQueue, buttonClickJSON)
if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {
go mycli.service.SendToGlobalQueues("ButtonClick", buttonClickJSON, mycli.userID)
}
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] ===== BUTTON CLICK EVENT DISPATCHED ===== Type: %s, ButtonId: %s", mycli.userID, buttonClickData["type"], buttonClickData["buttonId"])
}
}
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] ===== MESSAGE PROCESSING COMPLETED ===== ID: %s, From: %s, Type: %s, Webhook: %v", mycli.userID, evt.Info.ID, evt.Info.Chat.String(), evt.Info.Type, doWebhook)
case *events.Receipt:
doWebhook = true
@@ -1914,16 +2020,57 @@ func (w *whatsmeowService) CallWebhook(instance *instance_model.Instance, queueN
if contains(subscriptions, "MESSAGE") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
} else {
// Forward to GROUP/NEWSLETTER subscribers even without MESSAGE subscription
if dataMap, ok := data["data"].(map[string]interface{}); ok {
if infoMap, ok := dataMap["Info"].(map[string]interface{}); ok {
if chat, ok := infoMap["Chat"].(string); ok {
if strings.HasSuffix(chat, "@g.us") && contains(subscriptions, "GROUP") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s (Group)", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
} else if strings.HasSuffix(chat, "@newsletter") && contains(subscriptions, "NEWSLETTER") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s (Newsletter)", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
}
}
}
}
case "SendMessage":
if contains(subscriptions, "SEND_MESSAGE") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
} else {
if dataMap, ok := data["data"].(map[string]interface{}); ok {
if infoMap, ok := dataMap["Info"].(map[string]interface{}); ok {
if chat, ok := infoMap["Chat"].(string); ok {
if strings.HasSuffix(chat, "@g.us") && contains(subscriptions, "GROUP") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s (Group)", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
} else if strings.HasSuffix(chat, "@newsletter") && contains(subscriptions, "NEWSLETTER") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s (Newsletter)", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
}
}
}
}
case "Receipt":
if contains(subscriptions, "READ_RECEIPT") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
} else {
if dataMap, ok := data["data"].(map[string]interface{}); ok {
if chat, ok := dataMap["Chat"].(string); ok {
if strings.HasSuffix(chat, "@g.us") && contains(subscriptions, "GROUP") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s (Group)", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
} else if strings.HasSuffix(chat, "@newsletter") && contains(subscriptions, "NEWSLETTER") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s (Newsletter)", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
}
}
}
case "Presence":
if contains(subscriptions, "PRESENCE") {
@@ -1975,6 +2122,11 @@ func (w *whatsmeowService) CallWebhook(instance *instance_model.Instance, queueN
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
case "ButtonClick":
if contains(subscriptions, "BUTTON_CLICK") || contains(subscriptions, "MESSAGE") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
default:
return
@@ -2035,7 +2187,21 @@ func (w whatsmeowService) StartInstance(instanceId string) error {
}
if instance.Proxy == "" && w.config.ProxyHost != "" && w.config.ProxyPort != "" && w.config.ProxyUsername != "" && w.config.ProxyPassword != "" {
instance.Proxy = fmt.Sprintf(`{"host": "%s", "port": "%s", "username": "%s", "password": "%s"}`, w.config.ProxyHost, w.config.ProxyPort, w.config.ProxyUsername, w.config.ProxyPassword)
proxyConfig := ProxyConfig{
Protocol: utils.NormalizeProxyProtocol(w.config.ProxyProtocol, w.config.ProxyPort),
Host: w.config.ProxyHost,
Port: w.config.ProxyPort,
Username: w.config.ProxyUsername,
Password: w.config.ProxyPassword,
}
proxyJSON, err := json.Marshal(proxyConfig)
if err != nil {
w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to marshal proxy config: %v", instanceId, err)
return err
}
instance.Proxy = string(proxyJSON)
err = w.instanceRepository.UpdateProxy(instance.Id, instance.Proxy)
if err != nil {
@@ -2293,7 +2459,21 @@ func (w *whatsmeowService) SendToGlobalQueues(eventType string, payload []byte,
}
}
var (
cachedWebVersion *clientVersion
cachedWebVersionAt time.Time
cachedWebVersionMu sync.Mutex
webVersionCacheTTL = 1 * time.Hour
)
func fetchWhatsAppWebVersion() (*clientVersion, error) {
cachedWebVersionMu.Lock()
defer cachedWebVersionMu.Unlock()
if cachedWebVersion != nil && time.Since(cachedWebVersionAt) < webVersionCacheTTL {
return cachedWebVersion, nil
}
resp, err := http.Get("https://web.whatsapp.com/sw.js")
if err != nil {
return nil, fmt.Errorf("failed to fetch WhatsApp Web version: %v", err)
@@ -2327,11 +2507,13 @@ func fetchWhatsAppWebVersion() (*clientVersion, error) {
// Log qual padrão funcionou
if clientRevision > 0 {
return &clientVersion{
cachedWebVersion = &clientVersion{
Major: 2,
Minor: 3000,
Patch: clientRevision,
}, nil
}
cachedWebVersionAt = time.Now()
return cachedWebVersion, nil
}
}
}