diff --git a/.env.example b/.env.example index 831e431..b601db7 100644 --- a/.env.example +++ b/.env.example @@ -9,7 +9,7 @@ GLOBAL_API_KEY=429683C4C977415CAAFCCE10F7D57E11 WADEBUG=DEBUG LOGTYPE=console -WEBHOOKFILES=true +WEBHOOK_FILES=true CONNECT_ON_STARTUP=true @@ -20,6 +20,15 @@ AMQP_GLOBAL_ENABLED=false WEBHOOK_URL=https://webhook.site/2e6af2fa-6b04-497f-b4a1-13a905728d83 +# Proxy Configuration +# PROXY_PROTOCOL can be http, https or socks5. If omitted, it is inferred from +# the port (1080/2080/42000-43000 → socks5; otherwise http). +# PROXY_PROTOCOL=http +# PROXY_HOST=proxy.example.com +# PROXY_PORT=8080 +# PROXY_USERNAME=user +# PROXY_PASSWORD=secret + # Minio Configuration MINIO_ENABLED=true MINIO_ENDPOINT=localhost:9000 diff --git a/.github/ISSUE_TEMPLATE/-en--bug-report.yaml b/.github/ISSUE_TEMPLATE/-en--bug-report.yaml index 97f7a85..c529699 100644 --- a/.github/ISSUE_TEMPLATE/-en--bug-report.yaml +++ b/.github/ISSUE_TEMPLATE/-en--bug-report.yaml @@ -12,7 +12,7 @@ body: The issue tracker is only for reporting bugs and feature requests. For support questions, please visit: - [Community](https://evolutionfoundation.com.br/community) - - [WhatsApp Support](https://wa.me/553175038350) + - [WhatsApp Support](https://wa.me/553196219989)
**DO NOT OPEN AN ISSUE FOR GENERAL SUPPORT QUESTIONS.** diff --git a/.github/ISSUE_TEMPLATE/-pt--reportar-bug.yaml b/.github/ISSUE_TEMPLATE/-pt--reportar-bug.yaml index 0dc227d..4400a65 100644 --- a/.github/ISSUE_TEMPLATE/-pt--reportar-bug.yaml +++ b/.github/ISSUE_TEMPLATE/-pt--reportar-bug.yaml @@ -12,7 +12,7 @@ body: O rastreador de problemas é apenas para relatar bugs e solicitações de recursos. Para perguntas de suporte, acesse: - [Comunidade](https://evolutionfoundation.com.br/community) - - [WhatsApp Suporte](https://wa.me/553175038350) + - [WhatsApp Suporte](https://wa.me/553196219989)
**NÃO ABRA UM PROBLEMA PARA PERGUNTAS GERAIS DE SUPORTE.** diff --git a/CHANGELOG.md b/CHANGELOG.md index 031fa45..acceb98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,41 @@ # Evolution GO - Changelog +## v0.7.0 + +**Docker:** `evoapicloud/evolution-go:0.7.0` + +### 🆕 New Features +- **Multi-platform interactive messages** — Buttons, lists and carousel working on Android, iOS and WhatsApp Web/Desktop + - **SendButton**: removed `ViewOnceMessage` wrapper that blocked rendering on iOS and WhatsApp Web; `Footer` and `Header` are now conditional + - **SendList**: migrated from `InteractiveMessage`/`NativeFlowMessage` to legacy `ListMessage` (native protobuf) for broad compatibility + - **SendCarousel**: new endpoint `POST /send/carousel` with cards (image, text, footer, buttons) and automatic JPEG thumbnail generation for instant image loading + - `whatsmeow-lib`: added `biz` node for `InteractiveMessage` and pinned `product_list` type on the `biz` node for `ListMessage` +- **Base64 media support on `/send/media`** — The `url` field on `POST /send/media` now also accepts base64-encoded media. When the value does not start with `http://` or `https://`, it is treated as base64 and decoded; reuses the existing `SendMediaFile` flow +- **WhatsApp status endpoints** — new `POST /send/status/text` and `POST /send/status/media` publish text/image/video status to `status@broadcast`. Media endpoint supports both JSON (with URL) and multipart/form-data (file upload). Thanks @Eduardo-gato (#15) +- **Webhook routing for GROUP / NEWSLETTER** — when the primary `MESSAGE` / `SEND_MESSAGE` / `READ_RECEIPT` subscription is absent, events from `@g.us` chats are forwarded to `GROUP` subscribers and events from `@newsletter` chats to `NEWSLETTER` subscribers. Thanks @oismaelash (#18) + +### 🔧 Improvements +- **Proxy protocol** — new optional `protocol` field (and `PROXY_PROTOCOL` env) supporting `http`, `https`, `socks5`. Replaces the hardcoded SOCKS5 dialer with `client.SetProxyAddress`, fixing HTTP-proxy QR pairing (#12). Thanks @TBDevMaster (#13) +- **WhatsApp Web version cache** — `fetchWhatsAppWebVersion` now caches the result for 1 hour with a mutex instead of issuing one request per instance startup. Thanks @VitorS0uza (#24) +- **Manager flicker fix** — instance page no longer replaces the list with skeleton cards on every 5s polling cycle (`hasLoaded` flag). Thanks @TBDevMaster (#14), closes #11 +- **`WEBHOOKFILES` → `WEBHOOK_FILES`** — `.env.example`, docker-compose and docs aligned with the env var the runtime actually reads. Thanks @VitorS0uza (#22) +- **Dependency cleanup** — removed unused `github.com/EvolutionAPI/evo-gate` from `go.mod` +- **whatsmeow-lib** bumped to `0923702fb` +- **Telemetry removed** — dropped legacy `pkg/telemetry` + +### 🐛 Bug Fixes +- **`/message/edit`** — was silently ignored because the edit payload used `Conversation` while the original message was sent as `ExtendedTextMessage`. WhatsApp requires matching types; now the edit uses `ExtendedTextMessage` and the response returns the actual server timestamp instead of the zero value. Closes #16 +- **Sticker upload to S3/MinIO** — when `webp.Decode` or `png.Encode` failed, the whole media pipeline aborted and the sticker was lost from the webhook. Now we log a warning and keep the raw `.webp` bytes so the sticker still reaches the bucket. Closes #5 +- **Multipart `/send/media`** — the binary-upload branch silently dropped `mentionAll`, `mentionedJid` and `quoted`. These fields now parse from the form (with `mentionedJid` accepting repeated or comma-separated values) and reach the send service. Closes #2 + +### ⚠️ Breaking changes +- **Proxy** — previously all proxies were forced through SOCKS5. If you run SOCKS5 on a non-standard port (anything outside 1080/2080/42000-43000), set `PROXY_PROTOCOL=socks5` in the env or pass `"protocol": "socks5"` in the proxy body explicitly — otherwise the new protocol inference will fall back to HTTP. + +### 📝 Docs +- **README** — updated WhatsApp support number and issue templates +- **Interactive messages guide** — new `docs/wiki/guias-api/api-interactive.md` +- **Proxy docs** — environment variables, configuration guide and API reference updated with the new `protocol` field + ## v0.6.1 ### 🆕 New Features diff --git a/README.md b/README.md index bc89966..fa39825 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ evolution-go/ | Website | [evolutionfoundation.com.br](https://evolutionfoundation.com.br/) | | Documentation | [docs.evolutionfoundation.com.br](https://docs.evolutionfoundation.com.br/) | | Community | [evolutionfoundation.com.br/community](https://evolutionfoundation.com.br/community) | -| WhatsApp Support | [+55 31 7503-8350](https://wa.me/553175038350) | +| WhatsApp Support | [+55 31 9621-9989](https://wa.me/553196219989) | | GitHub Issues | [evolution-go/issues](https://github.com/EvolutionAPI/evolution-go/issues) | ## Hosting diff --git a/VERSION b/VERSION index ee6cdce..faef31a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.6.1 +0.7.0 diff --git a/cmd/evolution-go/main.go b/cmd/evolution-go/main.go index ddc760e..d9ad785 100644 --- a/cmd/evolution-go/main.go +++ b/cmd/evolution-go/main.go @@ -59,7 +59,6 @@ import ( server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler" storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces" minio_storage "github.com/EvolutionAPI/evolution-go/pkg/storage/minio" - "github.com/EvolutionAPI/evolution-go/pkg/telemetry" user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler" user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service" whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service" @@ -200,8 +199,6 @@ func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.C // NOVO: PollHandler usando PollService já inicializado no whatsmeowService (evita dupla inicialização) pollHandler := poll_handler.NewPollHandler(whatsmeowService.GetPollService(), loggerWrapper) - telemetry := telemetry.NewTelemetryService() - r := gin.Default() // CORS middleware — must be before everything else @@ -218,8 +215,6 @@ func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.C c.Next() }) - r.Use(telemetry.TelemetryMiddleware()) - r.Use(core.GateMiddleware(runtimeCtx)) // License routes (always accessible, even without license) diff --git a/docker/examples/.env.example b/docker/examples/.env.example index a72c0b4..4f8c9cd 100644 --- a/docker/examples/.env.example +++ b/docker/examples/.env.example @@ -58,7 +58,7 @@ LOG_COMPRESS=true CONNECT_ON_STARTUP=false # Enviar arquivos via webhook -WEBHOOKFILES=true +WEBHOOK_FILES=true # Nome do sistema operacional OS_NAME=Linux diff --git a/docker/examples/docker-compose.full.yml b/docker/examples/docker-compose.full.yml index 31c36f7..c0035d9 100644 --- a/docker/examples/docker-compose.full.yml +++ b/docker/examples/docker-compose.full.yml @@ -31,7 +31,7 @@ services: # Conexão CONNECT_ON_STARTUP: "false" - WEBHOOKFILES: "true" + WEBHOOK_FILES: "true" # Sistema OS_NAME: "Linux" diff --git a/docker/examples/docker-compose.swarm.yml b/docker/examples/docker-compose.swarm.yml index b764f28..00c00fe 100644 --- a/docker/examples/docker-compose.swarm.yml +++ b/docker/examples/docker-compose.swarm.yml @@ -29,7 +29,7 @@ services: # Conexão CONNECT_ON_STARTUP: "true" - WEBHOOKFILES: "true" + WEBHOOK_FILES: "true" # Sistema OS_NAME: "Linux" diff --git a/docker/examples/docker-compose.yml b/docker/examples/docker-compose.yml index 2714e16..0a60912 100644 --- a/docker/examples/docker-compose.yml +++ b/docker/examples/docker-compose.yml @@ -31,7 +31,7 @@ services: # Conexão CONNECT_ON_STARTUP: "false" - WEBHOOKFILES: "true" + WEBHOOK_FILES: "true" # Sistema OS_NAME: "Linux" diff --git a/docs/wiki/deploy-producao/docker-deployment.md b/docs/wiki/deploy-producao/docker-deployment.md index 70d1d8c..f4d7459 100644 --- a/docs/wiki/deploy-producao/docker-deployment.md +++ b/docs/wiki/deploy-producao/docker-deployment.md @@ -85,7 +85,7 @@ services: WADEBUG: "INFO" LOGTYPE: "console" CONNECT_ON_STARTUP: "false" - WEBHOOKFILES: "true" + WEBHOOK_FILES: "true" volumes: - evolution_data:/app/dbdata @@ -469,7 +469,7 @@ data: WADEBUG: "INFO" LOGTYPE: "console" CONNECT_ON_STARTUP: "false" - WEBHOOKFILES: "true" + WEBHOOK_FILES: "true" DATABASE_SAVE_MESSAGES: "false" ``` diff --git a/docs/wiki/desenvolvimento/development-guide.md b/docs/wiki/desenvolvimento/development-guide.md index a471264..03cb695 100644 --- a/docs/wiki/desenvolvimento/development-guide.md +++ b/docs/wiki/desenvolvimento/development-guide.md @@ -147,7 +147,7 @@ LOGTYPE=console # Configurações de desenvolvimento CONNECT_ON_STARTUP=false -WEBHOOKFILES=true +WEBHOOK_FILES=true OS_NAME=Linux ``` diff --git a/docs/wiki/fundamentos/configuration.md b/docs/wiki/fundamentos/configuration.md index 35460c0..575a8ad 100644 --- a/docs/wiki/fundamentos/configuration.md +++ b/docs/wiki/fundamentos/configuration.md @@ -211,7 +211,7 @@ CONNECT_ON_STARTUP=false **Recomendação**: `false` para maior controle sobre o ciclo de vida das instâncias. -### WEBHOOKFILES +### WEBHOOK_FILES Envia URLs de mídia nos payloads de webhook. @@ -219,7 +219,7 @@ Envia URLs de mídia nos payloads de webhook. - **Padrão**: `true` ```env -WEBHOOKFILES=true +WEBHOOK_FILES=true ``` ### QRCODE_MAX_COUNT @@ -540,7 +540,7 @@ LOGTYPE=console # Comportamento CONNECT_ON_STARTUP=false -WEBHOOKFILES=true +WEBHOOK_FILES=true CHECK_USER_EXISTS=true EVENT_IGNORE_STATUS=true ``` diff --git a/docs/wiki/fundamentos/installation.md b/docs/wiki/fundamentos/installation.md index ec05c03..ebdd3af 100644 --- a/docs/wiki/fundamentos/installation.md +++ b/docs/wiki/fundamentos/installation.md @@ -198,7 +198,7 @@ DATABASE_SAVE_MESSAGES=false WADEBUG=DEBUG LOGTYPE=console CONNECT_ON_STARTUP=false -WEBHOOKFILES=true +WEBHOOK_FILES=true OS_NAME=Linux ``` diff --git a/docs/wiki/guias-api/api-interactive.md b/docs/wiki/guias-api/api-interactive.md new file mode 100644 index 0000000..368b2a9 --- /dev/null +++ b/docs/wiki/guias-api/api-interactive.md @@ -0,0 +1,724 @@ +# API de Mensagens Interativas + +Documentação completa dos endpoints para enviar mensagens interativas no WhatsApp: botões, listas e carrosséis. Todos os endpoints são compatíveis com **Android**, **iOS (iPhone)** e **WhatsApp Web/Desktop**. + +## 📋 Índice + +- [Enviar Botões](#enviar-botões) +- [Enviar Lista](#enviar-lista) +- [Enviar Carrossel](#enviar-carrossel) +- [Evento ButtonClick (Rastreio)](#evento-buttonclick) +- [Tipos de Botões](#tipos-de-botões) +- [Notas de Compatibilidade](#notas-de-compatibilidade) + +--- + +## Enviar Botões + +Envia uma mensagem com botões interativos. Suporta botões de resposta rápida (reply), URL, ligação (call), cópia (copy) e PIX. + +**Endpoint**: `POST /send/button` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "number": "5511999999999", + "title": "Título da Mensagem", + "description": "Texto do corpo da mensagem", + "footer": "Texto do rodapé", + "buttons": [ + { + "type": "reply", + "displayText": "Texto do Botão", + "id": "identificador_unico" + } + ], + "delay": 1000, + "quoted": { + "messageId": "BAE5..." + } +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário (formato: DDI + DDD + número) | +| `description` | string | ✅ Sim | Texto do corpo da mensagem | +| `buttons` | array | ✅ Sim | Array de botões (ver [Tipos de Botões](#tipos-de-botões)) | +| `title` | string | ❌ Não | Título exibido em negrito acima do corpo | +| `footer` | string | ❌ Não | Texto pequeno no rodapé. **Não enviar vazio** | +| `delay` | int32 | ❌ Não | Delay em milissegundos antes de enviar | +| `mentionedJid` | string | ❌ Não | JID do usuário a mencionar | +| `mentionAll` | bool | ❌ Não | Mencionar todos os participantes (apenas grupos) | +| `formatJid` | bool | ❌ Não | Formatar número automaticamente (padrão: true) | +| `quoted` | object | ❌ Não | Mensagem a ser citada | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB034D434158AD2CC0B9A", + "Chat": "5511999999999@s.whatsapp.net", + "Type": "ButtonMessage", + "Timestamp": "2026-04-01T17:54:09Z" + } + } +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "phone number is required" +} +``` + +### Exemplo 1: Botões Quick Reply + +Máximo 3 botões. Não pode misturar com outros tipos. + +```bash +curl -X POST http://localhost:4000/send/button \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "title": "Atendimento", + "description": "Como podemos ajudar você hoje?", + "footer": "Responda clicando em um botão", + "buttons": [ + {"type": "reply", "displayText": "Suporte Técnico", "id": "suporte"}, + {"type": "reply", "displayText": "Financeiro", "id": "financeiro"}, + {"type": "reply", "displayText": "Vendas", "id": "vendas"} + ] + }' +``` + +### Exemplo 2: Botões Mistos (URL + Call + Copy) + +Podem ser combinados entre si livremente. + +```bash +curl -X POST http://localhost:4000/send/button \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "title": "Nossos Canais", + "description": "Escolha como deseja entrar em contato:", + "footer": "Empresa XYZ", + "buttons": [ + {"type": "url", "displayText": "Acessar Site", "url": "https://empresa.com"}, + {"type": "call", "displayText": "Ligar para Nós", "phoneNumber": "+5511999999999"}, + {"type": "copy", "displayText": "Copiar Email", "copyCode": "contato@empresa.com"} + ] + }' +``` + +### Exemplo 3: Botão PIX + +Deve ser enviado **sozinho**, sem outros botões. + +```bash +curl -X POST http://localhost:4000/send/button \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "title": "Pagamento PIX", + "description": "Realize o pagamento via PIX:", + "buttons": [ + { + "type": "pix", + "currency": "BRL", + "name": "Empresa XYZ LTDA", + "keyType": "CNPJ", + "key": "12345678000199" + } + ] + }' +``` + +--- + +## Enviar Lista + +Envia uma mensagem com lista de opções organizadas em seções. O usuário toca no botão para abrir a lista e seleciona uma opção. + +**Endpoint**: `POST /send/list` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "number": "5511999999999", + "title": "Título da Lista", + "description": "Texto do corpo da mensagem", + "buttonText": "Texto do botão que abre a lista", + "footerText": "Texto do rodapé", + "sections": [ + { + "title": "Nome da Seção", + "rows": [ + { + "title": "Título da Opção", + "description": "Descrição da opção", + "rowId": "identificador_unico" + } + ] + } + ], + "delay": 1000, + "quoted": { + "messageId": "BAE5..." + } +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `description` | string | ✅ Sim | Texto do corpo da mensagem | +| `sections` | array | ✅ Sim | Array de seções contendo rows | +| `buttonText` | string | ❌ Não | Texto do botão que abre a lista (padrão: "Ver Menu") | +| `title` | string | ❌ Não | Título em negrito no topo | +| `footerText` | string | ❌ Não | Texto do rodapé | +| `delay` | int32 | ❌ Não | Delay em milissegundos antes de enviar | +| `mentionedJid` | string | ❌ Não | JID do usuário a mencionar | +| `mentionAll` | bool | ❌ Não | Mencionar todos (apenas grupos) | +| `formatJid` | bool | ❌ Não | Formatar número automaticamente | +| `quoted` | object | ❌ Não | Mensagem a ser citada | + +**Parâmetros da Seção**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `title` | string | ✅ Sim | Nome da seção | +| `rows` | array | ✅ Sim | Array de opções da seção | + +**Parâmetros da Row**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `title` | string | ✅ Sim | Texto da opção | +| `description` | string | ❌ Não | Descrição da opção | +| `rowId` | string | ✅ Sim | ID único para rastreio do clique | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Chat": "5511999999999@s.whatsapp.net", + "Type": "ListMessage", + "Timestamp": "2026-04-01T18:00:00Z" + } + } +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "sections are required" +} +``` + +### Exemplo 1: Cardápio Digital + +```bash +curl -X POST http://localhost:4000/send/list \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "title": "Cardápio Digital", + "description": "Escolha um item do nosso cardápio:", + "buttonText": "Ver Cardápio", + "footerText": "Restaurante XYZ", + "sections": [ + { + "title": "Pratos Principais", + "rows": [ + {"title": "Filé Mignon", "description": "Com arroz e batata - R$ 45,90", "rowId": "file_mignon"}, + {"title": "Salmão Grelhado", "description": "Com legumes - R$ 52,90", "rowId": "salmao"}, + {"title": "Frango Parmegiana", "description": "Com purê - R$ 35,90", "rowId": "frango"} + ] + }, + { + "title": "Bebidas", + "rows": [ + {"title": "Suco Natural", "description": "Laranja, Limão ou Maracujá - R$ 8,00", "rowId": "suco"}, + {"title": "Refrigerante", "description": "Lata 350ml - R$ 6,00", "rowId": "refri"}, + {"title": "Água Mineral", "description": "500ml - R$ 4,00", "rowId": "agua"} + ] + }, + { + "title": "Sobremesas", + "rows": [ + {"title": "Pudim", "description": "R$ 12,00", "rowId": "pudim"}, + {"title": "Petit Gâteau", "description": "R$ 18,00", "rowId": "petit_gateau"} + ] + } + ] + }' +``` + +### Exemplo 2: Menu de Serviços + +```bash +curl -X POST http://localhost:4000/send/list \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "description": "Selecione o serviço desejado:", + "buttonText": "Ver Serviços", + "sections": [ + { + "title": "Atendimento", + "rows": [ + {"title": "Falar com Atendente", "description": "Atendimento humano", "rowId": "atendente"}, + {"title": "FAQ", "description": "Perguntas frequentes", "rowId": "faq"}, + {"title": "Abrir Ticket", "description": "Registrar ocorrência", "rowId": "ticket"} + ] + } + ] + }' +``` + +--- + +## Enviar Carrossel + +Envia uma mensagem com cards deslizáveis (carrossel), cada um com imagem, texto, rodapé e botões. Ideal para catálogos de produtos, planos e portfólios. + +**Endpoint**: `POST /send/carousel` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "number": "5511999999999", + "body": "Texto do corpo principal", + "footer": "Texto do rodapé principal", + "cards": [ + { + "header": { + "title": "Título do Card", + "imageUrl": "https://url-da-imagem.com/foto.jpg" + }, + "body": "Texto do corpo do card", + "footer": "Rodapé do card", + "buttons": [ + { + "type": "REPLY", + "displayText": "Texto do Botão", + "id": "id_rastreio" + } + ] + } + ], + "delay": 1000, + "quoted": { + "messageId": "BAE5..." + } +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `cards` | array | ✅ Sim | Array de cards (mínimo 2, máximo ~10) | +| `body` | string | ❌ Não | Texto do corpo principal (acima dos cards) | +| `footer` | string | ❌ Não | Rodapé principal | +| `delay` | int32 | ❌ Não | Delay em milissegundos antes de enviar | +| `formatJid` | bool | ❌ Não | Formatar número automaticamente | +| `quoted` | object | ❌ Não | Mensagem a ser citada | + +**Parâmetros do Card**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `header` | object | ✅ Sim | Cabeçalho do card (deve conter imagem) | +| `header.title` | string | ❌ Não | Título do card | +| `header.subtitle` | string | ❌ Não | Subtítulo do card | +| `header.imageUrl` | string | ✅ Sim* | URL da imagem do card | +| `header.videoUrl` | string | ❌ Não | URL de vídeo (alternativa à imagem) | +| `body` | string | ✅ Sim | Texto do corpo do card | +| `footer` | string | ❌ Não | Rodapé do card | +| `buttons` | array | ❌ Não | Array de botões do card | + +> ⚠️ **Importante**: Todos os cards **devem** ter imagem (`imageUrl`) para o carrossel renderizar corretamente em todos os dispositivos. As imagens recebem thumbnail JPEG automaticamente para carregamento instantâneo. + +**Parâmetros do Botão do Card**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `type` | string | ❌ Não | Tipo do botão: `REPLY`, `URL`, `CALL`, `COPY` (padrão: `REPLY`) | +| `displayText` | string | ✅ Sim | Texto visível do botão | +| `id` | string | ✅ Sim* | ID para rastreio (reply) ou URL/telefone (url/call) | +| `copyCode` | string | ✅ Sim* | Texto a copiar (apenas tipo `COPY`) | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Chat": "5511999999999@s.whatsapp.net", + "Type": "InteractiveMessage", + "Timestamp": "2026-04-01T18:30:00Z" + } + } +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "cards are required (minimum 1)" +} +``` + +### Exemplo 1: Catálogo de Produtos + +```bash +curl -X POST http://localhost:4000/send/carousel \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "body": "Confira nossos produtos em destaque!", + "footer": "Loja Virtual XYZ", + "cards": [ + { + "header": { + "title": "Smartphone Pro Max", + "imageUrl": "https://placehold.co/600x400/1a1a2e/white?text=Smartphone" + }, + "body": "Tela 6.7 AMOLED, 256GB, Câmera 108MP.\nDe R$ 4.999 por R$ 3.799!", + "footer": "12x sem juros", + "buttons": [ + {"type": "REPLY", "displayText": "Comprar", "id": "comprar_smartphone"}, + {"type": "URL", "displayText": "Ver Detalhes", "id": "https://loja.com/smartphone"} + ] + }, + { + "header": { + "title": "Notebook Ultra", + "imageUrl": "https://placehold.co/600x400/16213e/white?text=Notebook" + }, + "body": "Intel i7, 16GB RAM, SSD 512GB, Tela 15.6 FHD.\nPor apenas R$ 5.299!", + "footer": "Frete grátis", + "buttons": [ + {"type": "REPLY", "displayText": "Comprar", "id": "comprar_notebook"}, + {"type": "URL", "displayText": "Ver Detalhes", "id": "https://loja.com/notebook"} + ] + }, + { + "header": { + "title": "Fone Bluetooth", + "imageUrl": "https://placehold.co/600x400/0f3460/white?text=Fone" + }, + "body": "Cancelamento de ruído ativo, 30h bateria.\nR$ 299,90", + "footer": "Envio imediato", + "buttons": [ + {"type": "REPLY", "displayText": "Comprar", "id": "comprar_fone"}, + {"type": "CALL", "displayText": "Ligar p/ Comprar", "id": "+5511999999999"} + ] + } + ] + }' +``` + +### Exemplo 2: Planos de Serviço + +```bash +curl -X POST http://localhost:4000/send/carousel \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "body": "Conheça nossos planos:", + "cards": [ + { + "header": { + "title": "Plano Básico", + "imageUrl": "https://placehold.co/600x400/2ecc71/white?text=Basico" + }, + "body": "Ideal para pequenas empresas.\n- 1.000 mensagens/mês\n- 1 instância\n- Suporte email\n\nR$ 97/mês", + "buttons": [ + {"type": "REPLY", "displayText": "Contratar Básico", "id": "plano_basico"}, + {"type": "COPY", "displayText": "Copiar Link", "copyCode": "https://planos.com/basico"} + ] + }, + { + "header": { + "title": "Plano Pro", + "imageUrl": "https://placehold.co/600x400/3498db/white?text=Pro" + }, + "body": "Para empresas em crescimento.\n- 10.000 mensagens/mês\n- 5 instâncias\n- Suporte prioritário\n\nR$ 297/mês", + "buttons": [ + {"type": "REPLY", "displayText": "Contratar Pro", "id": "plano_pro"}, + {"type": "COPY", "displayText": "Copiar Link", "copyCode": "https://planos.com/pro"} + ] + }, + { + "header": { + "title": "Plano Enterprise", + "imageUrl": "https://placehold.co/600x400/9b59b6/white?text=Enterprise" + }, + "body": "Solução completa.\n- Mensagens ilimitadas\n- Instâncias ilimitadas\n- Suporte 24/7\n\nSob consulta", + "buttons": [ + {"type": "REPLY", "displayText": "Solicitar Orçamento", "id": "plano_enterprise"}, + {"type": "CALL", "displayText": "Falar com Vendas", "id": "+5511999999999"} + ] + } + ] + }' +``` + +--- + +## Evento ButtonClick + +Quando um usuário clica em um botão, seleciona um item de lista ou interage com um card de carrossel, a API dispara o evento `ButtonClick` para todos os canais configurados na instância. + +### Canais de Disparo + +- **Webhook** - Callback HTTP para URL configurada +- **WebSocket** - Evento em tempo real +- **RabbitMQ** - Mensagem na fila +- **NATS** - Mensagem no tópico + +### Requisito + +A instância deve ter o evento `BUTTON_CLICK` ou `MESSAGE` habilitado na configuração de events. + +### Payload do Evento + +```json +{ + "event": "ButtonClick", + "data": { + "buttonId": "suporte", + "buttonText": "Suporte Técnico", + "type": "native_flow_response", + "phone": "5511999999999", + "jid": "5511999999999@s.whatsapp.net", + "pushName": "João Silva", + "messageId": "3EB034D434158AD2CC0B9A", + "chat": "5511999999999@s.whatsapp.net", + "fromMe": false, + "timestamp": 1711990500, + "extraData": {} + }, + "instanceToken": "token_da_instancia", + "instanceId": "uuid-da-instancia", + "instanceName": "nome_da_instancia" +} +``` + +### Campos do Evento + +| Campo | Tipo | Descrição | +|-------|------|-----------| +| `buttonId` | string | ID do botão/row clicado (conforme definido no envio) | +| `buttonText` | string | Texto exibido no botão/row | +| `type` | string | Tipo de resposta (ver tabela abaixo) | +| `phone` | string | Número do usuário que clicou | +| `jid` | string | JID completo do usuário | +| `pushName` | string | Nome do contato no WhatsApp | +| `messageId` | string | ID da mensagem de resposta | +| `chat` | string | JID do chat | +| `fromMe` | bool | Se a mensagem é própria | +| `timestamp` | int64 | Timestamp Unix do clique | + +### Tipos de Resposta + +| Valor de `type` | Origem | +|-----------------|--------| +| `native_flow_response` | Clique em botão enviado via `/send/button` ou `/send/carousel` | +| `list_response` | Seleção de item em lista enviada via `/send/list` | +| `buttons_response` | Resposta a botões legados (ButtonsMessage) | +| `template_button_reply` | Resposta a template buttons | + +### Exemplo: Botão Reply Clicado + +```json +{ + "event": "ButtonClick", + "data": { + "buttonId": "vendas", + "buttonText": "Vendas", + "type": "native_flow_response", + "phone": "5511999999999", + "jid": "5511999999999@s.whatsapp.net", + "pushName": "Maria Santos", + "messageId": "3EB0XXXXXXXXXXXXXX", + "chat": "5511999999999@s.whatsapp.net", + "fromMe": false, + "timestamp": 1711991000 + }, + "instanceToken": "teste123", + "instanceId": "4ee8ab07-8a67-42a8-a029-f382315912b1", + "instanceName": "minha_instancia" +} +``` + +### Exemplo: Item de Lista Selecionado + +```json +{ + "event": "ButtonClick", + "data": { + "buttonId": "file_mignon", + "buttonText": "Filé Mignon", + "type": "list_response", + "phone": "5511999999999", + "jid": "5511999999999@s.whatsapp.net", + "pushName": "Pedro Oliveira", + "messageId": "3EB0XXXXXXXXXXXXXX", + "chat": "5511999999999@s.whatsapp.net", + "fromMe": false, + "timestamp": 1711991500 + }, + "instanceToken": "teste123", + "instanceId": "4ee8ab07-8a67-42a8-a029-f382315912b1", + "instanceName": "minha_instancia" +} +``` + +### Exemplo: Botão de Carrossel Clicado + +```json +{ + "event": "ButtonClick", + "data": { + "buttonId": "comprar_smartphone", + "buttonText": "Comprar", + "type": "native_flow_response", + "phone": "5511999999999", + "jid": "5511999999999@s.whatsapp.net", + "pushName": "Ana Costa", + "messageId": "3EB0XXXXXXXXXXXXXX", + "chat": "5511999999999@s.whatsapp.net", + "fromMe": false, + "timestamp": 1711992000 + }, + "instanceToken": "teste123", + "instanceId": "4ee8ab07-8a67-42a8-a029-f382315912b1", + "instanceName": "minha_instancia" +} +``` + +--- + +## Tipos de Botões + +### Resumo por Endpoint + +| Tipo | SendButton | SendCarousel | Campo obrigatório | +|------|-----------|-------------|-------------------| +| Reply | `"reply"` | `"REPLY"` (padrão) | `displayText`, `id` | +| URL | `"url"` | `"URL"` | `displayText`, `url` ou `id` | +| Call | `"call"` | `"CALL"` | `displayText`, `phoneNumber` ou `id` | +| Copy | `"copy"` | `"COPY"` | `displayText`, `copyCode` | +| PIX | `"pix"` | N/A | `currency`, `name`, `keyType`, `key` | + +### Regras de Combinação + +- **Reply**: Máximo 3 botões. **Não** pode misturar com outros tipos no mesmo envio. +- **PIX**: Deve ser enviado **sozinho**, sem outros botões. +- **URL / Call / Copy**: Podem ser combinados livremente entre si. +- **Carrossel**: Todos os tipos (exceto PIX) podem ser combinados no mesmo card. +- **Lista**: Não possui botões nos items. Usa `rowId` para rastreio. + +### Estrutura de Cada Tipo + +**Reply** (Resposta Rápida): +```json +{"type": "reply", "displayText": "Suporte", "id": "btn_suporte"} +``` + +**URL** (Abre Link): +```json +{"type": "url", "displayText": "Acessar Site", "url": "https://empresa.com"} +``` + +**Call** (Ligação): +```json +{"type": "call", "displayText": "Ligar Agora", "phoneNumber": "+5511999999999"} +``` + +**Copy** (Copiar Texto): +```json +{"type": "copy", "displayText": "Copiar Código", "copyCode": "DESCONTO20"} +``` + +**PIX** (Pagamento): +```json +{ + "type": "pix", + "currency": "BRL", + "name": "Empresa XYZ", + "keyType": "CPF", + "key": "12345678901" +} +``` + +--- + +## Notas de Compatibilidade + +### Regras para Funcionamento em Todos os Dispositivos + +| Regra | Detalhe | +|-------|---------| +| Footer vazio | **Não** envie campo `footer` vazio. Omita o campo ou preencha com texto | +| Imagens no carrossel | **Todos** os cards devem ter `imageUrl` para renderizar corretamente | +| Mínimo de cards | Carrossel requer no **mínimo 2 cards** | +| Thumbnails | Gerados automaticamente pela API (72px JPEG) para carregamento instantâneo | +| Formato do número | DDI + DDD + número, sem caracteres especiais (`5511999999999`) | +| Grupos | Use o JID do grupo (ex: `120363XXXXX@g.us`) | +| Mensagem quoted | Adicione `"quoted": {"messageId": "ID"}` ao payload | + +### Compatibilidade Testada + +| Tipo de Mensagem | Android | iOS (iPhone) | WhatsApp Web | +|------------------|---------|--------------|--------------| +| Botões (reply) | ✅ | ✅ | ✅ | +| Botões (url) | ✅ | ✅ | ✅ | +| Botões (call) | ✅ | ✅ | ✅ | +| Botões (copy) | ✅ | ✅ | ✅ | +| Botões (pix) | ✅ | ✅ | ✅ | +| Lista | ✅ | ✅ | ✅ | +| Carrossel | ✅ | ✅ | ✅ | diff --git a/docs/wiki/guias-api/api-messages.md b/docs/wiki/guias-api/api-messages.md index 394c17e..35e2747 100644 --- a/docs/wiki/guias-api/api-messages.md +++ b/docs/wiki/guias-api/api-messages.md @@ -12,8 +12,9 @@ Documentação completa dos endpoints para enviar e gerenciar mensagens WhatsApp - [Enviar Sticker](#enviar-sticker) - [Enviar Localização](#enviar-localização) - [Enviar Contato](#enviar-contato) -- [~~Enviar Botões~~](#enviar-botões) ⚠️ **DEPRECIADO** -- [~~Enviar Lista~~](#enviar-lista) ⚠️ **DEPRECIADO** +- [Enviar Botões](api-interactive.md#enviar-botões) ➡️ **Ver [API de Mensagens Interativas](api-interactive.md)** +- [Enviar Lista](api-interactive.md#enviar-lista) ➡️ **Ver [API de Mensagens Interativas](api-interactive.md)** +- [Enviar Carrossel](api-interactive.md#enviar-carrossel) ➡️ **Ver [API de Mensagens Interativas](api-interactive.md)** ### Gerenciar Mensagens - [Reagir a Mensagem](#reagir-a-mensagem) diff --git a/docs/wiki/referencia/environment-variables.md b/docs/wiki/referencia/environment-variables.md index a1abf27..2b97a96 100644 --- a/docs/wiki/referencia/environment-variables.md +++ b/docs/wiki/referencia/environment-variables.md @@ -59,7 +59,7 @@ POSTGRES_USERS_DB=postgresql://user:pass@host:5432/evogo_users?sslmode=disable | Variável | Padrão | Descrição | |----------|--------|-----------| | `CONNECT_ON_STARTUP` | `false` | Conectar instâncias ao iniciar servidor | -| `WEBHOOKFILES` | `true` | Enviar URLs de mídia em webhooks | +| `WEBHOOK_FILES` | `true` | Enviar URLs de mídia em webhooks | | `QRCODE_MAX_COUNT` | `5` | Tentativas máximas de QR Code | | `CHECK_USER_EXISTS` | `true` | Validar destinatário antes de enviar | @@ -197,7 +197,7 @@ LOGTYPE=console # Comportamento CONNECT_ON_STARTUP=false -WEBHOOKFILES=true +WEBHOOK_FILES=true CHECK_USER_EXISTS=true EVENT_IGNORE_STATUS=true diff --git a/evolution-go b/evolution-go index 8fbb1f9..e074bf6 100755 Binary files a/evolution-go and b/evolution-go differ diff --git a/go.mod b/go.mod index e877705..ef2a864 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/EvolutionAPI/evolution-go go 1.25.0 require ( - github.com/EvolutionAPI/evo-gate v0.1.2 github.com/chai2010/webp v1.1.1 github.com/gabriel-vasile/mimetype v1.4.5 github.com/gin-gonic/gin v1.10.0 diff --git a/go.sum b/go.sum index b2d291d..4ec26f6 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,6 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= -github.com/EvolutionAPI/evo-gate v0.1.2 h1:ZPQ9SZ7OlajNU1pbtYqbMg1U/ZiUSKmlrYk0GHWOXkc= -github.com/EvolutionAPI/evo-gate v0.1.2/go.mod h1:48tcAgZ0yVojqLdmLpOSyWDGqPODBYXYRSEs2yIUI/w= github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM= diff --git a/pkg/config/config.go b/pkg/config/config.go index a7a540a..4e0c19e 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -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, diff --git a/pkg/config/env/env.go b/pkg/config/env/env.go index 0fbd936..cda9be8 100644 --- a/pkg/config/env/env.go +++ b/pkg/config/env/env.go @@ -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" diff --git a/pkg/core/c0.go b/pkg/core/c0.go index e93caa1..da07b5a 100644 --- a/pkg/core/c0.go +++ b/pkg/core/c0.go @@ -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) } diff --git a/pkg/instance/handler/instance_handler.go b/pkg/instance/handler/instance_handler.go index ebf8406..9218180 100644 --- a/pkg/instance/handler/instance_handler.go +++ b/pkg/instance/handler/instance_handler.go @@ -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}) diff --git a/pkg/instance/service/instance_service.go b/pkg/instance/service/instance_service.go index 32d831e..25831fc 100644 --- a/pkg/instance/service/instance_service.go +++ b/pkg/instance/service/instance_service.go @@ -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, diff --git a/pkg/internal/event_types/event_types.go b/pkg/internal/event_types/event_types.go index 5ff8f87..3f7a632 100644 --- a/pkg/internal/event_types/event_types.go +++ b/pkg/internal/event_types/event_types.go @@ -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 { diff --git a/pkg/message/service/message_service.go b/pkg/message/service/message_service.go index 36ffb68..b2b21c7 100644 --- a/pkg/message/service/message_service.go +++ b/pkg/message/service/message_service.go @@ -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( diff --git a/pkg/routes/routes.go b/pkg/routes/routes.go index 0064014..f51e7d9 100644 --- a/pkg/routes/routes.go +++ b/pkg/routes/routes.go @@ -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") diff --git a/pkg/sendMessage/handler/send_handler.go b/pkg/sendMessage/handler/send_handler.go index 7e4e43f..cbe4b75 100644 --- a/pkg/sendMessage/handler/send_handler.go +++ b/pkg/sendMessage/handler/send_handler.go @@ -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 { diff --git a/pkg/sendMessage/service/send_service.go b/pkg/sendMessage/service/send_service.go index 09db21a..f887049 100644 --- a/pkg/sendMessage/service/send_service.go +++ b/pkg/sendMessage/service/send_service.go @@ -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, diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index cf1697f..e759347 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -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: diff --git a/pkg/whatsmeow/service/whatsmeow.go b/pkg/whatsmeow/service/whatsmeow.go index 6af7174..78ec6c1 100644 --- a/pkg/whatsmeow/service/whatsmeow.go +++ b/pkg/whatsmeow/service/whatsmeow.go @@ -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()), ¶ms); 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 } } } diff --git a/whatsmeow-lib b/whatsmeow-lib index 28cca79..0923702 160000 --- a/whatsmeow-lib +++ b/whatsmeow-lib @@ -1 +1 @@ -Subproject commit 28cca7935ac05814b8ad745d0c3a5e6dc2372560 +Subproject commit 0923702fb3fac8525241f15331b92116485d69eb