merge: promote maintained-stable (v0.7.2-evogo.3) into main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
997bbc85c2
154 files changed
+83129
-2
No files matched your search
@@ -0,0 +1,48 @@
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# Documentation
|
||||
README.md
|
||||
# docs/ - Mantido porque docs/docs.go é necessário para o build (gerado pelo swagger)
|
||||
docs/wiki/
|
||||
|
||||
# Logs
|
||||
logs/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Build artifacts
|
||||
server
|
||||
build/
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
docker/
|
||||
|
||||
# Scripts
|
||||
*.sh
|
||||
Makefile
|
||||
|
||||
# Test files
|
||||
*_test.go
|
||||
*.test
|
||||
|
||||
# Manager/dist é necessário - serve arquivos estáticos do frontend React
|
||||
# Não excluir - precisa estar na imagem final para ser acessado via /manager
|
||||
|
||||
# Keep these important files/folders for build:
|
||||
# - whatsmeow/ (nossa versão local modificada)
|
||||
# - go.mod, go.sum (dependências)
|
||||
# - pkg/, cmd/ (código fonte necessário para compilar)
|
||||
# - docs/docs.go (gerado pelo swagger, necessário para build)
|
||||
|
||||
# IMPORTANT: O código-fonte (pkg/, cmd/, etc.) é necessário no stage de build
|
||||
# mas NÃO é copiado para a imagem final - apenas o executável compilado vai.
|
||||
@@ -0,0 +1,53 @@
|
||||
SERVER_PORT=8080
|
||||
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:root@localhost:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://postgres:root@localhost:5432/evogo_users?sslmode=disable
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
CLIENT_NAME=evolution
|
||||
|
||||
GLOBAL_API_KEY=429683C4C977415CAAFCCE10F7D57E11
|
||||
|
||||
# License — headless auto-activation by email.
|
||||
# Set this to the email you used in your first manual license registration.
|
||||
# On startup, the service will silently call /v1/register/auto and skip the
|
||||
# browser flow. Falls back to the manual flow if the email isn't registered yet.
|
||||
# Leave empty (or unset) to keep the default behavior (manual registration).
|
||||
# [email protected]
|
||||
|
||||
WADEBUG=DEBUG
|
||||
LOGTYPE=console
|
||||
WEBHOOK_FILES=true
|
||||
|
||||
CONNECT_ON_STARTUP=true
|
||||
|
||||
OS_NAME=Evolution GO
|
||||
|
||||
# Passkey (WebAuthn) pairing — required only for accounts that ask for a passkey
|
||||
# when linking a device. Set this to the PUBLIC base URL of THIS API, reachable
|
||||
# by the browser where WhatsApp Web opens (the Evolution Passkey Helper extension
|
||||
# calls it from the web.whatsapp.com origin). Use a public domain in production,
|
||||
# or a tunnel (ngrok/cloudflared) / LAN IP in development — NOT localhost if the
|
||||
# browser runs on another machine. See docs/wiki/guias-api/passkey-pairing.md.
|
||||
# PASSKEY_PUBLIC_URL=https://your-api.example.com
|
||||
|
||||
AMQP_URL=amqp://admin:admin@localhost:5672/default
|
||||
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
|
||||
MINIO_ACCESS_KEY=minioadmin
|
||||
MINIO_SECRET_KEY=minioadmin
|
||||
MINIO_BUCKET=evolution-media
|
||||
MINIO_USE_SSL=false
|
||||
@@ -0,0 +1,52 @@
|
||||
name: CI - Validacao Go
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- maintained-develop
|
||||
- maintained-stable
|
||||
- 'fix/*'
|
||||
- 'maintenance/*'
|
||||
pull_request:
|
||||
branches:
|
||||
- maintained-develop
|
||||
- maintained-stable
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validar Codigo e Testes
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout do Repositorio
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Configurar Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Instalar Dependencias de Sistema
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends libjpeg-dev libwebp-dev poppler-utils ffmpeg
|
||||
|
||||
- name: Verificar Integridade das Dependencias
|
||||
run: go mod verify
|
||||
|
||||
- name: Compilar Codigo
|
||||
run: go build ./...
|
||||
|
||||
- name: Analise Estatica (Go Vet)
|
||||
run: go vet ./...
|
||||
|
||||
- name: Executar Testes Unitarios
|
||||
run: go test -v ./...
|
||||
@@ -0,0 +1,133 @@
|
||||
name: Docker - Build e Publicacao
|
||||
|
||||
# Publicacao no registry do Gitea (git.jf.eng.br/jfeng/evogo):
|
||||
# - push de tag v<versao> (ex: v0.7.2-evogo.1) = release aprovado -> publica
|
||||
# git.jf.eng.br/jfeng/evogo:<versao> (tag semantica)
|
||||
# git.jf.eng.br/jfeng/evogo:<versao>-<sha7> (tag imutavel do commit)
|
||||
# - workflow_dispatch com publish_image=true -> idem, versao = target_tag ou VERSION
|
||||
# - push em maintained-stable -> apenas build + teste + scan (nao publica)
|
||||
# :latest so e atualizada com promote_latest=true (manual), nunca automaticamente.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- maintained-stable
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
publish_image:
|
||||
description: 'Publicar imagem no registry apos build e testes (requer aprovacao)'
|
||||
type: boolean
|
||||
default: false
|
||||
required: true
|
||||
target_tag:
|
||||
description: 'Tag semantica para publicacao (ex: 0.7.2-evogo.1). Vazio = arquivo VERSION'
|
||||
type: string
|
||||
default: ''
|
||||
required: false
|
||||
promote_latest:
|
||||
description: 'Tambem atualizar :latest (somente versoes aprovadas em maintained-stable)'
|
||||
type: boolean
|
||||
default: false
|
||||
required: false
|
||||
|
||||
env:
|
||||
REGISTRY: git.jf.eng.br
|
||||
IMAGE: git.jf.eng.br/jfeng/evogo
|
||||
|
||||
jobs:
|
||||
build_docker:
|
||||
name: Build, Scan e Publicacao
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout do Repositorio
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Obter Versao e Commit SHA
|
||||
id: meta
|
||||
run: |
|
||||
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||
VERSION="${{ github.ref_name }}"
|
||||
VERSION="${VERSION#v}"
|
||||
PUBLISH=true
|
||||
else
|
||||
VERSION="${{ github.event.inputs.target_tag }}"
|
||||
[ -n "$VERSION" ] || VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
|
||||
PUBLISH="${{ github.event.inputs.publish_image == 'true' }}"
|
||||
fi
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "commit_sha=${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "publish=${PUBLISH}" >> "$GITHUB_OUTPUT"
|
||||
echo "Versao: ${VERSION} | Commit: ${COMMIT_SHA} | Publicar: ${PUBLISH}"
|
||||
|
||||
- name: Construir Imagem Docker Local
|
||||
run: |
|
||||
docker build \
|
||||
--build-arg VERSION=${{ steps.meta.outputs.image_tag }} \
|
||||
-t evogo:ci-${{ steps.meta.outputs.commit_sha }} .
|
||||
|
||||
- name: Testar Inicializacao do Container
|
||||
run: |
|
||||
# O binario precisa subir e falhar apenas por falta de banco/config,
|
||||
# nunca por erro de link (CGO/libwebp/libjpeg) ou arquivo ausente.
|
||||
set +e
|
||||
timeout 20 docker run --rm evogo:ci-${{ steps.meta.outputs.commit_sha }} > /tmp/run.log 2>&1
|
||||
set -e
|
||||
tail -20 /tmp/run.log
|
||||
if grep -qiE "error while loading shared libraries|exec format error|exec /app/server" /tmp/run.log; then
|
||||
echo "Falha ao iniciar o binario dentro da imagem"; exit 1
|
||||
fi
|
||||
docker run --rm --entrypoint sh evogo:ci-${{ steps.meta.outputs.commit_sha }} -c 'test -x /app/server && test -d /app/manager/dist && cat /app/VERSION'
|
||||
|
||||
- name: Verificar Vulnerabilidades (Trivy, nao bloqueante)
|
||||
continue-on-error: true
|
||||
run: |
|
||||
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
|
||||
image --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
|
||||
evogo:ci-${{ steps.meta.outputs.commit_sha }}
|
||||
|
||||
- name: Login no Gitea Package Registry
|
||||
if: steps.meta.outputs.publish == 'true'
|
||||
run: |
|
||||
USER="${{ secrets.REGISTRY_USER }}"
|
||||
[ -n "$USER" ] || USER="${{ github.actor }}"
|
||||
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
|
||||
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
|
||||
# O registry ja estourou timeout pontualmente (run 482); tenta de novo antes de falhar.
|
||||
for n in 1 2 3 4 5; do
|
||||
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
|
||||
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
|
||||
sleep $((n*15))
|
||||
done
|
||||
exit 1
|
||||
|
||||
- name: Publicar Imagens no Registry
|
||||
if: steps.meta.outputs.publish == 'true'
|
||||
run: |
|
||||
push() {
|
||||
for n in 1 2 3 4 5; do
|
||||
docker push "$1" && return 0
|
||||
echo "Push de $1 falhou (tentativa $n/5); nova tentativa em $((n*15))s"
|
||||
sleep $((n*15))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
SRC=evogo:ci-${{ steps.meta.outputs.commit_sha }}
|
||||
for TAG in "${{ steps.meta.outputs.image_tag }}" "${{ steps.meta.outputs.version }}"; do
|
||||
docker tag "$SRC" "$IMAGE:$TAG"
|
||||
push "$IMAGE:$TAG"
|
||||
echo "Publicado: $IMAGE:$TAG"
|
||||
done
|
||||
if [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
|
||||
docker tag "$SRC" "$IMAGE:latest"
|
||||
push "$IMAGE:latest"
|
||||
echo "Publicado: $IMAGE:latest"
|
||||
fi
|
||||
|
||||
- name: Limpeza
|
||||
if: always()
|
||||
run: docker image rm -f evogo:ci-${{ steps.meta.outputs.commit_sha }} >/dev/null 2>&1 || true
|
||||
@@ -0,0 +1,71 @@
|
||||
name: Docker - Promover latest
|
||||
|
||||
# :latest = ultimo release v* contido em maintained-stable.
|
||||
# Nao recompila: baixa a imagem imutavel <versao>-<sha7> ja publicada pelo
|
||||
# docker-build.yml para aquela tag e apenas a re-etiqueta, preservando o digest.
|
||||
# So roda quando maintained-stable avanca (promocao aprovada) ou manualmente.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- maintained-stable
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: promote-latest
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
REGISTRY: git.jf.eng.br
|
||||
IMAGE: git.jf.eng.br/jfeng/evogo
|
||||
|
||||
jobs:
|
||||
promote:
|
||||
name: Promover release para latest
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout do Repositorio
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Identificar release
|
||||
id: rel
|
||||
run: |
|
||||
git fetch --tags --force
|
||||
TAG=$(git describe --tags --abbrev=0 --match 'v*' HEAD)
|
||||
SHA7=$(git rev-list -n1 "$TAG" | cut -c1-7)
|
||||
VERSION="${TAG#v}"
|
||||
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||
echo "source=${IMAGE}:${VERSION}-${SHA7}" >> "$GITHUB_OUTPUT"
|
||||
echo "Release: ${TAG} -> ${IMAGE}:${VERSION}-${SHA7}"
|
||||
|
||||
- name: Login no Gitea Package Registry
|
||||
run: |
|
||||
USER="${{ secrets.REGISTRY_USER }}"
|
||||
[ -n "$USER" ] || USER="${{ github.actor }}"
|
||||
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
|
||||
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
|
||||
for n in 1 2 3 4 5; do
|
||||
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
|
||||
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
|
||||
sleep $((n*15))
|
||||
done
|
||||
exit 1
|
||||
|
||||
- name: Re-etiquetar como latest
|
||||
run: |
|
||||
retry() {
|
||||
for n in 1 2 3 4 5; do
|
||||
"$@" && return 0
|
||||
echo "'$*' falhou (tentativa $n/5); nova tentativa em $((n*15))s"
|
||||
sleep $((n*15))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
SRC="${{ steps.rel.outputs.source }}"
|
||||
retry docker pull "$SRC"
|
||||
docker tag "$SRC" "$IMAGE:latest"
|
||||
retry docker push "$IMAGE:latest"
|
||||
echo "Publicado: $IMAGE:latest (mesmo digest de $SRC)"
|
||||
@@ -0,0 +1,53 @@
|
||||
name: Sincronizacao Diaria com o Upstream
|
||||
|
||||
# Incorpora o upstream oficial (evolution-foundation/evolution-go) sem perder as
|
||||
# correcoes EvoGO: o merge e feito numa branch maintenance/sync-upstream-<sha>
|
||||
# criada a partir de maintained-develop, testado e enviado como PR.
|
||||
# Conflitos viram Issue. maintained-stable nunca e tocada.
|
||||
# Ver scripts/upstream-sync.sh e docs/maintenance/UPSTREAM_SYNC.md.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Diariamente as 04:00 UTC (01:00 BRT)
|
||||
- cron: '0 4 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: upstream-sync
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Incorporar upstream e verificar whatsmeow
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout do Repositorio
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: maintained-develop
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: Configurar Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Instalar Dependencias de Sistema
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq --no-install-recommends libjpeg-dev libwebp-dev
|
||||
|
||||
- name: Sincronizar com o upstream
|
||||
env:
|
||||
GITEA_URL: ${{ github.server_url }}
|
||||
REPO: ${{ github.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
# Defina a variavel de repositorio AUTO_MERGE_UPSTREAM=true para mesclar
|
||||
# automaticamente em maintained-develop quando build e testes passarem.
|
||||
AUTO_MERGE: ${{ vars.AUTO_MERGE_UPSTREAM || 'false' }}
|
||||
run: |
|
||||
git config user.name "EvoGO Upstream Bot"
|
||||
git config user.email "[email protected]"
|
||||
bash scripts/upstream-sync.sh
|
||||
@@ -0,0 +1,89 @@
|
||||
name: Bug Report
|
||||
description: Create a report to help us improve.
|
||||
labels:
|
||||
- bug
|
||||
- en
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Welcome!
|
||||
description: |
|
||||
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/553196219989)
|
||||
<br/>
|
||||
|
||||
**DO NOT OPEN AN ISSUE FOR GENERAL SUPPORT QUESTIONS.**
|
||||
|
||||
options:
|
||||
- label: Yes, I have searched for similar issues on [GitHub](https://github.com/evolution-foundation/evolution-go/issues) and found none.
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What did you do?
|
||||
description: |
|
||||
- Respect the issue template as much as possible.
|
||||
- The title should be short and descriptive.
|
||||
- Explain the conditions that led you to report this issue.
|
||||
- Be clear and concise.
|
||||
placeholder: Describe the problem you encountered in detail.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What did you expect?
|
||||
placeholder: Describe what you expected to happen.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What did you observe instead of what you expected?
|
||||
placeholder: Explain what actually happens when you follow the steps above.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Screenshots/Videos
|
||||
placeholder: If possible, add screenshots or videos that illustrate the problem.
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Which version are you using?
|
||||
description: Check the VERSION file or the startup log.
|
||||
placeholder: e.g. 0.6.1
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: select
|
||||
attributes:
|
||||
label: What is your environment?
|
||||
options:
|
||||
- Linux
|
||||
- Docker
|
||||
- Mac
|
||||
- Windows
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: If applicable, paste the log output
|
||||
description: Please attach any logs related to the issue.
|
||||
placeholder: Paste the application log here.
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional Notes
|
||||
description: Include any other information you think might be useful.
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,62 @@
|
||||
name: Feature Request
|
||||
description: Suggest ideas for the project.
|
||||
labels:
|
||||
- enhancement
|
||||
- en
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Welcome!
|
||||
description: '**DO NOT OPEN FOR GENERAL SUPPORT QUESTIONS.**'
|
||||
options:
|
||||
- label: Yes, I have searched for similar requests on [GitHub](https://github.com/evolution-foundation/evolution-go/issues) and found none.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: What type of feature?
|
||||
options:
|
||||
- Integration
|
||||
- Functionality
|
||||
- Endpoint
|
||||
- Performance
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What is the motivation for the request?
|
||||
description: |
|
||||
What problem does the feature seek to solve?
|
||||
Clearly describe the functionality you want implemented.
|
||||
placeholder: Detailed description
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Usage Examples
|
||||
description: Provide specific examples of how this functionality could be used.
|
||||
placeholder: text - image - video - flowcharts
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: How should the feature be developed?
|
||||
description: |
|
||||
Should it be inserted directly into the code?
|
||||
If you have implementation ideas, please share them here.
|
||||
placeholder: Insert feature ideas here
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional Notes
|
||||
description: Any other information relevant to your request.
|
||||
placeholder: Insert your observations here.
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,89 @@
|
||||
name: Relatório de bug
|
||||
description: Crie um relatório para nos ajudar a melhorar.
|
||||
labels:
|
||||
- bug
|
||||
- pt-br
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: termos
|
||||
attributes:
|
||||
label: Bem-vindo!
|
||||
description: |
|
||||
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/553196219989)
|
||||
<br/>
|
||||
|
||||
**NÃO ABRA UM PROBLEMA PARA PERGUNTAS GERAIS DE SUPORTE.**
|
||||
|
||||
options:
|
||||
- label: Sim, pesquisei problemas semelhantes no [GitHub](https://github.com/evolution-foundation/evolution-go/issues) e não encontrei nenhum.
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: O que você fez?
|
||||
description: |
|
||||
- Respeite o modelo de problema tanto quanto possível.
|
||||
- O título deve ser curto e descritivo.
|
||||
- Explique as condições que o levaram a reportar este problema.
|
||||
- Seja claro e conciso.
|
||||
placeholder: Descreva detalhadamente o problema que você encontrou.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: O que você esperava?
|
||||
placeholder: Descreva o que você esperava que acontecesse.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: O que você observou ao invés do que esperava?
|
||||
placeholder: Explique o que realmente acontece quando você segue os passos acima.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Capturas de Tela/Vídeos
|
||||
placeholder: Se possível, adicione capturas de tela ou vídeos que ilustrem o problema.
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Qual versão você está usando?
|
||||
description: Verifique o arquivo VERSION ou o log de inicialização.
|
||||
placeholder: ex. 0.6.1
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: select
|
||||
attributes:
|
||||
label: Qual é o seu ambiente?
|
||||
options:
|
||||
- Linux
|
||||
- Docker
|
||||
- Mac
|
||||
- Windows
|
||||
- Outro
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Se aplicável, cole a saída do log
|
||||
description: Por favor, anexe os logs que possam estar relacionados ao problema.
|
||||
placeholder: Cole aqui o log da aplicação.
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Notas Adicionais
|
||||
description: Inclua qualquer outra informação que possa ser útil.
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,62 @@
|
||||
name: Solicitação de recursos
|
||||
description: Sugira ideias para o projeto.
|
||||
labels:
|
||||
- enhancement
|
||||
- pt-br
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: termos
|
||||
attributes:
|
||||
label: Bem-vindo!
|
||||
description: '**NÃO ABRA PARA PERGUNTAS GERAIS DE SUPORTE.**'
|
||||
options:
|
||||
- label: Sim, pesquisei solicitações semelhantes no [GitHub](https://github.com/evolution-foundation/evolution-go/issues) e não encontrei nenhum.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Qual tipo de recurso?
|
||||
options:
|
||||
- Integração
|
||||
- Funcionalidade
|
||||
- Endpoint
|
||||
- Performance
|
||||
- Outro
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Qual a motivação para a solicitação?
|
||||
description: |
|
||||
Qual problema o recurso busca resolver?
|
||||
Descreva claramente a funcionalidade que você deseja que seja implementada.
|
||||
placeholder: Descrição detalhada
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Exemplos de Uso
|
||||
description: Forneça exemplos específicos de como essa funcionalidade poderia ser utilizada.
|
||||
placeholder: texto - imagem - video - fluxogramas
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Como o recurso deve ser desenvolvido?
|
||||
description: |
|
||||
Deve ser inserido diretamente no código?
|
||||
Se você tem ideias de implementação, por favor compartilhe aqui.
|
||||
placeholder: Insira ideias para o recurso
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Notas Adicionais
|
||||
description: Qualquer outra informação relevante para a sua solicitação.
|
||||
placeholder: Insira aqui as suas observações.
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,29 @@
|
||||
## Description
|
||||
<!-- Describe your changes in detail -->
|
||||
|
||||
## Related Issue
|
||||
<!-- Link to the issue this PR addresses -->
|
||||
Closes #(issue_number)
|
||||
|
||||
## Type of Change
|
||||
- [ ] Bug fix (non-breaking change which fixes an issue)
|
||||
- [ ] New feature (non-breaking change which adds functionality)
|
||||
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
|
||||
- [ ] Documentation update
|
||||
- [ ] Refactoring (no functional changes)
|
||||
- [ ] Performance improvement
|
||||
|
||||
## Testing
|
||||
- [ ] Manual testing completed
|
||||
- [ ] Functionality verified in development environment
|
||||
- [ ] No breaking changes introduced
|
||||
|
||||
## Screenshots (if applicable)
|
||||
|
||||
## Checklist
|
||||
- [ ] My code follows the project's style guidelines
|
||||
- [ ] I have performed a self-review of my code
|
||||
- [ ] I have tested my changes thoroughly
|
||||
- [ ] Any dependent changes have been merged and published
|
||||
|
||||
## Additional Notes
|
||||
@@ -0,0 +1,61 @@
|
||||
name: Build and Publish Docker Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Read version
|
||||
id: version
|
||||
run: echo "version=$(cat VERSION 2>/dev/null || echo '0.0.0')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: evoapicloud/evolution-go
|
||||
tags: |
|
||||
type=raw,value=${{ steps.version.outputs.version }}
|
||||
type=raw,value=latest,enable=${{ !contains(steps.version.outputs.version, '-beta') }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
VERSION=${{ steps.version.outputs.version }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
@@ -0,0 +1,9 @@
|
||||
.env
|
||||
logs/*
|
||||
build/
|
||||
*.prof
|
||||
coverage.*
|
||||
.air.toml
|
||||
.idea/
|
||||
.vscode/
|
||||
.DS_Store
|
||||
+415
@@ -0,0 +1,415 @@
|
||||
# Evolution GO - Changelog
|
||||
|
||||
## Não lançado
|
||||
|
||||
### 🔧 Correções
|
||||
- **whatsmeow atualizado para 2026-11-02** — a versão fixada na 0.7.2
|
||||
(commit `b572e5bcb92b`, de 30/06/2026) ficou 125 dias atrás do upstream. O
|
||||
WhatsApp subiu a versão mínima de cliente nesse intervalo e passou a recusar a
|
||||
conexão com **405 client outdated**, impedindo pareamento e reconexão das
|
||||
instâncias. Agora em `v0.0.0-20261102152715-54038813c47f`.
|
||||
- **Go 1.26** — o whatsmeow novo exige `go >= 1.26.0`; o `Dockerfile` passou a
|
||||
usar `golang:1.26.10-alpine` no estágio de build.
|
||||
- **Ajustes de API do whatsmeow** — `UpdateBlocklist` e `GetBlocklist` agora
|
||||
recebem um `dhash`; `SetStatusMessage` passou a receber `types.SetStatusInput`
|
||||
(novo endpoint mex). O formato de resposta de bloqueio mudou de
|
||||
`Modifications` para `Items` (com `LID`/`PN`/`Active`) — a documentação foi
|
||||
atualizada, mas integrações que leem `Modifications` precisam de ajuste.
|
||||
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe
|
||||
de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
|
||||
ao abrir o container; testado com banco SQLite v14 existente.
|
||||
- **Build quebrado após o fix 405** — `whatsmeow.go` referenciava `waProto`
|
||||
(pacote inexistente); `ClientPayload_UserAgent_AppVersion` vem de
|
||||
`go.mau.fi/whatsmeow/proto/waWa6`.
|
||||
|
||||
- **Nono dígito (BR)** — envios para celulares brasileiros consultam no
|
||||
WhatsApp as duas variantes (com e sem o 9) e usam a que está registrada.
|
||||
Contas antigas sem o 9 (ex.: `554291389691`) passam a receber mesmo quando o
|
||||
sistema envia `5542991389691`, e vice-versa (upstream issue #214 / PR #208).
|
||||
- **LID enviado como número** — quando o `number` não existe como telefone mas
|
||||
é o LID de um contato já conhecido pela instância (ex.: `255284433936406`),
|
||||
o envio vai direto para `255284433936406@lid` em vez de falhar com
|
||||
`no LID found for [email protected]`.
|
||||
|
||||
### 🆕 Novidades
|
||||
- `GET /server/ok` passa a informar a versão em execução
|
||||
(`{"status":"ok","version":"0.7.2-evogo.3-<sha7>"}`).
|
||||
|
||||
### 🛡️ Estabilidade (correções da comunidade incorporadas pelo EvoGO)
|
||||
- **Crash `concurrent map writes`** — `clientPointer`, `myClientPointer` e
|
||||
`killChannel` agora são `safemap.Map` com RWMutex (upstream PR #196, issue #203).
|
||||
- **Vazamento de conexões Postgres** — um único `sqlstore.Container`
|
||||
compartilhado em vez de um novo pool a cada `StartClient`/reconexão
|
||||
(upstream PR #206, issues #165/#175/#215).
|
||||
- **Loop de reconexão/QR infinito** — backoff progressivo após 5 reinícios em
|
||||
15 min (upstream PR #197); cliente sem dispositivo pareado não é reiniciado
|
||||
(upstream PR #240); `StartClient` duplicado é ignorado (upstream PR #239).
|
||||
- **Panics que derrubavam todas as instâncias** — `ReconnectClient` serializado
|
||||
por instância com checagem de nil (issue #188); envio em canal fechado ao
|
||||
excluir instância durante o QR (issue #222); evento `Archive` (upstream PR #195).
|
||||
- **Webhooks paravam após desconectar pela API** — `Disconnect` não apaga mais
|
||||
as inscrições de eventos (upstream PR #187).
|
||||
- **`/user/info` e `/user/avatar` travando 75 s** — `ParseJID` remove o `+` de
|
||||
JIDs de usuário (upstream PR #224, issue #223).
|
||||
- **WebSocket** — todos os assinantes de uma instância recebem eventos e as
|
||||
escritas são serializadas por conexão (upstream PR #181).
|
||||
- **NATS** — sem `NATS_URL` a conexão não é tentada (upstream PR #143).
|
||||
|
||||
### ⚙️ Manutenção EvoGO
|
||||
- Sincronização diária com o upstream via Gitea Actions: merge em
|
||||
`maintenance/sync-upstream-<sha>` a partir de `maintained-develop`, build/testes
|
||||
e PR automático; conflitos viram Issue; aviso de whatsmeow desatualizado.
|
||||
- Publicação da imagem em `git.jf.eng.br/jfeng/evogo` por tag `v*`, com tag
|
||||
imutável `<versão>-<sha7>` e scan Trivy.
|
||||
- Login, pull e push no registry com até 5 tentativas — um timeout pontual do
|
||||
endpoint de token derrubou a publicação da `v0.7.2-evogo.2` (run 482).
|
||||
|
||||
## v0.7.2
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.7.2`
|
||||
|
||||
### 🆕 New Features
|
||||
- **Passkey (WebAuthn) pairing** — support for linking accounts that the WhatsApp
|
||||
server locks behind a **passkey** (the *Shortcake* / CRSC flow). When the
|
||||
server demands a passkey, whatsmeow's `PairPasskeyRequest` is surfaced through a
|
||||
new ceremony flow: the backend mints a short-lived ceremony token, and a bundled
|
||||
browser extension (`passkey-helper`) runs the WebAuthn assertion on the
|
||||
`web.whatsapp.com` origin and posts it back. Three public endpoints drive it:
|
||||
`GET /passkey-ceremony/{token}`, `POST .../response`, `POST .../confirm`. The
|
||||
manager detects the passkey stage and shows an "Abrir WhatsApp Web" button.
|
||||
Confirmation is always manual (never auto-confirm on `SkipHandoffUX`).
|
||||
Configure the public API base via **`PASSKEY_PUBLIC_URL`**. Full guide:
|
||||
`docs/wiki/guias-api/passkey-pairing.md`. Note: there is no headless bypass —
|
||||
the ceremony requires the account owner's real authenticator; the extension is
|
||||
web-only.
|
||||
- **Headless license auto-activation** — set `EVOLUTION_OPERATOR_EMAIL` to the
|
||||
email used in your first manual license registration; on startup the service
|
||||
silently calls `/v1/register/auto` and skips the browser flow (falls back to the
|
||||
manual flow if the email isn't registered yet).
|
||||
- **Button message media support** — additional media handling for interactive
|
||||
button messages.
|
||||
|
||||
### 🔧 Improvements / CI
|
||||
- **Dropped the whatsmeow fork — now uses official `go.mau.fi/whatsmeow`.** The
|
||||
project previously vendored a fork (`whatsmeow-lib` submodule) to carry a
|
||||
PostgreSQL pool patch; upstream rejected that patch in favor of `NewWithDB`
|
||||
(app-side config). Removing the fork also pulled in upstream's native passkey
|
||||
support. Pinned to the commit that adds passkeys
|
||||
(`v0.0.0-20260630180629-b572e5bcb92b`). The `sync-releases` workflow no longer
|
||||
re-adds the submodule.
|
||||
- **QR pairing consumes `events.QR` directly** instead of `GetQRChannel`. The QR
|
||||
channel auto-confirms passkey on `SkipHandoffUX` and disconnects the socket when
|
||||
codes run out — both break an in-flight passkey ceremony. Connecting without it
|
||||
keeps the socket alive for as long as pairing (QR or passkey) needs. QR rotation
|
||||
now pauses while a passkey ceremony is active.
|
||||
- **Public sync fixes** — the release workflow drops the obsolete whatsmeow-lib
|
||||
step, targets `evolution-foundation/*`, and now ships the `passkey-helper`
|
||||
extension to the public repo.
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
- **`POST /instance/pair` returned an empty `PairingCode`** — the handler
|
||||
swallowed `PairPhone` errors and returned HTTP 200 with `PairingCode: ""`, and
|
||||
the client wasn't connected/awaiting-auth before `PairPhone`. Now starts the
|
||||
instance, waits for the websocket, and surfaces real errors (#21).
|
||||
- **`GET /instance/status` returned 400 after a manual disconnect** — now returns
|
||||
200 with the disconnected status instead of erroring until a container restart
|
||||
(#20).
|
||||
|
||||
### 🏷️ Org rename
|
||||
- Repository references updated from **EvolutionAPI** to **evolution-foundation**
|
||||
(module path, imports, GitHub URLs, submodule URLs).
|
||||
|
||||
## v0.7.1
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.7.1`
|
||||
|
||||
### 🆕 New Features
|
||||
- **Test-send modal in Manager** — new modal in the embedded manager UI to test message sending directly from the panel, covering text, media and interactive message types. Useful for validating an instance right after pairing without leaving the manager.
|
||||
|
||||
### 🔧 Improvements / CI
|
||||
- **whatsmeow-lib SHA now pinned in the public sync** — the `sync-releases` workflow previously re-cloned whatsmeow `main` on every run, so the SHA listed in the CHANGELOG could drift from what the public repos actually built against. The workflow now captures the SHA from the dev submodule and checks out that exact commit in the target, restoring release reproducibility.
|
||||
- **Repository cleanup** — dropped tracked binaries (`evolution-go`, `build/server`), IDE config (`.idea/`) and scratch files (`DIFF-COMPLETO.txt`, `API-INTERACTIVE-DOCS.txt`, `carousel-sender.html`). Expanded `.gitignore` to prevent reincidence.
|
||||
|
||||
### 📝 Docs
|
||||
- **Postman collection** — added `Set Proxy` request and multipart hints on `/send/media`; collection file renamed from `Evolution GO.postman_collection (2).json` to `Evolution GO.postman_collection.json`.
|
||||
- **Interactive messages docs** — additional examples and corrections.
|
||||
|
||||
## 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/evolution-foundation/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
|
||||
- **Group invite info endpoint** — `GET /group/invite-info` to get group details from invite link
|
||||
- **Enhanced media sending** — GIF playback, video stickers, and transparent sticker support
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
- **Admin revoke** — Allow deleting messages from others in groups (admin revoke)
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Version management** — Reads version from `VERSION` file with ldflags fallback
|
||||
- **CORS global middleware** — Applied before all routes
|
||||
- **Makefile compatibility** — Fixed `$(shell)` syntax for GNU Make 3.81 (macOS default)
|
||||
- **CI/CD cleanup** — Removed `develop` branch trigger and `homolog` tag from Docker workflow
|
||||
- **README updated** — New links, documentation, and hosting info
|
||||
|
||||
## v0.6.0
|
||||
|
||||
### 🆕 New Features
|
||||
- **Version from VERSION file** — Reads version from `VERSION` file at startup instead of hardcoded value
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Makefile compatibility** — Fixed `$(shell)` syntax for GNU Make 3.81 (macOS default)
|
||||
|
||||
## v0.5.4
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Update whatsmeow lib**
|
||||
|
||||
## v0.5.3
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.5.3`
|
||||
|
||||
### 🔧 Improvements
|
||||
|
||||
- **Update context handling in service methods**
|
||||
- Refactored multiple service methods across various packages to include `context.Background()` as the first argument in client calls. This change ensures that all client interactions are properly context-aware, allowing for better cancellation and timeout management.
|
||||
- Updated methods in `call_service.go`, `community_service.go`, `group_service.go`, `message_service.go`, `newsletter_service.go`, `send_service.go`, `user_service.go`, and `whatsmeow.go` to enhance consistency and reliability in handling requests.
|
||||
- This adjustment improves the overall robustness of the API by ensuring that all client calls can leverage context for better control over execution flow and resource management.
|
||||
|
||||
## v0.5.2
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.5.2`
|
||||
|
||||
### 🆕 New Features
|
||||
- **SetProxy Endpoint**: New endpoint `POST /instance/proxy/{instanceId}` to configure proxy for instances
|
||||
- Support for proxy with/without authentication
|
||||
- Validation of required fields (host, port)
|
||||
- Automatic cache update via reconnection
|
||||
- Integrated Swagger documentation
|
||||
|
||||
### 🔧 Improvements
|
||||
- **CheckUser Fallback Logic**: Implemented intelligent fallback logic
|
||||
- If `formatJid=true` returns `IsInWhatsapp=false`, automatically retries with `formatJid=false`
|
||||
- Significant improvement in valid user detection
|
||||
- Added `RemoteJID` field to use WhatsApp-validated JID
|
||||
- **LID/WhatsApp JID Swap**: Automatic handling of special cases
|
||||
- When `Sender` comes as `@lid` and `SenderAlt` comes as `@s.whatsapp.net`
|
||||
- Automatic inversion: `Sender` and `Chat` receive `@s.whatsapp.net`, `SenderAlt` receives `@lid`
|
||||
- Detailed logs for tracking swaps
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
- **SendMessage**: Standardization of WhatsApp-validated `remoteJID` usage
|
||||
- **User Validation**: Improvement in phone number validation and formatting
|
||||
|
||||
---
|
||||
|
||||
## v0.5.1
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.5.1`
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Instance Deletion**: Enhance instance deletion and media storage path resolution
|
||||
- **Media Storage**: Improvements in media storage and path resolution
|
||||
|
||||
---
|
||||
|
||||
## v0.5.0
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.5.0`
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Media Storage**: Enhance media storage and logging in Whatsmeow event handling
|
||||
- **Retry Logic**: Implement retry logic for client connection and message sending
|
||||
- **Media Handling**: Enhance media handling in event processing
|
||||
|
||||
---
|
||||
|
||||
## v0.4.9
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.4.9`
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Connection Handling**: Add instance update test scenarios and improve connection handling
|
||||
- **FormatJid Field**: Update FormatJid field to pointer type for better handling in message structures
|
||||
- **Dependencies**: Update dependencies and fix presence handling in Whatsmeow integration
|
||||
|
||||
---
|
||||
|
||||
## v0.4.8
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.4.8`
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Audio Duration**: Improve audio duration parsing in convertAudioToOpusWithDuration function
|
||||
|
||||
---
|
||||
|
||||
## v0.4.7
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.4.7`
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Phone Number Formatting**: Improve phone number formatting and validation in user service
|
||||
- **Brazilian/Portuguese Numbers**: Update Brazilian and Portuguese number formatting in utils
|
||||
|
||||
### 🆕 New Features
|
||||
- **Media Handling**: Enhance media handling in event processing
|
||||
|
||||
---
|
||||
|
||||
## v0.4.6
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.4.6`
|
||||
|
||||
### 🆕 New Features
|
||||
- **User Existence Check**: Add user existence check configuration and JID validation middleware
|
||||
|
||||
---
|
||||
|
||||
## v0.4.5
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.4.5`
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Dependencies**: Update dependencies and enhance audio conversion functionality
|
||||
|
||||
---
|
||||
|
||||
## v0.4.4
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.4.4`
|
||||
|
||||
### 🆕 New Features
|
||||
- **CLAUDE.md**: Add CLAUDE.md for project documentation and enhance RabbitMQ connection handling
|
||||
|
||||
---
|
||||
|
||||
## v0.4.3
|
||||
|
||||
**Docker:** `evoapicloud/evolution-go:0.4.3`
|
||||
|
||||
### 🔧 Improvements
|
||||
- **PostgreSQL Connection**: Fix in PostgreSQL connection configuration for session auth
|
||||
- Controlled configuration of pool, idle, etc.
|
||||
- Adjustment on top of whatsmeow lib
|
||||
- **User Endpoints**: Fix in 'User Info' and 'Check User' endpoints
|
||||
- Now return with contact's LID information
|
||||
|
||||
---
|
||||
|
||||
## v0.3.0
|
||||
|
||||
### 🆕 New Features
|
||||
- **Own Message Reactions**: Additional 'fromMe' parameter using Chat id
|
||||
- **CreatedAt Field**: CreatedAt field added to instances table
|
||||
|
||||
---
|
||||
|
||||
## v0.2.0
|
||||
|
||||
### 🆕 New Features
|
||||
- **Advanced Settings**: Advanced configurations in instance creation
|
||||
- `alwaysOnline` (still to be implemented)
|
||||
- `rejectCall` - Automatically reject calls
|
||||
- `msgRejectCall` - Call rejection message
|
||||
- `readMessages` - Automatically mark messages as read
|
||||
- `ignoreGroups` - Ignore group messages
|
||||
- `ignoreStatus` - Ignore status messages
|
||||
- **Advanced Settings Routes**: New routes for get and update of advanced settings
|
||||
- **QR Code Control**: `QRCODE_MAX_COUNT` variable to control how many QR codes to generate before timeout
|
||||
- **AMQP Events**: `AMQP_SPECIFIC_EVENTS` variable to individually select which events to receive in RabbitMQ
|
||||
|
||||
### 🔧 Improvements
|
||||
- **Reconnect Endpoint**: Fix in reconnect endpoint
|
||||
- **Sender Info**: `Sender` and `SenderAlt` no longer come with session id, only the id
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
- **QR Code Generation**: Fix to not generate QR code automatically after disconnection or logout
|
||||
|
||||
---
|
||||
|
||||
## v0.1.0
|
||||
|
||||
### 🆕 Initial Features
|
||||
- Base implementation of Evolution API in Go
|
||||
- WhatsApp integration via whatsmeow
|
||||
- Instance system
|
||||
- Basic message sending endpoints
|
||||
- Webhook support
|
||||
- RabbitMQ and NATS integration
|
||||
- Authentication system
|
||||
- Swagger documentation
|
||||
|
||||
---
|
||||
|
||||
## 📋 Migration Notes
|
||||
|
||||
### v0.5.2
|
||||
- The new `SetProxy` endpoint requires admin permissions (`AuthAdmin`)
|
||||
- The `CheckUser` fallback logic is automatic and transparent
|
||||
- LID/WhatsApp JID handling is automatic
|
||||
|
||||
### v0.4.3
|
||||
- Check PostgreSQL connection settings if using postgres auth
|
||||
|
||||
### v0.2.0
|
||||
- Review advanced settings configurations if necessary
|
||||
- Configure `QRCODE_MAX_COUNT` if you want to limit QR codes
|
||||
- Configure `AMQP_SPECIFIC_EVENTS` for specific RabbitMQ events
|
||||
|
||||
---
|
||||
|
||||
## 🔗 Useful Links
|
||||
|
||||
- **Docker Hub**: `evoapicloud/evolution-go`
|
||||
- **Documentation**: Swagger available at `/swagger/`
|
||||
- **GitHub**: [Evolution API Go](https://github.com/evolution-foundation/evolution-go)
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
To contribute to the project:
|
||||
1. Fork the repository
|
||||
2. Create a branch for your feature
|
||||
3. Commit your changes
|
||||
4. Open a Pull Request
|
||||
|
||||
---
|
||||
|
||||
*Last updated: October 2025*
|
||||
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
# 🚀 Guia Rápido de Comandos
|
||||
|
||||
Comandos mais usados no dia a dia de desenvolvimento do Evolution GO.
|
||||
|
||||
## 📋 Comandos Essenciais
|
||||
|
||||
### Desenvolvimento
|
||||
|
||||
```bash
|
||||
# Ver todos os comandos disponíveis
|
||||
make help
|
||||
|
||||
# Rodar em modo desenvolvimento
|
||||
make dev
|
||||
|
||||
# Rodar com hot reload (recarrega automaticamente ao salvar)
|
||||
make watch
|
||||
```
|
||||
|
||||
### Build e Instalação
|
||||
|
||||
```bash
|
||||
# Compilar a aplicação
|
||||
make build
|
||||
|
||||
# Compilar para todas as plataformas (Linux, Windows, macOS)
|
||||
make build-all
|
||||
|
||||
# Instalar no GOPATH
|
||||
make install
|
||||
```
|
||||
|
||||
### Testes
|
||||
|
||||
```bash
|
||||
# Rodar todos os testes
|
||||
make test
|
||||
|
||||
# Rodar testes com relatório de cobertura
|
||||
make test-coverage
|
||||
|
||||
# Rodar testes com verificação de race conditions
|
||||
make test-race
|
||||
|
||||
# Rodar benchmarks
|
||||
make bench
|
||||
```
|
||||
|
||||
### Qualidade de Código
|
||||
|
||||
```bash
|
||||
# Formatar código
|
||||
make fmt
|
||||
|
||||
# Executar linter
|
||||
make lint
|
||||
|
||||
# Executar go vet
|
||||
make vet
|
||||
|
||||
# Executar todas as verificações (fmt + vet + lint + test)
|
||||
make check
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
# Build da imagem Docker
|
||||
make docker-build
|
||||
|
||||
# Rodar container Docker
|
||||
make docker-run
|
||||
|
||||
# Iniciar todos os serviços com docker-compose
|
||||
make docker-compose-up
|
||||
|
||||
# Parar todos os serviços
|
||||
make docker-compose-down
|
||||
|
||||
# Ver logs do docker-compose
|
||||
make docker-compose-logs
|
||||
```
|
||||
|
||||
### Banco de Dados
|
||||
|
||||
```bash
|
||||
# Executar migrations
|
||||
make migrate-up
|
||||
|
||||
# Reverter migrations
|
||||
make migrate-down
|
||||
```
|
||||
|
||||
### Documentação
|
||||
|
||||
```bash
|
||||
# Gerar documentação Swagger
|
||||
make swagger
|
||||
|
||||
# Abrir documentação local
|
||||
make docs
|
||||
```
|
||||
|
||||
### Dependências
|
||||
|
||||
```bash
|
||||
# Instalar dependências
|
||||
make deps
|
||||
|
||||
# Atualizar dependências
|
||||
make deps-update
|
||||
|
||||
# Limpar dependências não utilizadas
|
||||
make deps-clean
|
||||
```
|
||||
|
||||
### Limpeza
|
||||
|
||||
```bash
|
||||
# Remover arquivos de build
|
||||
make clean
|
||||
|
||||
# Limpeza completa (incluindo cache do Go)
|
||||
make clean-all
|
||||
```
|
||||
|
||||
## 🎯 Workflows Comuns
|
||||
|
||||
### Setup Inicial
|
||||
|
||||
```bash
|
||||
# 1. Clone o repositório
|
||||
git clone https://git.evoai.app/Evolution/evolution-go.git
|
||||
cd evolution-go
|
||||
|
||||
# 2. Setup completo do ambiente
|
||||
make setup
|
||||
|
||||
# 3. Configure o .env
|
||||
cp .env.example .env
|
||||
# Edite o .env com suas configurações
|
||||
|
||||
# 4. Rode em modo desenvolvimento
|
||||
make dev
|
||||
```
|
||||
|
||||
### Desenvolvimento Diário
|
||||
|
||||
```bash
|
||||
# Rodar com hot reload
|
||||
make watch
|
||||
|
||||
# Em outro terminal, rodar testes em watch mode
|
||||
# (requer: go install github.com/cespare/reflex@latest)
|
||||
reflex -r '\.go$' -s -- make test
|
||||
```
|
||||
|
||||
### Antes de Fazer Commit
|
||||
|
||||
```bash
|
||||
# Executar todas as verificações
|
||||
make check
|
||||
|
||||
# Se tudo passar, commit e push
|
||||
git add .
|
||||
git commit -m "feat: sua feature"
|
||||
git push
|
||||
```
|
||||
|
||||
### Preparar para Deploy
|
||||
|
||||
```bash
|
||||
# 1. Rodar todos os testes
|
||||
make test
|
||||
|
||||
# 2. Build da imagem Docker
|
||||
make docker-build
|
||||
|
||||
# 3. Testar localmente
|
||||
make docker-run
|
||||
|
||||
# 4. Se tudo ok, fazer tag e push
|
||||
docker tag evolution-go:latest seu-registry/evolution-go:v1.0.0
|
||||
docker push seu-registry/evolution-go:v1.0.0
|
||||
```
|
||||
|
||||
### Debug e Profiling
|
||||
|
||||
```bash
|
||||
# Ver status da aplicação
|
||||
make status
|
||||
|
||||
# Ver logs em tempo real
|
||||
make logs
|
||||
|
||||
# Profile de CPU (aplicação deve estar rodando)
|
||||
make profile-cpu
|
||||
|
||||
# Profile de memória (aplicação deve estar rodando)
|
||||
make profile-mem
|
||||
|
||||
# Ver informações de versão
|
||||
make version
|
||||
```
|
||||
|
||||
## 🔧 Ferramentas Opcionais
|
||||
|
||||
Instale estas ferramentas para habilitar recursos adicionais:
|
||||
|
||||
```bash
|
||||
# Hot reload
|
||||
go install github.com/cosmtrek/air@latest
|
||||
|
||||
# Linter
|
||||
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
|
||||
|
||||
# Swagger generator
|
||||
go install github.com/swaggo/swag/cmd/swag@latest
|
||||
|
||||
# Watch mode para testes
|
||||
go install github.com/cespare/reflex@latest
|
||||
```
|
||||
|
||||
## 💡 Dicas
|
||||
|
||||
1. **Use `make help`** sempre que esquecer um comando
|
||||
2. **Use `make watch`** durante desenvolvimento para hot reload automático
|
||||
3. **Use `make check`** antes de fazer commit
|
||||
4. **Use `make setup`** em uma nova máquina para configurar tudo de uma vez
|
||||
5. **Configure seu IDE** para rodar `make fmt` ao salvar arquivos
|
||||
|
||||
## 📚 Documentação Completa
|
||||
|
||||
Para documentação completa da API e guias detalhados:
|
||||
|
||||
- **[Documentação Oficial](./docs/wiki/README.md)** - Guias, tutoriais e referência
|
||||
- **[API Swagger](http://localhost:4000/swagger/index.html)** - Documentação interativa (quando servidor estiver rodando)
|
||||
|
||||
## ❓ Problemas Comuns
|
||||
|
||||
### "make: command not found"
|
||||
- **macOS**: `xcode-select --install`
|
||||
- **Ubuntu/Debian**: `sudo apt-get install build-essential`
|
||||
- **Windows**: Use WSL ou instale Make para Windows
|
||||
|
||||
### "air: command not found" ao usar `make watch`
|
||||
```bash
|
||||
go install github.com/cosmtrek/air@latest
|
||||
```
|
||||
|
||||
### "golangci-lint: command not found" ao usar `make lint`
|
||||
```bash
|
||||
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
|
||||
```
|
||||
|
||||
### Porta 4000 já em uso
|
||||
```bash
|
||||
# Mude a porta no .env
|
||||
SERVER_PORT=8080
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Dica Final**: Rode `make help` para ver a lista completa e atualizada de comandos!
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
FROM golang:1.26.10-alpine AS build
|
||||
|
||||
RUN apk update && apk add --no-cache git build-base libjpeg-turbo-dev libwebp-dev
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# Copiar apenas arquivos de dependências primeiro para cachear o download
|
||||
COPY go.mod go.sum ./
|
||||
|
||||
# whatsmeow agora vem do proxy oficial (go.mau.fi/whatsmeow, sem replace local) —
|
||||
# não há mais submódulo whatsmeow-lib para copiar.
|
||||
RUN go mod download
|
||||
|
||||
# Copiar o restante do código
|
||||
COPY . .
|
||||
|
||||
ARG VERSION=dev
|
||||
RUN CGO_ENABLED=1 go build -ldflags "-X main.version=${VERSION}" -o server ./cmd/evolution-go
|
||||
|
||||
FROM alpine:3.19.1 AS final
|
||||
|
||||
# poppler-utils provides pdftoppm, used to rasterize PDF page 1 for /send/media document thumbnails
|
||||
RUN apk update && apk add --no-cache tzdata ffmpeg libjpeg-turbo libwebp poppler-utils
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=build /build/server .
|
||||
COPY --from=build /build/manager/dist ./manager/dist
|
||||
COPY --from=build /build/VERSION ./VERSION
|
||||
|
||||
ENV TZ=America/Sao_Paulo
|
||||
|
||||
ENTRYPOINT ["/app/server"]
|
||||
@@ -0,0 +1,208 @@
|
||||
# Evolution Go License
|
||||
|
||||
Evolution Go is licensed under the Apache License 2.0, with the following additional conditions:
|
||||
|
||||
1. Evolution Go may be utilized commercially, including as a backend service for other applications or as an application development platform for enterprises. Should the conditions below be met, a commercial license must be obtained from the producer:
|
||||
|
||||
a. **LOGO and copyright information**: In the process of using Evolution Go's frontend components, you may not remove or modify the LOGO or copyright information in the Evolution Go console or applications. This restriction is inapplicable to uses of Evolution Go that do not involve its frontend components.
|
||||
|
||||
b. **Usage Notification Requirement**: If Evolution Go is used as part of any project, including closed-source systems (e.g., proprietary software), the user is required to display a clear notification within the system that Evolution Go is being utilized. This notification should be visible to system administrators and accessible from the system's documentation or settings page. Failure to comply with this requirement may result in the necessity for a commercial license, as determined by the producer.
|
||||
|
||||
Please contact [email protected] to inquire about licensing matters.
|
||||
|
||||
Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at http://www.apache.org/licenses/LICENSE-2.0.
|
||||
|
||||
---
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright 2026 Evolution Foundation
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
© 2026 Evolution Foundation
|
||||
@@ -0,0 +1,268 @@
|
||||
.PHONY: help dev run build test clean swagger deps docker-build docker-run install setup migrate-up migrate-down logs
|
||||
|
||||
# Configurações
|
||||
APP_NAME=evolution-go
|
||||
MAIN_PATH=cmd/evolution-go/main.go
|
||||
BUILD_DIR=build
|
||||
GO=go
|
||||
VERSION=$(shell sed -n 's/^## \(v[0-9][^ ]*\).*/\1/p' CHANGELOG.md | head -1)
|
||||
LDFLAGS=-ldflags "-X main.version=$(VERSION)"
|
||||
GOFLAGS=-v
|
||||
|
||||
# Cores para output
|
||||
GREEN=\033[0;32m
|
||||
YELLOW=\033[0;33m
|
||||
RED=\033[0;31m
|
||||
NC=\033[0m # No Color
|
||||
|
||||
##@ Ajuda
|
||||
|
||||
help: ## Exibe esta mensagem de ajuda
|
||||
@echo "$(GREEN)Evolution GO - Makefile$(NC)"
|
||||
@echo ""
|
||||
@awk 'BEGIN {FS = ":.*##"; printf "\nUso:\n make $(YELLOW)<target>$(NC)\n"} /^[a-zA-Z_-]+:.*?##/ { printf " $(GREEN)%-15s$(NC) %s\n", $$1, $$2 } /^##@/ { printf "\n$(YELLOW)%s$(NC)\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
|
||||
|
||||
##@ Desenvolvimento
|
||||
|
||||
dev: ## Roda a aplicação em modo desenvolvimento
|
||||
@echo "$(GREEN)🚀 Rodando Evolution GO em modo desenvolvimento...$(NC)"
|
||||
$(GO) run $(LDFLAGS) $(MAIN_PATH) -dev
|
||||
|
||||
run: ## Roda a aplicação em modo produção
|
||||
@echo "$(GREEN)🚀 Rodando Evolution GO...$(NC)"
|
||||
$(GO) run $(MAIN_PATH)
|
||||
|
||||
watch: ## Roda a aplicação com hot reload (requer air)
|
||||
@if command -v air > /dev/null; then \
|
||||
echo "$(GREEN)🔥 Rodando com hot reload...$(NC)"; \
|
||||
air; \
|
||||
else \
|
||||
echo "$(RED)❌ Air não instalado. Instale com: go install github.com/cosmtrek/air@latest$(NC)"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
##@ Build
|
||||
|
||||
build: ## Compila a aplicação
|
||||
@echo "$(GREEN)🔨 Compilando $(APP_NAME)...$(NC)"
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
$(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME) $(MAIN_PATH)
|
||||
@echo "$(GREEN)✅ Build completo: $(BUILD_DIR)/$(APP_NAME)$(NC)"
|
||||
|
||||
build-linux: ## Compila para Linux
|
||||
@echo "$(GREEN)🔨 Compilando para Linux...$(NC)"
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=linux GOARCH=amd64 $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-linux-amd64 $(MAIN_PATH)
|
||||
@echo "$(GREEN)✅ Build Linux completo$(NC)"
|
||||
|
||||
build-windows: ## Compila para Windows
|
||||
@echo "$(GREEN)🔨 Compilando para Windows...$(NC)"
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=windows GOARCH=amd64 $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-windows-amd64.exe $(MAIN_PATH)
|
||||
@echo "$(GREEN)✅ Build Windows completo$(NC)"
|
||||
|
||||
build-all: build build-linux build-windows ## Compila para todas as plataformas
|
||||
@echo "$(GREEN)✅ Todos os builds completos$(NC)"
|
||||
|
||||
install: build ## Compila e instala no GOPATH
|
||||
@echo "$(GREEN)📦 Instalando $(APP_NAME)...$(NC)"
|
||||
$(GO) install $(MAIN_PATH)
|
||||
@echo "$(GREEN)✅ Instalado com sucesso$(NC)"
|
||||
|
||||
##@ Testes
|
||||
|
||||
test: ## Roda todos os testes
|
||||
@echo "$(GREEN)🧪 Rodando testes...$(NC)"
|
||||
$(GO) test -v ./...
|
||||
|
||||
test-coverage: ## Roda testes com cobertura
|
||||
@echo "$(GREEN)🧪 Rodando testes com cobertura...$(NC)"
|
||||
$(GO) test -v -coverprofile=coverage.out ./...
|
||||
$(GO) tool cover -html=coverage.out -o coverage.html
|
||||
@echo "$(GREEN)✅ Cobertura gerada: coverage.html$(NC)"
|
||||
|
||||
test-race: ## Roda testes verificando race conditions
|
||||
@echo "$(GREEN)🧪 Rodando testes com race detector...$(NC)"
|
||||
$(GO) test -race -v ./...
|
||||
|
||||
bench: ## Roda benchmarks
|
||||
@echo "$(GREEN)⚡ Rodando benchmarks...$(NC)"
|
||||
$(GO) test -bench=. -benchmem ./...
|
||||
|
||||
##@ Dependências
|
||||
|
||||
deps: ## Instala dependências
|
||||
@echo "$(GREEN)📦 Instalando dependências...$(NC)"
|
||||
$(GO) mod download
|
||||
$(GO) mod verify
|
||||
@echo "$(GREEN)✅ Dependências instaladas$(NC)"
|
||||
|
||||
deps-update: ## Atualiza dependências
|
||||
@echo "$(GREEN)📦 Atualizando dependências...$(NC)"
|
||||
$(GO) get -u ./...
|
||||
$(GO) mod tidy
|
||||
@echo "$(GREEN)✅ Dependências atualizadas$(NC)"
|
||||
|
||||
deps-clean: ## Limpa dependências não utilizadas
|
||||
@echo "$(GREEN)🧹 Limpando dependências...$(NC)"
|
||||
$(GO) mod tidy
|
||||
@echo "$(GREEN)✅ Dependências limpas$(NC)"
|
||||
|
||||
deps-reset: ## Limpa cache e reinstala dependências (força uso do código local)
|
||||
@echo "$(GREEN)🔄 Resetando dependências e cache...$(NC)"
|
||||
@echo "$(YELLOW)Limpeza de cache e módulos...$(NC)"
|
||||
$(GO) clean -cache -modcache -i -r
|
||||
@echo "$(YELLOW)Download de módulos...$(NC)"
|
||||
$(GO) mod download
|
||||
@echo "$(YELLOW)Organizando módulos...$(NC)"
|
||||
$(GO) mod tidy
|
||||
@echo "$(GREEN)✅ Dependências resetadas e atualizadas$(NC)"
|
||||
|
||||
##@ Documentação
|
||||
|
||||
swagger: ## Gera documentação Swagger
|
||||
@echo "$(GREEN)📚 Gerando documentação Swagger...$(NC)"
|
||||
@if command -v swag > /dev/null; then \
|
||||
swag init -g $(MAIN_PATH) -o ./docs; \
|
||||
echo "$(GREEN)✅ Swagger gerado com sucesso$(NC)"; \
|
||||
else \
|
||||
echo "$(RED)❌ Swag não instalado. Instale com: go install github.com/swaggo/swag/cmd/swag@latest$(NC)"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
docs: ## Abre a documentação local
|
||||
@echo "$(GREEN)📖 Abrindo documentação...$(NC)"
|
||||
@if [ -f "docs/wiki/README.md" ]; then \
|
||||
echo "Documentação disponível em: docs/wiki/README.md"; \
|
||||
else \
|
||||
echo "$(RED)❌ Documentação não encontrada$(NC)"; \
|
||||
fi
|
||||
|
||||
##@ Database
|
||||
|
||||
migrate-up: ## Executa migrations do banco de dados
|
||||
@echo "$(GREEN)🗃️ Executando migrations...$(NC)"
|
||||
@if [ -d "migrations" ]; then \
|
||||
$(GO) run $(MAIN_PATH) migrate up; \
|
||||
else \
|
||||
echo "$(YELLOW)⚠️ Diretório migrations não encontrado$(NC)"; \
|
||||
fi
|
||||
|
||||
migrate-down: ## Reverte migrations do banco de dados
|
||||
@echo "$(YELLOW)⚠️ Revertendo migrations...$(NC)"
|
||||
@if [ -d "migrations" ]; then \
|
||||
$(GO) run $(MAIN_PATH) migrate down; \
|
||||
else \
|
||||
echo "$(YELLOW)⚠️ Diretório migrations não encontrado$(NC)"; \
|
||||
fi
|
||||
|
||||
##@ Docker
|
||||
|
||||
docker-build: ## Build da imagem Docker
|
||||
@echo "$(GREEN)🐳 Construindo imagem Docker...$(NC)"
|
||||
docker build --build-arg VERSION=$(VERSION) -t $(APP_NAME):latest .
|
||||
@echo "$(GREEN)✅ Imagem Docker construída$(NC)"
|
||||
|
||||
docker-run: ## Roda container Docker
|
||||
@echo "$(GREEN)🐳 Iniciando container...$(NC)"
|
||||
docker run -p 4000:4000 --env-file .env $(APP_NAME):latest
|
||||
|
||||
docker-compose-up: ## Sobe todos os serviços com docker-compose
|
||||
@echo "$(GREEN)🐳 Iniciando serviços com docker-compose...$(NC)"
|
||||
docker-compose up -d
|
||||
|
||||
docker-compose-down: ## Para todos os serviços do docker-compose
|
||||
@echo "$(YELLOW)🐳 Parando serviços...$(NC)"
|
||||
docker-compose down
|
||||
|
||||
docker-compose-logs: ## Exibe logs do docker-compose
|
||||
docker-compose logs -f
|
||||
|
||||
##@ Linting e Formatação
|
||||
|
||||
fmt: ## Formata o código
|
||||
@echo "$(GREEN)✨ Formatando código...$(NC)"
|
||||
$(GO) fmt ./...
|
||||
@echo "$(GREEN)✅ Código formatado$(NC)"
|
||||
|
||||
lint: ## Executa linter (requer golangci-lint)
|
||||
@echo "$(GREEN)🔍 Executando linter...$(NC)"
|
||||
@if command -v golangci-lint > /dev/null; then \
|
||||
golangci-lint run ./...; \
|
||||
echo "$(GREEN)✅ Lint completo$(NC)"; \
|
||||
else \
|
||||
echo "$(RED)❌ golangci-lint não instalado. Instale com: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest$(NC)"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
vet: ## Executa go vet
|
||||
@echo "$(GREEN)🔍 Executando go vet...$(NC)"
|
||||
$(GO) vet ./...
|
||||
@echo "$(GREEN)✅ Vet completo$(NC)"
|
||||
|
||||
check: fmt vet lint test ## Executa todas as verificações
|
||||
|
||||
##@ Limpeza
|
||||
|
||||
clean: ## Remove arquivos de build
|
||||
@echo "$(YELLOW)🧹 Limpando arquivos de build...$(NC)"
|
||||
@rm -rf $(BUILD_DIR)
|
||||
@rm -f coverage.out coverage.html
|
||||
@echo "$(GREEN)✅ Limpeza completa$(NC)"
|
||||
|
||||
clean-all: clean ## Remove arquivos de build e cache
|
||||
@echo "$(YELLOW)🧹 Limpeza completa (incluindo cache)...$(NC)"
|
||||
$(GO) clean -cache -testcache -modcache
|
||||
@echo "$(GREEN)✅ Limpeza completa$(NC)"
|
||||
|
||||
##@ Utilitários
|
||||
|
||||
setup: deps swagger ## Setup completo do ambiente de desenvolvimento
|
||||
@echo "$(GREEN)🎉 Setup completo!$(NC)"
|
||||
@echo ""
|
||||
@echo "Para começar a desenvolver, rode:"
|
||||
@echo " $(YELLOW)make dev$(NC)"
|
||||
@echo ""
|
||||
@echo "Outros comandos úteis:"
|
||||
@echo " $(YELLOW)make help$(NC) - Ver todos os comandos"
|
||||
@echo " $(YELLOW)make test$(NC) - Rodar testes"
|
||||
@echo " $(YELLOW)make build$(NC) - Compilar a aplicação"
|
||||
|
||||
logs: ## Exibe logs da aplicação (se estiver rodando)
|
||||
@echo "$(GREEN)📋 Exibindo logs...$(NC)"
|
||||
@if [ -f "logs/app.log" ]; then \
|
||||
tail -f logs/app.log; \
|
||||
else \
|
||||
echo "$(YELLOW)⚠️ Arquivo de log não encontrado$(NC)"; \
|
||||
fi
|
||||
|
||||
version: ## Exibe versão do Go e dependências
|
||||
@echo "$(GREEN)📌 Versões:$(NC)"
|
||||
@$(GO) version
|
||||
@echo ""
|
||||
@echo "$(GREEN)Dependências principais:$(NC)"
|
||||
@$(GO) list -m all | grep -E '(whatsmeow|postgres|minio)'
|
||||
|
||||
status: ## Verifica status da aplicação
|
||||
@echo "$(GREEN)🔍 Verificando status...$(NC)"
|
||||
@curl -s http://localhost:4000/health || echo "$(RED)❌ Aplicação não está rodando$(NC)"
|
||||
|
||||
##@ Desenvolvimento Avançado
|
||||
|
||||
profile-cpu: ## Profile de CPU (requer aplicação rodando)
|
||||
@echo "$(GREEN)📊 Capturando profile de CPU...$(NC)"
|
||||
curl http://localhost:4000/debug/pprof/profile?seconds=30 > cpu.prof
|
||||
$(GO) tool pprof -http=:8080 cpu.prof
|
||||
|
||||
profile-mem: ## Profile de memória (requer aplicação rodando)
|
||||
@echo "$(GREEN)📊 Capturando profile de memória...$(NC)"
|
||||
curl http://localhost:4000/debug/pprof/heap > mem.prof
|
||||
$(GO) tool pprof -http=:8080 mem.prof
|
||||
|
||||
generate: ## Roda go generate
|
||||
@echo "$(GREEN)⚙️ Executando go generate...$(NC)"
|
||||
$(GO) generate ./...
|
||||
|
||||
mod-graph: ## Exibe gráfico de dependências
|
||||
@echo "$(GREEN)📊 Gráfico de dependências:$(NC)"
|
||||
$(GO) mod graph
|
||||
@@ -0,0 +1,18 @@
|
||||
Evolution Go
|
||||
Copyright 2026 Evolution Foundation
|
||||
|
||||
This product includes software developed by Evolution Foundation
|
||||
(https://evolutionfoundation.com.br).
|
||||
|
||||
Trademark notice
|
||||
"Evolution Foundation", "Evolution" and "Evolution Go" are trademarks of
|
||||
Evolution Foundation. The Evolution Go logo, wordmark, and visual identity
|
||||
are governed by the Trademark and Brand Assets Policy included in this
|
||||
repository (TRADEMARKS.md).
|
||||
|
||||
Third-party attributions
|
||||
|
||||
This product includes software developed by external contributors:
|
||||
|
||||
- whatsmeow (https://github.com/tulir/whatsmeow) by Tulir Asokan, used as the
|
||||
WhatsApp protocol library.
|
||||
@@ -1,3 +1,261 @@
|
||||
# template-ci-cd
|
||||
<p align="center">
|
||||
<a href="https://evolutionfoundation.com.br">
|
||||
<img src="./public/hover-evolution.png" alt="Evolution Foundation" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
Modelo de projetos com Gitea Actions, Docker e instruções para agentes de IA
|
||||
<h1 align="center">Evolution Go</h1>
|
||||
|
||||
<p align="center">
|
||||
High-performance WhatsApp API built in Go — part of the Evolution Foundation ecosystem.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/evolution-foundation/evolution-go/releases/latest"><img src="https://img.shields.io/github/v/release/evolution-foundation/evolution-go?include_prereleases&label=version&color=00ffa7" alt="Latest version" /></a>
|
||||
<a href="https://opensource.org/licenses/Apache-2.0"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License: Apache 2.0" /></a>
|
||||
<a href="https://docs.evolutionfoundation.com.br"><img src="https://img.shields.io/badge/Docs-evolutionfoundation.com.br-00ffa7" alt="Documentation" /></a>
|
||||
<a href="https://evolutionfoundation.com.br/community"><img src="https://img.shields.io/badge/Community-Join%20us-white" alt="Community" /></a>
|
||||
<a href="https://hub.docker.com/r/evoapicloud/evolution-go"><img src="https://img.shields.io/badge/Docker-evoapicloud-blue" alt="Docker image" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://evolutionfoundation.com.br">Website</a> ·
|
||||
<a href="https://docs.evolutionfoundation.com.br">Documentation</a> ·
|
||||
<a href="https://evolutionfoundation.com.br/community">Community</a> ·
|
||||
<a href="mailto:suporte@evofoundation.com.br">Support</a>
|
||||
</p>
|
||||
|
||||
|
||||
---
|
||||
|
||||
## About
|
||||
|
||||
**Evolution Go** is a high-performance WhatsApp API built in Go. Part of the Evolution Foundation ecosystem, it provides a robust, lightweight solution for WhatsApp integration using the [whatsmeow](https://github.com/tulir/whatsmeow) library.
|
||||
|
||||
## Part of the Evolution Foundation ecosystem
|
||||
|
||||
Evolution Go is one of the messaging engines maintained by Evolution Foundation. It is used as a WhatsApp provider by the [Evo CRM Community](https://github.com/evolution-foundation/evo-crm-community) and other projects in the ecosystem.
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **High performance** — built with Go for minimal resource usage
|
||||
- **RESTful API** — clean, well-documented REST endpoints with Swagger
|
||||
- **Real-time events** — WebSocket, Webhook, AMQP/RabbitMQ and NATS support
|
||||
- **Media support** — images, videos, audio, documents with MinIO/S3 storage
|
||||
- **Message storage** — optional PostgreSQL persistence
|
||||
- **QR code pairing** — built-in QR code generation for device linking
|
||||
- **License management** — built-in licensing with registration, activation, and heartbeat
|
||||
- **Docker ready** — production-ready Docker configuration
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Docker (recommended)
|
||||
|
||||
```bash
|
||||
git clone https://github.com/evolution-foundation/evolution-go.git
|
||||
cd evolution-go
|
||||
make docker-build
|
||||
make docker-run
|
||||
```
|
||||
|
||||
### Local development
|
||||
|
||||
```bash
|
||||
git clone https://github.com/evolution-foundation/evolution-go.git
|
||||
cd evolution-go
|
||||
|
||||
# Setup, configure and run
|
||||
make setup
|
||||
cp .env.example .env
|
||||
make dev
|
||||
```
|
||||
|
||||
> Run `make help` to see all available commands. See [COMMANDS.md](./COMMANDS.md) for detailed workflows.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Create a `.env` file:
|
||||
|
||||
```env
|
||||
# Server
|
||||
SERVER_PORT=8080
|
||||
CLIENT_NAME=evolution
|
||||
|
||||
# Security
|
||||
GLOBAL_API_KEY=your-secure-api-key-here
|
||||
|
||||
# Database
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:password@localhost:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://postgres:password@localhost:5432/evogo_users?sslmode=disable
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
|
||||
# Logging
|
||||
WADEBUG=DEBUG
|
||||
LOGTYPE=console
|
||||
|
||||
# Optional
|
||||
# AMQP_URL=amqp://guest:guest@localhost:5672/
|
||||
# NATS_URL=nats://localhost:4222
|
||||
# WEBHOOK_URL=https://your-webhook-url.com/webhook
|
||||
# MINIO_ENABLED=true
|
||||
# MINIO_ENDPOINT=localhost:9000
|
||||
# MINIO_ACCESS_KEY=minioadmin
|
||||
# MINIO_SECRET_KEY=minioadmin
|
||||
```
|
||||
|
||||
| Variable | Description | Default |
|
||||
|---|---|---|
|
||||
| `SERVER_PORT` | Server port | `8080` |
|
||||
| `CLIENT_NAME` | Client identifier | `evolution` |
|
||||
| `GLOBAL_API_KEY` | API authentication key | **Required** |
|
||||
| `DATABASE_SAVE_MESSAGES` | Enable message storage | `false` |
|
||||
| `WADEBUG` | WhatsApp debug level | `INFO` |
|
||||
|
||||
---
|
||||
|
||||
## License Activation
|
||||
|
||||
Evolution Go requires a license to operate. On first run:
|
||||
|
||||
1. Start the server — API endpoints return `503` until activated
|
||||
2. Open the **Manager** at `http://localhost:8080/manager/login`
|
||||
3. Enter your API URL and `GLOBAL_API_KEY`
|
||||
4. Complete the license registration flow
|
||||
5. Once activated, the API is fully operational
|
||||
|
||||
The license status persists in the database (`runtime_configs` table). Heartbeats are sent periodically to maintain activation.
|
||||
|
||||
---
|
||||
|
||||
## API Documentation
|
||||
|
||||
Swagger UI available at:
|
||||
|
||||
```
|
||||
http://localhost:8080/swagger/index.html
|
||||
```
|
||||
|
||||
### Key Endpoints
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|---|---|---|
|
||||
| `POST` | `/instance/create` | Create WhatsApp instance |
|
||||
| `GET` | `/instance/{name}/qrcode` | Get QR code for pairing |
|
||||
| `POST` | `/message/sendText` | Send text message |
|
||||
| `POST` | `/message/sendMedia` | Send media message |
|
||||
| `GET` | `/instance/{name}/status` | Get instance status |
|
||||
| `DELETE` | `/instance/{name}` | Delete instance |
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
evolution-go/
|
||||
├── cmd/evolution-go/ # Application entry point
|
||||
├── pkg/
|
||||
│ ├── core/ # License management & middleware
|
||||
│ ├── instance/ # Instance management
|
||||
│ ├── message/ # Message handling
|
||||
│ ├── sendMessage/ # Message sending
|
||||
│ ├── routes/ # HTTP routes
|
||||
│ ├── middleware/ # Auth & validation middleware
|
||||
│ ├── config/ # Configuration
|
||||
│ ├── events/ # Event producers (AMQP, NATS, Webhook, WS)
|
||||
│ └── storage/ # Media storage (MinIO)
|
||||
├── docs/ # Swagger documentation
|
||||
├── Dockerfile
|
||||
├── Makefile
|
||||
└── VERSION
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Component | Technology |
|
||||
|---|---|
|
||||
| Language | Go 1.24+ |
|
||||
| HTTP framework | Gin |
|
||||
| WhatsApp | [whatsmeow](https://github.com/tulir/whatsmeow) |
|
||||
| Database | PostgreSQL |
|
||||
| ORM | GORM |
|
||||
| Message queue | RabbitMQ, NATS |
|
||||
| Object storage | MinIO/S3 |
|
||||
| Documentation | Swagger/OpenAPI |
|
||||
| Container | Docker |
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
| Resource | Link |
|
||||
|---|---|
|
||||
| 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) |
|
||||
| Docker Hub | [evoapicloud/evolution-go](https://hub.docker.com/r/evoapicloud/evolution-go) |
|
||||
| Changelog | [CHANGELOG.md](./CHANGELOG.md) |
|
||||
| Contributing | [CONTRIBUTING.md](./CONTRIBUTING.md) |
|
||||
| Security | [SECURITY.md](./SECURITY.md) |
|
||||
|
||||
---
|
||||
|
||||
## Hosting
|
||||
|
||||
Deploy Evolution Go with optimized infrastructure through our HostGator partnership:
|
||||
|
||||
[**Evolution Go VPS — HostGator**](https://evolution-api.com/vps-evolution-go)
|
||||
|
||||
---
|
||||
|
||||
## Telemetry
|
||||
|
||||
Evolution Go collects anonymous telemetry data (routes used, API version) to help improve the service. **No sensitive or personal data is collected.**
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please read [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines on how to submit issues, propose features, and open pull requests.
|
||||
|
||||
Join our [community](https://evolutionfoundation.com.br/community) to discuss ideas and collaborate.
|
||||
|
||||
---
|
||||
|
||||
## Security
|
||||
|
||||
For security issues, **do not open a public issue**. Email **[email protected]** or use GitHub's private vulnerability reporting. See [SECURITY.md](./SECURITY.md) for details.
|
||||
|
||||
---
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
- [whatsmeow](https://github.com/tulir/whatsmeow) by [Tulir Asokan](https://github.com/tulir) — WhatsApp protocol library
|
||||
- [Evolution API](https://github.com/evolution-foundation/evolution-api) — Node.js sister project
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Evolution Go is licensed under the Apache License 2.0, with additional brand-protection conditions (LOGO/copyright preservation and Usage Notification requirement). See [LICENSE](./LICENSE) for full details.
|
||||
|
||||
For licensing inquiries, contact **[email protected]**.
|
||||
|
||||
## Trademarks
|
||||
|
||||
"Evolution Foundation", "Evolution" and "Evolution Go" are trademarks of Evolution Foundation. See [TRADEMARKS.md](./TRADEMARKS.md) for the brand assets policy.
|
||||
|
||||
Third-party attributions are documented in [NOTICE](./NOTICE).
|
||||
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
Made by <a href="https://evolutionfoundation.com.br">Evolution Foundation</a> · © 2026
|
||||
</p>
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
# Evolution Go — Trademark and Brand Assets Policy
|
||||
|
||||
Version 1.0, 2026.05.06
|
||||
|
||||
"Evolution Foundation", "Evolution" and "Evolution Go" are trademarks of
|
||||
Evolution Foundation. The "evolution-go" wordmark and the Evolution Go
|
||||
logo are trademarks of Evolution Foundation.
|
||||
|
||||
## 1. Scope and purpose
|
||||
|
||||
This policy governs the use of Evolution Go trademarks and brand assets.
|
||||
It is intended to protect users from confusion and to preserve the official
|
||||
Evolution Go visual identity.
|
||||
|
||||
This policy applies to any use of:
|
||||
(a) the product names and marks "Evolution Foundation", "Evolution" and "Evolution Go";
|
||||
(b) the official logo and wordmark: the "evolution-go" wordmark and any
|
||||
associated icon in neon green;
|
||||
(c) the copyright line "© 2026 Evolution Foundation"; and
|
||||
(d) any materials that implement or express the Evolution Go official look
|
||||
and feel, including the Protected Visual Identity Elements listed in Section 3.
|
||||
|
||||
This policy does not change the software license for the source code, which is
|
||||
licensed under the Apache License 2.0. This policy controls only trademarks and
|
||||
brand assets.
|
||||
|
||||
## 2. Permitted trademark and brand asset use
|
||||
|
||||
2.1. You may truthfully refer to Evolution Go to describe that your software
|
||||
is based on, compatible with, or derived from this project, provided that such
|
||||
use does not imply endorsement by Evolution Foundation.
|
||||
|
||||
2.2. You may distribute and publicly host unmodified official builds of
|
||||
Evolution Go that include Evolution Go brand assets, provided that you
|
||||
comply with Section 3 and do not suggest endorsement beyond being an official
|
||||
unmodified build.
|
||||
|
||||
2.3. You may use Evolution Go marks in nominative ways, such as
|
||||
"based on Evolution Go", provided that the use is accurate and does not
|
||||
create confusion.
|
||||
|
||||
## 3. Protected Visual Identity Elements (Brand Assets)
|
||||
|
||||
The following are the "Protected Visual Identity Elements":
|
||||
(a) Product names and marks: "Evolution Foundation", "Evolution" and "Evolution Go";
|
||||
(b) Official logo and wordmark: the "evolution-go" wordmark and any associated icon;
|
||||
(c) Copyright line: "© 2026 Evolution Foundation";
|
||||
(d) Official palette:
|
||||
Background main: #0a0a0a
|
||||
Background cards and popovers: #0a0a0a
|
||||
Sidebar background: #171717
|
||||
Primary neon green: #00ffa7
|
||||
Primary green for light mode references: #01b274
|
||||
Main text: #fafafa
|
||||
Muted text: #a1a1a1
|
||||
Borders and inputs: #262626
|
||||
Muted background: #262626
|
||||
Ring and focus: #555555
|
||||
(e) Typography: ui sans serif, system ui, sans serif with base size 16px;
|
||||
(f) Border radius: 0.625rem (10px) as the default component radius.
|
||||
|
||||
## 4. Restrictions for forks, modified versions, and redistributions
|
||||
|
||||
4.1. **No modification of Protected Visual Identity Elements when using
|
||||
Evolution Go brand assets.** If you distribute or publicly host any version
|
||||
of the user interface that uses Evolution Go brand assets, you may not
|
||||
remove, replace, modify, disable, or bypass any Protected Visual Identity Element.
|
||||
|
||||
4.2. **Modified UI must remove Evolution Go brand assets.**
|
||||
If you distribute or publicly host a modified user interface or user experience
|
||||
(including changes to branding or visual identity), you must:
|
||||
(a) remove and replace all Evolution Go trademarks and brand assets from
|
||||
the user interface, product name display, and related marketing materials
|
||||
for that distribution; and
|
||||
(b) choose a name and branding that are clearly distinct from Evolution Go.
|
||||
|
||||
4.3. **No endorsement.**
|
||||
You may not use Evolution Go trademarks or brand assets in a way that
|
||||
implies Evolution Foundation sponsors, endorses, or is affiliated with your
|
||||
distribution, except for unmodified official builds.
|
||||
|
||||
4.4. **No derivative works of the logo and wordmark.**
|
||||
You may not modify, adapt, recolor, redesign, or create derivative works of the
|
||||
Evolution Go logo or wordmark.
|
||||
|
||||
## 5. Permission requests
|
||||
|
||||
Any use not expressly permitted by this policy requires prior written permission
|
||||
from Evolution Foundation. Contact: **[email protected]**.
|
||||
|
||||
## 6. Enforcement and termination
|
||||
|
||||
Any violation of this policy terminates your permission to use Evolution Go
|
||||
brand assets. You must promptly cease use and remove Evolution Go trademarks
|
||||
and brand assets from your distribution and any public hosting.
|
||||
|
||||
## 7. Disclaimer
|
||||
|
||||
This policy is provided "as is" and does not grant any rights beyond what is
|
||||
expressly stated. All rights not expressly granted are reserved by Evolution
|
||||
Foundation.
|
||||
@@ -0,0 +1,448 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/joho/godotenv"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"gorm.io/gorm"
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
call_handler "github.com/evolution-foundation/evolution-go/pkg/call/handler"
|
||||
call_service "github.com/evolution-foundation/evolution-go/pkg/call/service"
|
||||
chat_handler "github.com/evolution-foundation/evolution-go/pkg/chat/handler"
|
||||
chat_service "github.com/evolution-foundation/evolution-go/pkg/chat/service"
|
||||
community_handler "github.com/evolution-foundation/evolution-go/pkg/community/handler"
|
||||
community_service "github.com/evolution-foundation/evolution-go/pkg/community/service"
|
||||
config "github.com/evolution-foundation/evolution-go/pkg/config"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/core"
|
||||
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
|
||||
nats_producer "github.com/evolution-foundation/evolution-go/pkg/events/nats"
|
||||
rabbitmq_producer "github.com/evolution-foundation/evolution-go/pkg/events/rabbitmq"
|
||||
webhook_producer "github.com/evolution-foundation/evolution-go/pkg/events/webhook"
|
||||
websocket_producer "github.com/evolution-foundation/evolution-go/pkg/events/websocket"
|
||||
group_handler "github.com/evolution-foundation/evolution-go/pkg/group/handler"
|
||||
group_service "github.com/evolution-foundation/evolution-go/pkg/group/service"
|
||||
instance_handler "github.com/evolution-foundation/evolution-go/pkg/instance/handler"
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
instance_repository "github.com/evolution-foundation/evolution-go/pkg/instance/repository"
|
||||
instance_service "github.com/evolution-foundation/evolution-go/pkg/instance/service"
|
||||
label_handler "github.com/evolution-foundation/evolution-go/pkg/label/handler"
|
||||
label_model "github.com/evolution-foundation/evolution-go/pkg/label/model"
|
||||
label_repository "github.com/evolution-foundation/evolution-go/pkg/label/repository"
|
||||
label_service "github.com/evolution-foundation/evolution-go/pkg/label/service"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
message_handler "github.com/evolution-foundation/evolution-go/pkg/message/handler"
|
||||
message_model "github.com/evolution-foundation/evolution-go/pkg/message/model"
|
||||
message_repository "github.com/evolution-foundation/evolution-go/pkg/message/repository"
|
||||
message_service "github.com/evolution-foundation/evolution-go/pkg/message/service"
|
||||
auth_middleware "github.com/evolution-foundation/evolution-go/pkg/middleware"
|
||||
newsletter_handler "github.com/evolution-foundation/evolution-go/pkg/newsletter/handler"
|
||||
newsletter_service "github.com/evolution-foundation/evolution-go/pkg/newsletter/service"
|
||||
passkey_handler "github.com/evolution-foundation/evolution-go/pkg/passkey/handler"
|
||||
poll_handler "github.com/evolution-foundation/evolution-go/pkg/poll/handler"
|
||||
routes "github.com/evolution-foundation/evolution-go/pkg/routes"
|
||||
send_handler "github.com/evolution-foundation/evolution-go/pkg/sendMessage/handler"
|
||||
send_service "github.com/evolution-foundation/evolution-go/pkg/sendMessage/service"
|
||||
server_handler "github.com/evolution-foundation/evolution-go/pkg/server/handler"
|
||||
storage_interfaces "github.com/evolution-foundation/evolution-go/pkg/storage/interfaces"
|
||||
minio_storage "github.com/evolution-foundation/evolution-go/pkg/storage/minio"
|
||||
user_handler "github.com/evolution-foundation/evolution-go/pkg/user/handler"
|
||||
user_service "github.com/evolution-foundation/evolution-go/pkg/user/service"
|
||||
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
var devMode = flag.Bool("dev", false, "Enable development mode")
|
||||
|
||||
var version = "0.0.0"
|
||||
|
||||
func init() {
|
||||
// ldflags -X main.version= sets this at compile time.
|
||||
// If not set (or still default), try reading from VERSION file.
|
||||
if version == "0.0.0" {
|
||||
if v, err := os.ReadFile("VERSION"); err == nil {
|
||||
if trimmed := strings.TrimSpace(string(v)); trimmed != "" {
|
||||
version = trimmed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.Config, conn *amqp.Connection, exPath string, runtimeCtx *core.RuntimeContext) *gin.Engine {
|
||||
killChannel := safemap.New[chan bool]()
|
||||
clientPointer := safemap.New[*whatsmeow.Client]()
|
||||
|
||||
loggerWrapper := logger_wrapper.NewLoggerManager(config)
|
||||
|
||||
var rabbitmqProducer producer_interfaces.Producer
|
||||
if conn != nil {
|
||||
logger.LogInfo("RabbitMQ enabled")
|
||||
rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer(
|
||||
conn,
|
||||
config.AmqpGlobalEnabled,
|
||||
config.AmqpGlobalEvents,
|
||||
config.AmqpSpecificEvents,
|
||||
config.AmqpUrl,
|
||||
loggerWrapper,
|
||||
)
|
||||
} else {
|
||||
// Even if initial connection failed, pass the URL so reconnection can work
|
||||
rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer(
|
||||
nil,
|
||||
config.AmqpGlobalEnabled,
|
||||
config.AmqpGlobalEvents,
|
||||
config.AmqpSpecificEvents,
|
||||
config.AmqpUrl, // Keep the URL for reconnection attempts
|
||||
loggerWrapper,
|
||||
)
|
||||
}
|
||||
|
||||
var natsProducer producer_interfaces.Producer
|
||||
if config.NatsUrl != "" {
|
||||
logger.LogInfo("NATS enabled")
|
||||
natsProducer = nats_producer.NewNatsProducer(
|
||||
config.NatsUrl,
|
||||
config.NatsGlobalEnabled,
|
||||
config.NatsGlobalEvents,
|
||||
loggerWrapper,
|
||||
)
|
||||
} else {
|
||||
natsProducer = nats_producer.NewNatsProducer(
|
||||
"",
|
||||
false,
|
||||
nil,
|
||||
loggerWrapper,
|
||||
)
|
||||
}
|
||||
|
||||
webhookProducer := webhook_producer.NewWebhookProducer(config.WebhookUrl, loggerWrapper)
|
||||
websocketProducer := websocket_producer.NewWebsocketProducer(loggerWrapper)
|
||||
|
||||
// Cria filas globais se o RabbitMQ global estiver habilitado
|
||||
if config.AmqpGlobalEnabled && conn != nil {
|
||||
logger.LogInfo("Creating global RabbitMQ queues...")
|
||||
if err := rabbitmqProducer.CreateGlobalQueues(); err != nil {
|
||||
logger.LogError("Failed to create global RabbitMQ queues: %v", err)
|
||||
} else {
|
||||
logger.LogInfo("Global RabbitMQ queues created successfully")
|
||||
}
|
||||
}
|
||||
|
||||
var mediaStorage storage_interfaces.MediaStorage
|
||||
var err error
|
||||
if config.MinioEnabled {
|
||||
mediaStorage, err = minio_storage.NewMinioMediaStorage(
|
||||
config.MinioEndpoint,
|
||||
config.MinioAccessKey,
|
||||
config.MinioSecretKey,
|
||||
config.MinioBucket,
|
||||
config.MinioRegion,
|
||||
config.MinioUseSSL,
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
instanceRepository := instance_repository.NewInstanceRepository(db)
|
||||
messageRepository := message_repository.NewMessageRepository(db)
|
||||
labelRepository := label_repository.NewLabelRepository(db)
|
||||
|
||||
whatsmeowService := whatsmeow_service.NewWhatsmeowService(
|
||||
instanceRepository,
|
||||
authDB,
|
||||
message_repository.NewMessageRepository(db),
|
||||
labelRepository,
|
||||
config,
|
||||
killChannel,
|
||||
clientPointer,
|
||||
rabbitmqProducer,
|
||||
webhookProducer,
|
||||
websocketProducer,
|
||||
sqliteDB,
|
||||
exPath,
|
||||
mediaStorage,
|
||||
natsProducer,
|
||||
loggerWrapper,
|
||||
)
|
||||
instanceService := instance_service.NewInstanceService(
|
||||
instanceRepository,
|
||||
killChannel,
|
||||
clientPointer,
|
||||
whatsmeowService,
|
||||
config,
|
||||
loggerWrapper,
|
||||
)
|
||||
sendMessageService := send_service.NewSendService(clientPointer, whatsmeowService, config, loggerWrapper)
|
||||
userService := user_service.NewUserService(clientPointer, whatsmeowService, loggerWrapper)
|
||||
messageService := message_service.NewMessageService(clientPointer, messageRepository, whatsmeowService, loggerWrapper)
|
||||
chatService := chat_service.NewChatService(clientPointer, whatsmeowService, loggerWrapper)
|
||||
groupService := group_service.NewGroupService(clientPointer, whatsmeowService, loggerWrapper)
|
||||
callService := call_service.NewCallService(clientPointer, whatsmeowService, loggerWrapper)
|
||||
communityService := community_service.NewCommunityService(clientPointer, whatsmeowService, loggerWrapper)
|
||||
labelService := label_service.NewLabelService(clientPointer, whatsmeowService, labelRepository, loggerWrapper)
|
||||
newsletterService := newsletter_service.NewNewsletterService(clientPointer, whatsmeowService, loggerWrapper)
|
||||
|
||||
// NOVO: PollHandler usando PollService já inicializado no whatsmeowService (evita dupla inicialização)
|
||||
pollHandler := poll_handler.NewPollHandler(whatsmeowService.GetPollService(), loggerWrapper)
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
// CORS middleware — must be before everything else
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Cache-Control, X-Requested-With, apikey, ApiKey")
|
||||
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(200)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
|
||||
r.Use(core.GateMiddleware(runtimeCtx))
|
||||
|
||||
// License routes (always accessible, even without license)
|
||||
core.LicenseRoutes(r, runtimeCtx)
|
||||
|
||||
// Passkey ceremony routes — PUBLIC (called by the browser extension from the
|
||||
// web.whatsapp.com origin, gated only by an opaque ephemeral token).
|
||||
passkey_handler.RegisterRoutes(r, whatsmeowService)
|
||||
|
||||
routes.NewRouter(
|
||||
auth_middleware.NewMiddleware(config, instanceService),
|
||||
instance_handler.NewInstanceHandler(instanceService, config),
|
||||
user_handler.NewUserHandler(userService),
|
||||
send_handler.NewSendHandler(sendMessageService),
|
||||
message_handler.NewMessageHandler(messageService),
|
||||
chat_handler.NewChatHandler(chatService),
|
||||
group_handler.NewGroupHandler(groupService),
|
||||
call_handler.NewCallHandler(callService),
|
||||
community_handler.NewCommunityHandler(communityService),
|
||||
label_handler.NewLabelHandler(labelService),
|
||||
newsletter_handler.NewNewsletterHandler(newsletterService),
|
||||
pollHandler,
|
||||
server_handler.NewServerHandler(version),
|
||||
).AssignRoutes(r)
|
||||
|
||||
if config.ConnectOnStartup {
|
||||
go whatsmeowService.ConnectOnStartup(config.ClientName)
|
||||
}
|
||||
|
||||
r.GET("/ws", func(c *gin.Context) {
|
||||
token := c.Query("token")
|
||||
instanceId := c.Query("instanceId")
|
||||
|
||||
if token != config.GlobalApiKey {
|
||||
logger.LogError("Token inválido: %s", token)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
websocket_producer.ServeWs(c.Writer, c.Request, instanceId, websocketProducer)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func migrate(db *gorm.DB) {
|
||||
err := db.AutoMigrate(&instance_model.Instance{}, &message_model.Message{}, &label_model.Label{})
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func initAuthDB(config *config.Config) (*sql.DB, string, error) {
|
||||
if config.PostgresAuthDB != "" {
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
ex, err := os.Executable()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
exPath := filepath.Dir(ex)
|
||||
|
||||
dbDirectory := exPath + "/dbdata"
|
||||
_, err = os.Stat(dbDirectory)
|
||||
if os.IsNotExist(err) {
|
||||
errDir := os.MkdirAll(dbDirectory, 0751)
|
||||
if errDir != nil {
|
||||
panic("Could not create dbdata directory")
|
||||
}
|
||||
}
|
||||
|
||||
db, err := sql.Open("sqlite", exPath+"/dbdata/users.db?_pragma=foreign_keys(1)&_busy_timeout=3000")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return db, exPath, nil
|
||||
}
|
||||
|
||||
func initPostgresAuthDB(config *config.Config) (*sql.DB, error) {
|
||||
if config.PostgresAuthDB == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err := config.EnsureDBExists(config.PostgresAuthDB); err != nil {
|
||||
logger.LogWarn("Auto-setup auth DB failed (will try connecting anyway): %v", err)
|
||||
}
|
||||
|
||||
db, err := sql.Open("postgres", config.PostgresAuthDB)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erro ao conectar ao banco AUTH PostgreSQL: %v", err)
|
||||
}
|
||||
|
||||
// Configurar pool de conexões para evitar conexões ociosas não fechadas
|
||||
db.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente
|
||||
db.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool
|
||||
db.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts
|
||||
db.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto
|
||||
|
||||
err = db.Ping()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erro ao pingar banco AUTH PostgreSQL: %v", err)
|
||||
}
|
||||
|
||||
logger.LogInfo("Conectado ao banco AUTH PostgreSQL com pool configurado")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// @title Evolution GO
|
||||
// @version 1.0
|
||||
// @description Evolution GO - whatsmeow
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if *devMode {
|
||||
err := godotenv.Load(".env")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
cfg := config.Load()
|
||||
|
||||
logger.LogInfo("Starting Evolution GO version %s", version)
|
||||
|
||||
startTime := time.Now()
|
||||
|
||||
db, err := cfg.CreateUsersDB()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Inicializar PostgreSQL AUTH
|
||||
authDB, err := initPostgresAuthDB(cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if authDB != nil {
|
||||
defer authDB.Close()
|
||||
}
|
||||
|
||||
// Manter inicialização do SQLite
|
||||
sqliteDB, exPath, err := initAuthDB(cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if sqliteDB != nil {
|
||||
defer sqliteDB.Close()
|
||||
}
|
||||
|
||||
migrate(db)
|
||||
|
||||
// Initialize core DB + license runtime
|
||||
core.SetDB(db)
|
||||
if err := core.MigrateDB(); err != nil {
|
||||
log.Fatal("Failed to migrate runtime_configs: ", err)
|
||||
}
|
||||
tier := "evolution-go"
|
||||
runtimeCtx := core.InitializeRuntime(tier, version, cfg.GlobalApiKey)
|
||||
|
||||
var conn *amqp.Connection
|
||||
|
||||
if cfg.AmqpUrl != "" {
|
||||
logger.LogInfo("Attempting to connect to RabbitMQ...")
|
||||
|
||||
// Create connection with heartbeat to prevent timeouts
|
||||
amqpConfig := amqp.Config{
|
||||
Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds
|
||||
Locale: "en_US",
|
||||
}
|
||||
|
||||
conn, err = amqp.DialConfig(cfg.AmqpUrl, amqpConfig)
|
||||
if err != nil {
|
||||
logger.LogError("Failed to connect to RabbitMQ, err: %v", err)
|
||||
logger.LogInfo("RabbitMQ producer will be created with reconnection capability")
|
||||
} else {
|
||||
logger.LogInfo("Successfully connected to RabbitMQ with heartbeat enabled")
|
||||
defer func(conn *amqp.Connection) {
|
||||
err := conn.Close()
|
||||
if err != nil {
|
||||
logger.LogError("Failed to close RabbitMQ connection, err: %v", err)
|
||||
}
|
||||
}(conn)
|
||||
}
|
||||
} else {
|
||||
logger.LogInfo("RabbitMQ URL not configured, skipping RabbitMQ connection")
|
||||
}
|
||||
|
||||
r := setupRouter(db, authDB, sqliteDB, cfg, conn, exPath, runtimeCtx)
|
||||
|
||||
// Graceful shutdown with heartbeat
|
||||
heartbeatCtx, heartbeatCancel := context.WithCancel(context.Background())
|
||||
defer heartbeatCancel()
|
||||
|
||||
core.StartHeartbeat(heartbeatCtx, runtimeCtx, startTime)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + os.Getenv("SERVER_PORT"),
|
||||
Handler: r,
|
||||
}
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
go func() {
|
||||
logger.LogInfo("Iniciando servidor na porta %s", os.Getenv("SERVER_PORT"))
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
<-quit
|
||||
logger.LogInfo("[SHUTDOWN] Signal received, shutting down...")
|
||||
|
||||
// Stop heartbeat loop
|
||||
heartbeatCancel()
|
||||
|
||||
core.Shutdown(runtimeCtx)
|
||||
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer shutdownCancel()
|
||||
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
logger.LogError("[SHUTDOWN] Server forced to shutdown: %v", err)
|
||||
}
|
||||
|
||||
logger.LogInfo("[SHUTDOWN] Server exited")
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
# Evolution GO - Configuração de Ambiente
|
||||
# Copie este arquivo para .env e ajuste conforme necessário
|
||||
|
||||
# ========================================
|
||||
# CONFIGURAÇÕES OBRIGATÓRIAS
|
||||
# ========================================
|
||||
|
||||
# Porta do servidor
|
||||
SERVER_PORT=4000
|
||||
|
||||
# Nome do cliente/instância
|
||||
CLIENT_NAME=evolution
|
||||
|
||||
# Chave de API (OBRIGATÓRIO - Use uma chave forte e única)
|
||||
GLOBAL_API_KEY=sua-chave-api-segura-aqui-uuid-recomendado
|
||||
|
||||
# ========================================
|
||||
# BANCO DE DADOS
|
||||
# ========================================
|
||||
|
||||
# PostgreSQL (RECOMENDADO para produção)
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable
|
||||
|
||||
# Salvar mensagens no banco de dados
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
|
||||
# ========================================
|
||||
# LOGS E DEBUG
|
||||
# ========================================
|
||||
|
||||
# Nível de debug do WhatsApp (INFO, DEBUG, ERROR)
|
||||
WADEBUG=INFO
|
||||
|
||||
# Tipo de log (console, file)
|
||||
LOGTYPE=console
|
||||
|
||||
# Diretório de logs
|
||||
LOG_DIRECTORY=/app/logs
|
||||
|
||||
# Tamanho máximo do arquivo de log em MB
|
||||
LOG_MAX_SIZE=100
|
||||
|
||||
# Número máximo de arquivos de backup
|
||||
LOG_MAX_BACKUPS=5
|
||||
|
||||
# Dias de retenção dos logs
|
||||
LOG_MAX_AGE=30
|
||||
|
||||
# Comprimir logs antigos
|
||||
LOG_COMPRESS=true
|
||||
|
||||
# ========================================
|
||||
# CONEXÃO
|
||||
# ========================================
|
||||
|
||||
# Conectar automaticamente ao iniciar
|
||||
CONNECT_ON_STARTUP=false
|
||||
|
||||
# Enviar arquivos via webhook
|
||||
WEBHOOK_FILES=true
|
||||
|
||||
# Nome do sistema operacional
|
||||
OS_NAME=Linux
|
||||
|
||||
# ========================================
|
||||
# EVENTOS E WEBHOOKS
|
||||
# ========================================
|
||||
|
||||
# URL do webhook para receber eventos
|
||||
WEBHOOK_URL=
|
||||
|
||||
# RabbitMQ
|
||||
AMQP_URL=
|
||||
AMQP_GLOBAL_ENABLED=false
|
||||
AMQP_GLOBAL_EVENTS=
|
||||
AMQP_SPECIFIC_EVENTS=
|
||||
|
||||
# NATS
|
||||
NATS_URL=
|
||||
NATS_GLOBAL_ENABLED=false
|
||||
NATS_GLOBAL_EVENTS=
|
||||
|
||||
# Ignorar eventos de grupos
|
||||
EVENT_IGNORE_GROUP=false
|
||||
|
||||
# Ignorar eventos de status
|
||||
EVENT_IGNORE_STATUS=true
|
||||
|
||||
# ========================================
|
||||
# ARMAZENAMENTO DE MÍDIA (MinIO/S3)
|
||||
# ========================================
|
||||
|
||||
MINIO_ENABLED=false
|
||||
MINIO_ENDPOINT=
|
||||
MINIO_ACCESS_KEY=
|
||||
MINIO_SECRET_KEY=
|
||||
MINIO_BUCKET=
|
||||
MINIO_USE_SSL=false
|
||||
MINIO_REGION=
|
||||
|
||||
# ========================================
|
||||
# PROXY (Opcional)
|
||||
# ========================================
|
||||
|
||||
PROXY_HOST=
|
||||
PROXY_PORT=
|
||||
PROXY_USERNAME=
|
||||
PROXY_PASSWORD=
|
||||
|
||||
# ========================================
|
||||
# RECURSOS ADICIONAIS
|
||||
# ========================================
|
||||
|
||||
# API de conversão de áudio
|
||||
API_AUDIO_CONVERTER=
|
||||
API_AUDIO_CONVERTER_KEY=
|
||||
|
||||
# Número máximo de tentativas de QR Code
|
||||
QRCODE_MAX_COUNT=5
|
||||
|
||||
# Verificar se o usuário existe antes de enviar mensagem
|
||||
CHECK_USER_EXISTS=true
|
||||
|
||||
# Versão do WhatsApp (opcional - deixe vazio para usar a padrão)
|
||||
WHATSAPP_VERSION_MAJOR=
|
||||
WHATSAPP_VERSION_MINOR=
|
||||
WHATSAPP_VERSION_PATCH=
|
||||
@@ -0,0 +1,144 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
evolution-go:
|
||||
image: evoapicloud/evolution-go:latest
|
||||
container_name: evolution-go
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "4000:4000"
|
||||
environment:
|
||||
# Servidor
|
||||
SERVER_PORT: 4000
|
||||
CLIENT_NAME: "evolution"
|
||||
|
||||
# Segurança
|
||||
GLOBAL_API_KEY: "sua-chave-api-segura-aqui"
|
||||
|
||||
# Banco de Dados PostgreSQL
|
||||
POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable"
|
||||
POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable"
|
||||
DATABASE_SAVE_MESSAGES: "true"
|
||||
|
||||
# Logs e Debug
|
||||
WADEBUG: "DEBUG"
|
||||
LOGTYPE: "console"
|
||||
LOG_DIRECTORY: "/app/logs"
|
||||
LOG_MAX_SIZE: "100"
|
||||
LOG_MAX_BACKUPS: "5"
|
||||
LOG_MAX_AGE: "30"
|
||||
LOG_COMPRESS: "true"
|
||||
|
||||
# Conexão
|
||||
CONNECT_ON_STARTUP: "false"
|
||||
WEBHOOK_FILES: "true"
|
||||
|
||||
# Sistema
|
||||
OS_NAME: "Linux"
|
||||
|
||||
# Webhook
|
||||
WEBHOOK_URL: "https://seu-webhook.com/endpoint"
|
||||
|
||||
# RabbitMQ
|
||||
AMQP_URL: "amqp://admin:admin@rabbitmq:5672/default"
|
||||
AMQP_GLOBAL_ENABLED: "true"
|
||||
AMQP_GLOBAL_EVENTS: "messages.upsert,messages.update,connection.update"
|
||||
AMQP_SPECIFIC_EVENTS: ""
|
||||
|
||||
# NATS
|
||||
NATS_URL: "nats://nats:4222"
|
||||
NATS_GLOBAL_ENABLED: "false"
|
||||
NATS_GLOBAL_EVENTS: ""
|
||||
|
||||
# MinIO
|
||||
MINIO_ENABLED: "true"
|
||||
MINIO_ENDPOINT: "minio:9000"
|
||||
MINIO_ACCESS_KEY: "minioadmin"
|
||||
MINIO_SECRET_KEY: "minioadmin"
|
||||
MINIO_BUCKET: "evolution-media"
|
||||
MINIO_USE_SSL: "false"
|
||||
MINIO_REGION: "us-east-1"
|
||||
|
||||
# Eventos
|
||||
EVENT_IGNORE_GROUP: "false"
|
||||
EVENT_IGNORE_STATUS: "true"
|
||||
|
||||
# QR Code
|
||||
QRCODE_MAX_COUNT: "5"
|
||||
|
||||
# Verificação de Usuário
|
||||
CHECK_USER_EXISTS: "true"
|
||||
|
||||
volumes:
|
||||
- evolution_data:/app/dbdata
|
||||
- evolution_logs:/app/logs
|
||||
networks:
|
||||
- evolution_network
|
||||
depends_on:
|
||||
- postgres
|
||||
- rabbitmq
|
||||
- minio
|
||||
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: evolution-postgres
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
|
||||
networks:
|
||||
- evolution_network
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:3-management-alpine
|
||||
container_name: evolution-rabbitmq
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: admin
|
||||
RABBITMQ_DEFAULT_PASS: admin
|
||||
RABBITMQ_DEFAULT_VHOST: default
|
||||
ports:
|
||||
- "5672:5672"
|
||||
- "15672:15672"
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
networks:
|
||||
- evolution_network
|
||||
|
||||
minio:
|
||||
image: minio/minio:latest
|
||||
container_name: evolution-minio
|
||||
restart: unless-stopped
|
||||
command: server /data --console-address ":9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: minioadmin
|
||||
MINIO_ROOT_PASSWORD: minioadmin
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
networks:
|
||||
- evolution_network
|
||||
|
||||
volumes:
|
||||
evolution_data:
|
||||
driver: local
|
||||
evolution_logs:
|
||||
driver: local
|
||||
postgres_data:
|
||||
driver: local
|
||||
rabbitmq_data:
|
||||
driver: local
|
||||
minio_data:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
evolution_network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,102 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
evolution_go:
|
||||
image: evoapicloud/evolution-go:latest
|
||||
networks:
|
||||
- network_public
|
||||
environment:
|
||||
# Servidor
|
||||
SERVER_PORT: 4000
|
||||
CLIENT_NAME: "evolution"
|
||||
|
||||
# Segurança (OBRIGATÓRIO)
|
||||
GLOBAL_API_KEY: "sua-chave-api-segura-aqui"
|
||||
|
||||
# Banco de Dados PostgreSQL (RECOMENDADO)
|
||||
POSTGRES_AUTH_DB: "postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable"
|
||||
POSTGRES_USERS_DB: "postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable"
|
||||
DATABASE_SAVE_MESSAGES: "false"
|
||||
|
||||
# Logs e Debug
|
||||
WADEBUG: "INFO"
|
||||
LOGTYPE: "console"
|
||||
LOG_DIRECTORY: "/app/logs"
|
||||
LOG_MAX_SIZE: "100"
|
||||
LOG_MAX_BACKUPS: "5"
|
||||
LOG_MAX_AGE: "30"
|
||||
LOG_COMPRESS: "true"
|
||||
|
||||
# Conexão
|
||||
CONNECT_ON_STARTUP: "true"
|
||||
WEBHOOK_FILES: "true"
|
||||
|
||||
# Sistema
|
||||
OS_NAME: "Linux"
|
||||
|
||||
# Conversor de Áudio (Opcional)
|
||||
API_AUDIO_CONVERTER: ""
|
||||
API_AUDIO_CONVERTER_KEY: ""
|
||||
|
||||
# Proxy (Opcional)
|
||||
PROXY_HOST: ""
|
||||
PROXY_PORT: ""
|
||||
PROXY_USERNAME: ""
|
||||
PROXY_PASSWORD: ""
|
||||
|
||||
# RabbitMQ (Opcional)
|
||||
AMQP_URL: ""
|
||||
AMQP_GLOBAL_ENABLED: "false"
|
||||
AMQP_GLOBAL_EVENTS: ""
|
||||
|
||||
# NATS (Opcional)
|
||||
NATS_URL: ""
|
||||
NATS_GLOBAL_ENABLED: "false"
|
||||
|
||||
# Eventos
|
||||
EVENT_IGNORE_GROUP: "false"
|
||||
EVENT_IGNORE_STATUS: "true"
|
||||
|
||||
# MinIO/S3 (Opcional)
|
||||
MINIO_ENABLED: "false"
|
||||
MINIO_ENDPOINT: ""
|
||||
MINIO_ACCESS_KEY: ""
|
||||
MINIO_SECRET_KEY: ""
|
||||
MINIO_BUCKET: ""
|
||||
MINIO_USE_SSL: "false"
|
||||
|
||||
volumes:
|
||||
- evolution_go_data:/app/dbdata
|
||||
- evolution_go_logs:/app/logs
|
||||
|
||||
deploy:
|
||||
replicas: 1
|
||||
placement:
|
||||
constraints:
|
||||
- node.role == manager
|
||||
restart_policy:
|
||||
condition: on-failure
|
||||
delay: 5s
|
||||
max_attempts: 3
|
||||
labels:
|
||||
# Traefik Labels (ajuste conforme necessário)
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.evolution_go.rule=Host(`evolution.seudominio.com`)
|
||||
- traefik.http.routers.evolution_go.entrypoints=websecure
|
||||
- traefik.http.routers.evolution_go.tls.certresolver=letsencryptresolver
|
||||
- traefik.http.routers.evolution_go.service=evolution_go
|
||||
- traefik.http.services.evolution_go.loadbalancer.server.port=4000
|
||||
- traefik.http.services.evolution_go.loadbalancer.passHostHeader=true
|
||||
|
||||
volumes:
|
||||
evolution_go_data:
|
||||
external: true
|
||||
name: evolution_go_data
|
||||
evolution_go_logs:
|
||||
external: true
|
||||
name: evolution_go_logs
|
||||
|
||||
networks:
|
||||
network_public:
|
||||
external: true
|
||||
name: network_public
|
||||
@@ -0,0 +1,96 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
evolution-go:
|
||||
image: evoapicloud/evolution-go:latest
|
||||
container_name: evolution-go
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "4000:4000"
|
||||
environment:
|
||||
# Servidor
|
||||
SERVER_PORT: 4000
|
||||
CLIENT_NAME: "evolution"
|
||||
|
||||
# Segurança (OBRIGATÓRIO)
|
||||
GLOBAL_API_KEY: "sua-chave-api-segura-aqui"
|
||||
|
||||
# Banco de Dados PostgreSQL (RECOMENDADO)
|
||||
POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable"
|
||||
POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable"
|
||||
DATABASE_SAVE_MESSAGES: "false"
|
||||
|
||||
# Logs e Debug
|
||||
WADEBUG: "INFO"
|
||||
LOGTYPE: "console"
|
||||
LOG_DIRECTORY: "/app/logs"
|
||||
LOG_MAX_SIZE: "100"
|
||||
LOG_MAX_BACKUPS: "5"
|
||||
LOG_MAX_AGE: "30"
|
||||
LOG_COMPRESS: "true"
|
||||
|
||||
# Conexão
|
||||
CONNECT_ON_STARTUP: "false"
|
||||
WEBHOOK_FILES: "true"
|
||||
|
||||
# Sistema
|
||||
OS_NAME: "Linux"
|
||||
|
||||
# Eventos (Opcionais)
|
||||
WEBHOOK_URL: ""
|
||||
AMQP_URL: ""
|
||||
AMQP_GLOBAL_ENABLED: "false"
|
||||
NATS_URL: ""
|
||||
NATS_GLOBAL_ENABLED: "false"
|
||||
|
||||
# Armazenamento de Mídia (Opcional)
|
||||
MINIO_ENABLED: "false"
|
||||
|
||||
# Proxy (Opcional)
|
||||
PROXY_HOST: ""
|
||||
PROXY_PORT: ""
|
||||
PROXY_USERNAME: ""
|
||||
PROXY_PASSWORD: ""
|
||||
|
||||
# Eventos
|
||||
EVENT_IGNORE_GROUP: "false"
|
||||
EVENT_IGNORE_STATUS: "true"
|
||||
|
||||
# QR Code
|
||||
QRCODE_MAX_COUNT: "5"
|
||||
|
||||
volumes:
|
||||
- evolution_data:/app/dbdata
|
||||
- evolution_logs:/app/logs
|
||||
networks:
|
||||
- evolution_network
|
||||
depends_on:
|
||||
- postgres
|
||||
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: evolution-postgres
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
|
||||
networks:
|
||||
- evolution_network
|
||||
|
||||
volumes:
|
||||
evolution_data:
|
||||
driver: local
|
||||
evolution_logs:
|
||||
driver: local
|
||||
postgres_data:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
evolution_network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Script de inicialização dos bancos de dados Evolution GO
|
||||
|
||||
-- Criar database para autenticação
|
||||
CREATE DATABASE evogo_auth;
|
||||
|
||||
-- Criar database para dados de usuários
|
||||
CREATE DATABASE evogo_users;
|
||||
|
||||
-- Mensagem de confirmação
|
||||
SELECT 'Databases evogo_auth e evogo_users criados com sucesso!' as message;
|
||||
@@ -0,0 +1,89 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
evolution_go:
|
||||
image: intrategica/evg:1
|
||||
networks:
|
||||
- papi
|
||||
environment:
|
||||
# Servidor
|
||||
SERVER_PORT: 3300
|
||||
CLIENT_NAME: "evolution"
|
||||
|
||||
# Segurança (ALTERE a chave abaixo)
|
||||
GLOBAL_API_KEY: "429683C4C977415CAAFCCE10F7D57E11"
|
||||
|
||||
# Banco de Dados PostgreSQL (serviço 'postgres' já existente)
|
||||
POSTGRES_AUTH_DB: "postgresql://pastorini:pastorini123@postgres:5432/pastorini_api?sslmode=disable"
|
||||
POSTGRES_USERS_DB: "postgresql://pastorini:pastorini123@postgres:5432/pastorini_api?sslmode=disable"
|
||||
POSTGRES_HOST: "postgres"
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_USER: "pastorini"
|
||||
POSTGRES_PASSWORD: "pastorini123"
|
||||
POSTGRES_DB: "pastorini_api"
|
||||
DATABASE_SAVE_MESSAGES: "false"
|
||||
|
||||
# Logs e Debug
|
||||
WADEBUG: "INFO"
|
||||
LOGTYPE: "console"
|
||||
LOG_DIRECTORY: "/app/logs"
|
||||
LOG_MAX_SIZE: "100"
|
||||
LOG_MAX_BACKUPS: "5"
|
||||
LOG_MAX_AGE: "30"
|
||||
LOG_COMPRESS: "true"
|
||||
|
||||
# Conexão
|
||||
CONNECT_ON_STARTUP: "true"
|
||||
WEBHOOKFILES: "true"
|
||||
|
||||
# Sistema
|
||||
OS_NAME: "Linux"
|
||||
|
||||
# Eventos
|
||||
EVENT_IGNORE_GROUP: "false"
|
||||
EVENT_IGNORE_STATUS: "true"
|
||||
|
||||
# MinIO/S3 (Opcional)
|
||||
MINIO_ENABLED: "false"
|
||||
MINIO_ENDPOINT: ""
|
||||
MINIO_ACCESS_KEY: ""
|
||||
MINIO_SECRET_KEY: ""
|
||||
MINIO_BUCKET: ""
|
||||
MINIO_USE_SSL: "false"
|
||||
|
||||
volumes:
|
||||
- evolution_go_data:/app/dbdata
|
||||
- evolution_go_logs:/app/logs
|
||||
|
||||
deploy:
|
||||
replicas: 1
|
||||
placement:
|
||||
constraints:
|
||||
- node.role == manager
|
||||
restart_policy:
|
||||
condition: on-failure
|
||||
delay: 5s
|
||||
max_attempts: 3
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=papi
|
||||
- traefik.http.routers.evocrm.rule=Host(`evocrm.intrategica.com.br`)
|
||||
- traefik.http.routers.evocrm.entrypoints=websecure
|
||||
- traefik.http.routers.evocrm.tls=true
|
||||
- traefik.http.routers.evocrm.tls.certresolver=letsencryptresolver
|
||||
- traefik.http.routers.evocrm.service=evocrm
|
||||
- traefik.http.services.evocrm.loadbalancer.server.port=3300
|
||||
- traefik.http.services.evocrm.loadbalancer.passHostHeader=true
|
||||
|
||||
volumes:
|
||||
evolution_go_data:
|
||||
external: true
|
||||
name: evolution_go_data
|
||||
evolution_go_logs:
|
||||
external: true
|
||||
name: evolution_go_logs
|
||||
|
||||
networks:
|
||||
papi:
|
||||
external: true
|
||||
name: papi
|
||||
+14329
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,98 @@
|
||||
# Arquitetura do Sistema — EvoGO
|
||||
|
||||
## 1. Visão Geral
|
||||
|
||||
O **EvoGO** é uma distribuição independente da Evolution Go, uma API de alto desempenho construída em Go para controle e integração com instâncias do WhatsApp Web via protocolo WebSocket/Noise utilizando a biblioteca `whatsmeow`.
|
||||
|
||||
A aplicação atua como um gateway REST e Websocket/Eventos, permitindo que sistemas corporativos e aplicações SaaS gerenciem instâncias do WhatsApp, enviem mensagens de texto, mídias, stickers, listas interativas, botões, realizem consultas a grupos e processem webhooks em tempo real.
|
||||
|
||||
---
|
||||
|
||||
## 2. Diagrama de Arquitetura
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ Clientes Externos │
|
||||
│ (Sistemas Web, CRMs, n8n, Agentes IA) │
|
||||
└───────────────────────────┬────────────────────────────┘
|
||||
│ HTTP REST / WebSocket
|
||||
▼
|
||||
┌───────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ EvoGO Core │
|
||||
│ │
|
||||
│ ┌─────────────────────┐ ┌───────────────────────┐ ┌─────────────────────┐ │
|
||||
│ │ Rotas Gin HTTP │──▶│ Auth / License Check │──▶│ Handlers (pkg/*) │ │
|
||||
│ │ (pkg/routes) │ │ (pkg/core) │ │ (instance, msg, …) │ │
|
||||
│ └─────────────────────┘ └───────────────────────┘ └──────────┬──────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌─────────────────────┐ │
|
||||
│ │ Services de Negócio │ │
|
||||
│ │ (pkg/*/service) │ │
|
||||
│ └──────────┬──────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌─────────────────────┐ │
|
||||
│ │ Whatsmeow Service │ │
|
||||
│ │ (Handshake/Versão) │ │
|
||||
│ └──────────┬──────────┘ │
|
||||
└────────────────────────────────────────────────────────────────────┼──────────────┘
|
||||
│
|
||||
┌───────────────────────────────────────────┴─────────────────────────┐
|
||||
│ │
|
||||
▼ ▼
|
||||
┌───────────────────────────────────────┐ ┌───────────────────────────────────────┐
|
||||
│ WhatsApp Web Servers │ │ Bancos e Mensageria Local │
|
||||
│ (Noise Protocol / WebSocket) │ │ - SQLite / PostgreSQL (Sessões) │
|
||||
│ - Handshake com store.SetWAVersion│ │ - Redis / Caches de Versão / MinIO │
|
||||
│ - Pairing Code e QR Code │ │ - RabbitMQ / NATS / Webhooks │
|
||||
└───────────────────────────────────────┘ └───────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Módulos e Componentes Principais
|
||||
|
||||
### 3.1. `cmd/evolution-go/main.go`
|
||||
- Inicializa as variáveis de ambiente e configurações globais (`pkg/config`).
|
||||
- Inicializa a conexão com o banco de dados (SQLite ou PostgreSQL via GORM).
|
||||
- Inicializa os serviços de mensageria (RabbitMQ, NATS, Webhooks e WebSockets).
|
||||
- Configura o mecanismo de licenciamento e heartbeat (`pkg/core`).
|
||||
- Inicia o servidor HTTP Gin na porta configurada (padrão: 8080).
|
||||
|
||||
### 3.2. `pkg/core/`
|
||||
- **Validação de Runtime e Licença:** Contém a verificação de ativação via `EVOLUTION_OPERATOR_EMAIL` ou `GLOBAL_API_KEY`.
|
||||
- **Middleware de Proteção:** Intercepta rotas e garante que endpoints da API retornem 503 caso o serviço ainda não esteja licenciado, permitindo apenas rotas administrativas de ativação (`/license/*`).
|
||||
|
||||
### 3.3. `pkg/whatsmeow/service/`
|
||||
- **Abstração do Whatsmeow:** Gerencia a criação do `whatsmeow.Client`, mapeia manipuladores de eventos (`EventHandler`) para mensagens, status e presença.
|
||||
- **Handshake e Resolução de Versão:** Responsável por evitar o erro `Client outdated (405)`. Realiza busca da versão do WhatsApp Web em `https://web.whatsapp.com/sw.js` com cache de 1 hora, injeta User-Agent padronizado e aplica via `store.SetWAVersion` e `store.BaseClientPayload.UserAgent.AppVersion`.
|
||||
|
||||
### 3.4. `pkg/instance/`
|
||||
- Controla o ciclo de vida de cada número de WhatsApp conectado (instância).
|
||||
- Salva o estado da conexão (`connecting`, `open`, `close`, `refused`).
|
||||
- Permite pareamento via QR Code (Base64) ou código de pareamento numérico (Pairing Code).
|
||||
|
||||
### 3.5. `pkg/sendMessage/`
|
||||
- Implementa endpoints de envio com suporte a texto, áudios convertidos (opus/ogg), imagens, vídeos, documentos PDF com prévia/thumbnail rasterizada via `poppler-utils` (`pdftoppm`), enquetes, contatos e mensagens interativas (botões e listas).
|
||||
|
||||
### 3.6. `manager/dist/`
|
||||
- Console administrativo em frontend SPA (React/Vite) servido diretamente pelo binário em `/manager`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Persistência de Dados
|
||||
|
||||
1. **Estado das Instâncias e Mensagens da API:**
|
||||
- Suporta SQLite (`evolution.db`) para ambientes simples ou PostgreSQL para ambientes de alta concorrência.
|
||||
2. **Sessões Criptográficas do WhatsApp:**
|
||||
- O `whatsmeow` armazena chaves de sessão, tokens de pré-chave, registros de identidade e metadados de autenticação nas tabelas de schema do whatsmeow (`whatsmeow_device`, `whatsmeow_identity_keys`, etc.).
|
||||
- As migrações de schema do whatsmeow (ex: v14 para v16) são executadas automaticamente pela biblioteca na abertura do container.
|
||||
|
||||
---
|
||||
|
||||
## 5. Práticas para Manutenção por Agentes de IA
|
||||
|
||||
- Ao implementar novas rotas, mantenha a separação em camadas: `handler` (validação e parsing HTTP) -> `service` (regras de negócio e chamadas whatsmeow) -> `repository` (interação com banco).
|
||||
- Nunca modifique métodos do `pkg/core/` que alterem a verificação de licenciamento.
|
||||
- Nunca adicione chamadas diretas de rede sem timeout configurado.
|
||||
@@ -0,0 +1,128 @@
|
||||
# Guia de Compilação e Publicação (BUILD_AND_RELEASE.md)
|
||||
|
||||
Este documento descreve detalhadamente o processo de compilação da aplicação, construção das imagens Docker, convenções de tags e fluxo de publicação em registry próprio.
|
||||
|
||||
---
|
||||
|
||||
## 1. Requisitos de Ambiente
|
||||
|
||||
- **Go:** Versão Go 1.25+ ou 1.26+ (conforme exigido pela versão do `whatsmeow` em uso).
|
||||
- **CGO:** Habilitado (`CGO_ENABLED=1`) para compilação com suporte a drivers nativos e processamento de imagens/PDFs.
|
||||
- **Bibliotecas nativas de sistema (Alpine/Debian):**
|
||||
- `libjpeg-turbo-dev`
|
||||
- `libwebp-dev`
|
||||
- `poppler-utils` (`pdftoppm` para geração de thumbnails de PDF)
|
||||
- `ffmpeg` (para conversão e manipulação de mídias de áudio/vídeo)
|
||||
- **Docker:** Engine 24.0+ com plugin `buildx`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Compilação Local
|
||||
|
||||
### Compilar binário para teste:
|
||||
```bash
|
||||
# Definir versão de compilação
|
||||
VERSION=$(cat VERSION 2>/dev/null || echo "dev")
|
||||
|
||||
# Compilar com tags de linkagem
|
||||
CGO_ENABLED=1 go build -ldflags "-X main.version=${VERSION}" -o build/evolution-go ./cmd/evolution-go
|
||||
```
|
||||
|
||||
### Executar a suite de testes:
|
||||
```bash
|
||||
# Executar todos os testes
|
||||
go test -v ./...
|
||||
|
||||
# Executar testes com detecção de data race
|
||||
go test -race ./...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Construção da Imagem Docker
|
||||
|
||||
A construção utiliza Dockerfile multi-stage otimizado:
|
||||
- **Estágio 1 (`build`):** Imagem base Go Alpine com compilador, dependências C e ferramentas de build.
|
||||
- **Estágio 2 (`final`):** Imagem final Alpine mínima contendo apenas os binários, dependências de runtime (`ffmpeg`, `poppler-utils`, `libwebp`), assets estáticos do manager (`manager/dist`) e timezone.
|
||||
|
||||
### Comando de Build Manual:
|
||||
```bash
|
||||
# Exemplo para versão 0.7.2 com SHA do commit
|
||||
COMMIT_SHA=$(git rev-parse --short HEAD)
|
||||
VERSION=$(cat VERSION)
|
||||
|
||||
docker build \
|
||||
--build-arg VERSION="${VERSION}-${COMMIT_SHA}" \
|
||||
-t evogo:${VERSION}-${COMMIT_SHA} \
|
||||
-t evogo:latest \
|
||||
-f Dockerfile .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Estratégia de Registry e Publicação
|
||||
|
||||
### Registries Alvo:
|
||||
1. **Gitea Package Registry (Recomendado):**
|
||||
- Endereço: `git.jf.eng.br`
|
||||
- Imagem: `git.jf.eng.br/jfeng/evogo`
|
||||
- Autenticação: Utiliza o token padrão do Gitea Actions (`secrets.GITEA_TOKEN`) ou credenciais configuradas.
|
||||
2. **Registry Externo (se configurado):**
|
||||
- Variáveis: `REGISTRY_USER` e `REGISTRY_TOKEN`.
|
||||
|
||||
### Convenções de Tags:
|
||||
- **Tag Imutável por Commit:** `git.jf.eng.br/jfeng/evogo:${VERSION}-${COMMIT_SHA}` (ex: `0.7.2-9337afc`)
|
||||
- **Tag de Versão Semântica:** `git.jf.eng.br/jfeng/evogo:${VERSION}` (ex: `0.7.2`)
|
||||
- **Tag Flutuante Estável:** `git.jf.eng.br/jfeng/evogo:latest` (atualizada **somente** após aprovação em `maintained-stable`)
|
||||
- **Tag de Integração:** `git.jf.eng.br/jfeng/evogo:develop`
|
||||
|
||||
---
|
||||
|
||||
## 5. Pipeline Automatizado no Gitea Actions
|
||||
|
||||
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
|
||||
|
||||
1. **Push em `maintained-stable`:** build da imagem (`linux/amd64`), teste de
|
||||
inicialização do binário e scan Trivy (HIGH/CRITICAL, não bloqueante).
|
||||
**Não publica.**
|
||||
2. **Push de tag `v<versão>` (release aprovado):** mesmo build/teste/scan e
|
||||
publicação de:
|
||||
- `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
|
||||
- `git.jf.eng.br/jfeng/evogo:<versão>`
|
||||
3. **`workflow_dispatch`:** publica apenas com `publish_image=true`; `:latest`
|
||||
só com `promote_latest=true`.
|
||||
|
||||
### Gerar um release
|
||||
|
||||
```bash
|
||||
git checkout maintained-develop && git pull
|
||||
git tag -a v0.7.2-evogo.1 -m "EvoGO 0.7.2-evogo.1"
|
||||
git push origin v0.7.2-evogo.1 # dispara o build e a publicação
|
||||
```
|
||||
|
||||
### Usar no docker-compose
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
image: git.jf.eng.br/jfeng/evogo:0.7.2-evogo.1
|
||||
```
|
||||
|
||||
Como o pacote é privado, o host precisa de `docker login git.jf.eng.br`
|
||||
(usuário Gitea + token com escopo `read:package`) antes de `docker compose pull`.
|
||||
Para fixar exatamente o commit testado, use a tag imutável `<versão>-<sha7>`.
|
||||
|
||||
### Promover para `:latest`
|
||||
|
||||
`.gitea/workflows/promote-latest.yml` roda quando `maintained-stable` avança:
|
||||
re-etiqueta a imagem imutável do último release `v*` contido na branch
|
||||
(`<versão>-<sha7>`) como `:latest`, sem recompilar (mesmo digest).
|
||||
|
||||
```bash
|
||||
git checkout maintained-stable
|
||||
git merge --ff-only v0.7.2-evogo.1
|
||||
git push origin maintained-stable # dispara a promoção para :latest
|
||||
```
|
||||
|
||||
Rollback de `:latest`: avance/reverta `maintained-stable` para o release
|
||||
anterior e rode o workflow manualmente, ou fixe a tag de versão no compose.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Procedimento de Rollback e Recuperação (ROLLBACK.md)
|
||||
|
||||
Este documento descreve os passos operacionais para reverter rapidamente uma versão do **EvoGO** em caso de falha crítica em produção.
|
||||
|
||||
---
|
||||
|
||||
## 1. Condições de Disparo para Rollback
|
||||
|
||||
Um rollback imediato deve ser acionado nas seguintes situações:
|
||||
|
||||
1. **Rejeição em Massa pelo WhatsApp:** A taxa de erro na conexão ou pareamento ultrapassa 20% com respostas `405 Client Outdated`, `401 Unauthorized` ou `503 Service Unavailable`.
|
||||
2. **Panic ou Reinicializações Contínuas (CrashLoop):** O container do EvoGO reinicia em loop devido a erros de runtime, falhas de I/O ou vazamento crítico de memória.
|
||||
3. **Corrupção de Sessões:** Instâncias anteriormente pareadas perdem suas chaves de sessão após atualização.
|
||||
4. **Regressão de Contrato de API:** Endpoints críticos de envio de mensagens falham de forma generalizada.
|
||||
|
||||
---
|
||||
|
||||
## 2. Procedimento Operacional de Rollback
|
||||
|
||||
### Passo 1: Identificar a Última Imagem Estável Validada
|
||||
Consulte o histórico de deploys ou os registros no Gitea Package Registry.
|
||||
Exemplo:
|
||||
- Versão com falha: `git.jf.eng.br/jfeng/evogo:0.7.3-f8a9b2c`
|
||||
- Versão estável anterior: `git.jf.eng.br/jfeng/evogo:0.7.2-9337afc`
|
||||
|
||||
### Passo 2: Atualização do Container / Docker Compose
|
||||
No host de produção (ex: ZimaOS ou servidor Docker Swarm/Compose):
|
||||
|
||||
1. Edite o arquivo `docker-compose.yml`:
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
image: git.jf.eng.br/jfeng/evogo:0.7.2-9337afc # Reverter para a tag imutável estável
|
||||
```
|
||||
2. Baixe a imagem anterior e reinicie o serviço:
|
||||
```bash
|
||||
docker compose pull evolution-go
|
||||
docker compose up -d evolution-go
|
||||
```
|
||||
3. Verifique os logs de inicialização imediatamente:
|
||||
```bash
|
||||
docker compose logs -f --tail=100 evolution-go
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Considerações sobre o Banco de Dados
|
||||
|
||||
### Sessões Whatsmeow e Schemas:
|
||||
- O banco de dados armazena o schema do `whatsmeow` nas tabelas `whatsmeow_version` e associadas.
|
||||
- **Atenção:** Se a versão nova executou uma migração de schema (ex: schema v14 para v16), o downgrade da biblioteca para uma versão antiga que espere schema v14 pode falhar se não houver compatibilidade reversa.
|
||||
- **Boas Práticas de Prevenção:**
|
||||
- Sempre realize um snapshot/backup do volume do banco de dados (`/data` ou banco PostgreSQL) antes de rodar atualizações de versão de dependência.
|
||||
- Para restaurar o backup de emergência em SQLite:
|
||||
```bash
|
||||
cp /var/data/evolution.db.backup /var/data/evolution.db
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Reversão no Git
|
||||
|
||||
Caso uma branch tenha sido integrada inadvertidamente em `maintained-stable`:
|
||||
|
||||
1. **Reverta o commit de merge:**
|
||||
```bash
|
||||
git checkout maintained-stable
|
||||
git revert -m 1 <commit_do_merge> -m "revert: rollback da versão com falha"
|
||||
git push origin maintained-stable
|
||||
```
|
||||
2. **Abra uma Issue no Gitea:**
|
||||
- Descreva os sintomas observados, logs do erro, versão problemática e passos executados no rollback.
|
||||
- Rotule como `bug` e `critical`.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Diretrizes de Segurança (SECURITY.md)
|
||||
|
||||
Este documento estabelece os padrões e práticas de segurança aplicáveis ao fork **EvoGO**, em conformidade com as melhores práticas de desenvolvimento seguro e OWASP.
|
||||
|
||||
---
|
||||
|
||||
## 1. Gestão de Credenciais e Segredos
|
||||
|
||||
1. **Proibição Absoluta de Segredos no Código:**
|
||||
- Nenhum token, senha de banco de dados, chave de API (`GLOBAL_API_KEY`, `AUTHENTICATION_API_KEY`) ou chave privada SSH pode ser adicionada ao repositório git.
|
||||
- Utilize arquivos `.env` locais para desenvolvimento e injete variáveis de ambiente via Docker secrets ou docker-compose em produção.
|
||||
2. **Prevenção de Vazamento em Logs:**
|
||||
- Assegure que handlers HTTP e middlewares sanitizem cabeçalhos como `apikey`, `Authorization`, `token` e payloads de webhook antes de imprimir logs.
|
||||
- Variáveis sensíveis como chaves de sessão do WhatsApp (`noise_keys`, `prekeys`) nunca devem ser expostas em logs, mesmo com `WA_DEBUG=DEBUG`.
|
||||
3. **Controle de Acesso ao Repositório:**
|
||||
- O repositório no Gitea deve permanecer privado.
|
||||
- Apenas o proprietário e deploys autorizados possuem permissão de push.
|
||||
|
||||
---
|
||||
|
||||
## 2. Segurança de Rede e Exposição de Serviços
|
||||
|
||||
1. **Isolamento de Portas e Proxies:**
|
||||
- O Evolution Go não deve ser exposto diretamente na internet sem um proxy reverso seguro (ex: Traefik, Nginx ou Cloudflare Tunnel) com terminação SSL/TLS (HTTPS).
|
||||
- O console de gerenciamento (`/manager`) deve ter proteção adicional por IP restrito, VPN ou autenticação básica quando acessado remotamente.
|
||||
2. **Conexões com o WhatsApp:**
|
||||
- Toda comunicação entre o `whatsmeow` e os servidores do WhatsApp utiliza túneis criptografados via protocolo Noise sobre WebSocket (`wss://web.whatsapp.com/ws/chat`).
|
||||
- Quando configurado proxy HTTP/SOCKS5 para as instâncias, certifique-se de que as credenciais do proxy sejam transmitidas de forma segura e não fiquem expostas em requisições de listagem pública.
|
||||
|
||||
---
|
||||
|
||||
## 3. Verificação Contínua de Dependências
|
||||
|
||||
1. **Auditoria de Módulos Go:**
|
||||
- O pipeline do Gitea Actions deve executar verificações periódicas de vulnerabilidades conhecidas:
|
||||
```bash
|
||||
go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||
govulncheck ./...
|
||||
```
|
||||
2. **Imagens Base Atualizadas:**
|
||||
- O `Dockerfile` deve utilizar imagens Alpine e Go com patches de segurança recentes (ex: `golang:1.26.10-alpine` e `alpine:3.19.1+`).
|
||||
|
||||
---
|
||||
|
||||
## 4. Licenciamento e Proteção Legal
|
||||
|
||||
- As condições específicas da licença do Evolution Go (preservação de logotipos e avisos de direitos autorais no frontend manager) devem ser rigorosamente respeitadas.
|
||||
- Qualquer alteração nos arquivos de licença ou mecanismos de validação é estritamente proibida por diretriz arquitetural.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Política de Atualizações e Dependências (UPDATE_POLICY.md)
|
||||
|
||||
Este documento define as regras, periodicidades e critérios técnicos para aceitação, teste e incorporação de atualizações no fork **EvoGO**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Classificação das Atualizações
|
||||
|
||||
Toda atualização deve ser classificada em uma das seguintes categorias:
|
||||
|
||||
### Nível 1: Emergencial / Crítica (Hotfix)
|
||||
- **Cenários:** Queda geral de conexão do WhatsApp (ex: erro `Client outdated (405)`), vulnerabilidade de execução remota de código (RCE) ou corrupção de sessões.
|
||||
- **Janela de Ação:** Imediata.
|
||||
- **Fluxo:** Criação direta de branch `fix/<nome-do-problema>` baseada em `maintained-develop`, testes de bancada focados e geração de hotfix com deploy controlado após aprovação.
|
||||
|
||||
### Nível 2: Atualização de Dependência do WhatsApp (`whatsmeow`)
|
||||
- **Cenários:** Novas versões da biblioteca `whatsmeow` lançadas por Tulir Asokan, contendo suporte a novos recursos do protocolo do WhatsApp ou novas revisões de schema.
|
||||
- **Janela de Ação:** Semanal ou quinzenal.
|
||||
- **Regra Técnica:** Verificar se há mudanças no schema do banco (ex: v14 -> v16) e na assinatura de funções públicas (ex: `UpdateBlocklist`, `GetBlocklist`, `SetStatusMessage`).
|
||||
|
||||
### Nível 3: Sincronização Periódica com Upstream
|
||||
- **Cenários:** Novos commits na branch `main` ou `develop` do upstream oficial que trazem melhorias incrementais, novas rotas ou correções de bugs.
|
||||
- **Janela de Ação:** Quinzenal ou mensal.
|
||||
- **Fluxo:** Branch `maintenance/sync-upstream-<data>` -> PR para `maintained-develop`.
|
||||
|
||||
### Nível 4: Manutenção de Dependências Gerais (Go Modules)
|
||||
- **Cenários:** Atualização de drivers (GORM, PostgreSQL, SQLite), Gin, logger, MinIO, etc.
|
||||
- **Critério:** Atualizações de patches (`patch version`) são aceitas se os testes passarem. Atualizações de minor/major exigem análise de breaking changes.
|
||||
|
||||
---
|
||||
|
||||
## 2. Regras para Atualização da Biblioteca `whatsmeow`
|
||||
|
||||
A biblioteca `whatsmeow` é a peça central do sistema e a mais suscetível a quebras devido a mudanças nos servidores da Meta.
|
||||
|
||||
Ao atualizar a versão do `whatsmeow`:
|
||||
|
||||
1. **Investigar o histórico recente de commits do whatsmeow:**
|
||||
- Acesse o repositório oficial da biblioteca: `https://github.com/tulir/whatsmeow`.
|
||||
- Analise se houve alteração na versão mínima do Go (ex: migração para Go 1.26).
|
||||
2. **Avaliar alterações de Schema no Banco de Dados:**
|
||||
- A biblioteca whatsmeow realiza auto-migrações das tabelas do dispositivo (`device store`).
|
||||
- Verifique se novas tabelas ou colunas foram adicionadas.
|
||||
- **IMPORTANTE:** Bancos de dados em produção devem ter backup realizado antes da inicialização do novo container.
|
||||
3. **Manter a injeção dinâmica de versão de handshake:**
|
||||
- O Evolution Go deve manter a injeção em `pkg/whatsmeow/service/whatsmeow.go` (`store.SetWAVersion` e `store.BaseClientPayload.UserAgent.AppVersion`), assegurando que a versão em runtime seja respeitada mesmo que a biblioteca compilada fique temporariamente defasada.
|
||||
|
||||
---
|
||||
|
||||
## 3. Critérios de Rejeição de Atualizações
|
||||
|
||||
Uma atualização externa do upstream **DEVE SER REJEITADA OU BLOQUEADA** se:
|
||||
|
||||
- Modificar, contornar ou desativar os termos da licença Apache 2.0 / avisos de direitos autorais.
|
||||
- Adicionar dependências externas não auditadas ou binários pré-compilados proprietários sem código-fonte.
|
||||
- Quebrar retrocompatibilidade com endpoints existentes sem fornecer mecanismo de fallback ou versionamento de rota (`/v1`, `/v2`).
|
||||
- Remover testes automatizados existentes sem justificativa técnica.
|
||||
- Apresentar falhas nos testes de estresse ou memory leaks em profiling de conexões ativas.
|
||||
|
||||
---
|
||||
|
||||
## 4. Política de Versionamento de Releases
|
||||
|
||||
As tags e imagens Docker do EvoGO seguem o formato semântico estendido:
|
||||
|
||||
- **Versões estáveis:** `v0.7.2`, `v0.7.3`, etc.
|
||||
- **Imagens Docker imutáveis:** `evogo:0.7.2-<commit_sha_curto>`
|
||||
- **Imagens de teste (develop):** `evogo:develop-<commit_sha_curto>`
|
||||
|
||||
Nenhuma tag imutável já publicada em registry deve ser sobrescrita.
|
||||
@@ -0,0 +1,140 @@
|
||||
# Procedimento de Sincronização com o Upstream (UPSTREAM_SYNC.md)
|
||||
|
||||
Este documento estabelece o procedimento operacional padrão para rastrear, importar e integrar atualizações do repositório oficial da Evolution Foundation (`evolution-foundation/evolution-go`) em nossa distribuição independente no Gitea.
|
||||
|
||||
---
|
||||
|
||||
## 1. Configuração dos Remotos Git
|
||||
|
||||
O ambiente local e os runners devem estar configurados com dois remotos oficiais:
|
||||
|
||||
- **`origin`**: Nosso repositório no Gitea.
|
||||
- SSH: `ssh://[email protected]:1080/jfeng/EvoGO.git`
|
||||
- **`upstream`**: O repositório oficial no GitHub.
|
||||
- HTTPS: `https://github.com/evolution-foundation/evolution-go.git`
|
||||
|
||||
Para verificar:
|
||||
```bash
|
||||
git remote -v
|
||||
```
|
||||
|
||||
Caso necessário reconfigurar:
|
||||
```bash
|
||||
git remote set-url origin ssh://[email protected]:1080/jfeng/EvoGO.git
|
||||
git remote add upstream https://github.com/evolution-foundation/evolution-go.git
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Sincronização Automática (Gitea Actions)
|
||||
|
||||
O workflow `.gitea/workflows/upstream-sync-check.yml` roda todo dia às 04:00 UTC
|
||||
(e sob demanda em *Actions → Sincronizacao Diaria com o Upstream → Run workflow*)
|
||||
e executa `scripts/upstream-sync.sh`:
|
||||
|
||||
1. `git fetch upstream main --tags`.
|
||||
2. Avança `upstream-sync` **somente por fast-forward** (push sem force). Se o
|
||||
upstream reescrever histórico, abre Issue e para.
|
||||
3. Se `maintained-develop` ainda não contém o upstream, cria
|
||||
`maintenance/sync-upstream-<sha7>` **a partir de `maintained-develop`** e faz
|
||||
`git merge --no-ff upstream/main`. Nossas correções ficam preservadas porque o
|
||||
upstream é mesclado *por cima* do nosso código, nunca o contrário.
|
||||
- **Conflito:** aborta e abre Issue com os arquivos em conflito e os comandos
|
||||
para resolver (seção 3 abaixo).
|
||||
- **Merge limpo:** roda `go build`, `go vet`, `go test`, faz push da branch e
|
||||
abre PR para `maintained-develop` com commits novos, arquivos sensíveis
|
||||
alterados (Dockerfile, go.mod, `pkg/core`, licenças) e resultado dos testes.
|
||||
4. Compara o `go.mau.fi/whatsmeow` do `go.mod` com `@latest` e abre Issue quando
|
||||
há versão mais nova (defasagem do whatsmeow causa o erro 405).
|
||||
|
||||
Mesclagem automática em `maintained-develop` (opcional): crie a variável de
|
||||
repositório `AUTO_MERGE_UPSTREAM=true` (*Settings → Actions → Variables*). O PR
|
||||
só é mesclado se build e testes passarem. `maintained-stable` **nunca** é tocada
|
||||
pela automação; a promoção e a publicação da imagem continuam manuais.
|
||||
|
||||
## 3. Fluxo Manual de Sincronização
|
||||
|
||||
A sincronização **NUNCA** deve sobrescrever diretamente a branch `maintained-stable` ou branches ativas de desenvolvimento sem validação.
|
||||
|
||||
### Etapa 1: Obter novidades do upstream
|
||||
```bash
|
||||
git fetch upstream --tags
|
||||
```
|
||||
|
||||
### Etapa 2: Identificar commits e tags novas
|
||||
Compare nossa branch de referência `upstream-sync` com a branch `main` do upstream:
|
||||
```bash
|
||||
git log upstream-sync..upstream/main --oneline
|
||||
git log -n 5 upstream/main --stat
|
||||
```
|
||||
|
||||
Verifique se foram geradas novas tags:
|
||||
```bash
|
||||
git tag -l -n1 --sort=-v:refname | head -n 10
|
||||
```
|
||||
|
||||
### Etapa 3: Atualizar a branch `upstream-sync`
|
||||
A branch `upstream-sync` é uma cópia 1:1 do upstream. Atualize-a utilizando exclusivamente fast-forward:
|
||||
```bash
|
||||
git checkout upstream-sync
|
||||
git merge --ff-only upstream/main
|
||||
git push origin upstream-sync --tags
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Integração e Análise de Impacto
|
||||
|
||||
### Etapa 4: Criar branch de teste e integração
|
||||
A partir de `maintained-develop`, crie uma branch de manutenção específica para a atualização:
|
||||
```bash
|
||||
git checkout maintained-develop
|
||||
git pull origin maintained-develop
|
||||
git checkout -b maintenance/sync-upstream-<nova-versao>
|
||||
```
|
||||
|
||||
### Etapa 5: Realizar o merge controlado
|
||||
```bash
|
||||
git merge upstream-sync
|
||||
```
|
||||
|
||||
Se houver conflitos:
|
||||
1. Examine os arquivos em conflito com `git status` e `git diff`.
|
||||
2. Dê prioridade a preservar nossas melhorias arquiteturais e correções (ex: injeção de handshake no `pkg/whatsmeow/service/whatsmeow.go`, configurações de CI do Gitea).
|
||||
3. Nunca utilize `git merge -X theirs` indiscriminadamente.
|
||||
4. Conclua o merge com `git commit`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Validação Pós-Sincronização
|
||||
|
||||
Antes de propor a integração para as branches mantidas:
|
||||
|
||||
1. **Validação do Go:**
|
||||
```bash
|
||||
go vet ./...
|
||||
go test -v ./...
|
||||
```
|
||||
2. **Compilação da aplicação:**
|
||||
```bash
|
||||
CGO_ENABLED=1 go build -o /dev/null ./cmd/evolution-go
|
||||
```
|
||||
3. **Verificação de dependências (`go.mod` e `go.sum`):**
|
||||
```bash
|
||||
go mod verify
|
||||
```
|
||||
4. **Verificação de arquivos de licença e autoria:**
|
||||
Confirme que `LICENSE`, `NOTICE` e avisos legais permanecem intactos.
|
||||
|
||||
---
|
||||
|
||||
## 6. Promoção para as Branches Oficiais
|
||||
|
||||
1. **Abra um Pull Request no Gitea:**
|
||||
- Origem: `maintenance/sync-upstream-<nova-versao>`
|
||||
- Destino: `maintained-develop`
|
||||
- Anexe o relatório de impacto, diffs relevantes e resultado dos testes.
|
||||
2. **Revisão e Aprovação:**
|
||||
- O proprietário valida as mudanças e executa testes em staging.
|
||||
3. **Promoção para `maintained-stable`:**
|
||||
- Uma vez homologado em `maintained-develop`, realiza-se o merge para `maintained-stable` para posterior geração de imagem Docker oficial.
|
||||
@@ -0,0 +1,91 @@
|
||||
# Compatibilidade com o WhatsApp e Resolução do Erro 405 (WHATSAPP_COMPATIBILITY.md)
|
||||
|
||||
Este documento documenta o protocolo de conexão com o WhatsApp Web, o diagnóstico aprofundado do erro **`Client outdated (405)`**, a análise comparativa dos Pull Requests da comunidade e o checklist oficial de testes de compatibilidade.
|
||||
|
||||
---
|
||||
|
||||
## 1. Funcionamento do Protocolo WhatsApp Web e Versões de Cliente
|
||||
|
||||
O WhatsApp Web opera sobre conexões WebSocket criptografadas via protocolo Noise. Durante o handshake de estabelecimento de conexão, o cliente deve enviar um payload (`ClientPayload`) contendo sua versão de aplicação (`AppVersion` / `waVersion`).
|
||||
|
||||
Periodicamente, os servidores da Meta elevam o patamar mínimo aceito da versão do cliente web. Quando um cliente envia uma versão abaixo desse patamar mínimo, o servidor WhatsApp recusa o handshake imediatamente com o código de erro:
|
||||
|
||||
```
|
||||
405 Client outdated
|
||||
```
|
||||
|
||||
Isso impede:
|
||||
- Conexão e inicialização de novas instâncias.
|
||||
- Geração de QR Code e Pairing Code.
|
||||
- Reconexão de sessões existentes após reinicialização do container.
|
||||
|
||||
---
|
||||
|
||||
## 2. Diagnóstico Técnico dos Pull Requests Upstream
|
||||
|
||||
Durante o segundo semestre de 2026, uma elevação do patamar de versão do WhatsApp causou a falha 405 generalizada. Quatro Pull Requests principais foram submetidos ao repositório oficial `evolution-foundation/evolution-go`:
|
||||
|
||||
### PR #226: `fix(deps): bump whatsmeow to fix "Client outdated (405)"`
|
||||
- **Autor:** MayconVM
|
||||
- **Modificações:**
|
||||
- Atualizou o `whatsmeow` para `v0.0.0-20261102152715-54038813c47f`.
|
||||
- Atualizou o Go para 1.26 (`go.mod` e `Dockerfile`).
|
||||
- Corrigiu quebras de API em `user_service.go` (`UpdateBlocklist`, `GetBlocklist`, `SetStatusMessage`).
|
||||
- **Limitação:** Não adicionou documentação nem tratou a injeção dinâmica de versão de handshake em runtime.
|
||||
|
||||
### PR #229: `fix(whatsmeow): apply store.SetWAVersion to update WhatsApp client handshake version`
|
||||
- **Autor:** Comunidade
|
||||
- **Modificações:**
|
||||
- Identificou que o Evolution Go apenas alterava `store.DeviceProps.Version`, o que **não atualiza** o handshake do `whatsmeow`.
|
||||
- Adicionou chamada explícita a `store.SetWAVersion(...)`.
|
||||
- Adicionou User-Agent Chrome e timeout de 10s no `fetchWhatsAppWebVersion()` em `sw.js`.
|
||||
- Adicionou fallback seguro de versão (`2.3000.1052812464`).
|
||||
- **Limitação:** Feito sobre o código antigo com whatsmeow desatualizado.
|
||||
|
||||
### PR #230: `fix: apply fetched WhatsApp version to the handshake (Client outdated 405)`
|
||||
- **Autor:** Comunidade
|
||||
- **Modificações:**
|
||||
- Reforçou a injeção chamando `store.SetWAVersion(next)` e `store.BaseClientPayload.UserAgent.AppVersion = next.ProtoAppVersion()`.
|
||||
- Adicionou lock de mutex (`waVersionMu`) e comparação `isNewerWAVersion`.
|
||||
|
||||
### PR #233: `deps: bump whatsmeow to 2026-11-02 (fix 405 client outdated)`
|
||||
- **Autor:** MayconVM
|
||||
- **Modificações:**
|
||||
- Evolução consolidada do PR #226.
|
||||
- Atualizou `whatsmeow` para `2026-11-02`.
|
||||
- Incluiu notas completas no `CHANGELOG.md` documentando a migração do schema SQLite de v14 para v16 e a mudança na resposta do blocklist (`Items` vs `Modifications`).
|
||||
- Atualizou `Makefile`, `Dockerfile` (`golang:1.26.10-alpine`) e documentação de API (`api-user.md`).
|
||||
|
||||
---
|
||||
|
||||
## 3. Estratégia Adotada no EvoGO (`fix/client-outdated-405`)
|
||||
|
||||
Para garantir uma solução definitiva, robusta e que não quebre novamente na próxima atualização do WhatsApp Web, a branch `fix/client-outdated-405` combina:
|
||||
|
||||
1. **A base do PR #233:**
|
||||
- Biblioteca `whatsmeow` atualizada para `2026-11-02`.
|
||||
- Toolchain Go 1.26.
|
||||
- Ajustes de API em `user_service.go`.
|
||||
- Documentação e migração automática de schema.
|
||||
2. **As melhorias de runtime dos PRs #229 e #230:**
|
||||
- Adição de User-Agent e timeout no `fetchWhatsAppWebVersion` para evitar bloqueios ao consultar `web.whatsapp.com/sw.js`.
|
||||
- Chamada a `store.SetWAVersion` e sincronização de `store.BaseClientPayload.UserAgent.AppVersion` durante o `StartClient`.
|
||||
|
||||
Desta forma, mesmo que novos patamares de versão do WhatsApp sejam exigidos antes de um novo rebuild do EvoGO, a aplicação busca e injeta a versão mais recente em tempo de execução automaticamente.
|
||||
|
||||
---
|
||||
|
||||
## 4. Checklist Obrigatório de Testes de Compatibilidade
|
||||
|
||||
Antes de promover qualquer atualização relacionada ao WhatsApp para `maintained-stable`, o seguinte checklist deve ser executado e validado em ambiente de homologação (staging):
|
||||
|
||||
- [ ] **1. Inicialização da Aplicação:** O container inicializa limpo, conecta ao banco e sobe o servidor HTTP sem erros de dependência ou biblioteca.
|
||||
- [ ] **2. Conexão e Handshake:** A instância inicia e o handshake é aceito pelo WhatsApp com log `Applied WhatsApp handshake version`.
|
||||
- [ ] **3. Geração de QR Code:** O endpoint `/instance/connect/:instance` gera o QR Code em base64 e exibe no console manager.
|
||||
- [ ] **4. Pareamento por Código (Pairing Code):** O endpoint `/instance/pair/:instance` retorna o código numérico de 8 dígitos para vinculação de aparelho.
|
||||
- [ ] **5. Persistência de Sessão:** As chaves de criptografia e metadados de sessão são gravados corretamente no banco de dados (`whatsmeow_device`).
|
||||
- [ ] **6. Reinicialização de Container:** Ao reiniciar o container (`docker restart`), a instância reconecta automaticamente sem exigir nova leitura de QR Code.
|
||||
- [ ] **7. Envio de Mensagem de Texto:** O endpoint `/message/sendText/:instance` entrega a mensagem com status de sucesso.
|
||||
- [ ] **8. Envio de Mídias e Áudio:** O endpoint `/message/sendMedia/:instance` entrega imagem e áudio com conversão de formato correta.
|
||||
- [ ] **9. Recebimento de Mensagens e Webhooks:** Mensagens enviadas de volta para o número pareado disparam eventos no webhook configurado.
|
||||
- [ ] **10. Compatibilidade de Banco Existente:** Nenhuma instância ou histórico é perdido ao subir uma versão com schema atualizado do whatsmeow (v14 -> v16).
|
||||
+14303
File diff suppressed because it is too large.
Load diff
+9832
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,171 @@
|
||||
<div align="center">
|
||||
|
||||
# 📚 Documentação Evolution GO
|
||||
|
||||
**Gateway de API WhatsApp de alta performance desenvolvido em Go**
|
||||
|
||||
[]()
|
||||
[]()
|
||||
[]()
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
Bem-vindo à documentação oficial do Evolution GO! Aqui você encontrará guias completos, referências de API e melhores práticas para integrar o WhatsApp às suas aplicações de forma profissional e escalável.
|
||||
|
||||
## 🚀 Começo Rápido
|
||||
|
||||
**Primeira vez aqui?** Siga este caminho:
|
||||
|
||||
1. 📖 [**Introdução**](./fundamentos/introduction.md) - Entenda o que é o Evolution GO
|
||||
2. 🔧 [**Instalação**](./fundamentos/installation.md) - Configure em 5 minutos
|
||||
3. ⚡ [**Quickstart**](./fundamentos/quickstart.md) - Envie sua primeira mensagem
|
||||
4. 📡 [**Visão Geral da API**](./guias-api/api-overview.md) - Conheça os endpoints disponíveis
|
||||
|
||||
## 📖 O que você quer fazer?
|
||||
|
||||
### Enviar Mensagens
|
||||
- [Enviar texto, imagens e documentos](./guias-api/api-messages.md)
|
||||
- [Criar enquetes interativas](./guias-api/api-messages.md#enviar-enquete)
|
||||
- [Enviar localizações e contatos](./guias-api/api-messages.md#enviar-localização)
|
||||
|
||||
### Gerenciar Instâncias
|
||||
- [Criar e conectar instâncias](./guias-api/api-instances.md)
|
||||
- [Autenticação via QR Code](./recursos-avancados/qrcode-connection.md)
|
||||
- [Gerenciar múltiplas contas](./conceitos-core/instances.md)
|
||||
|
||||
### Automatizar Workflows
|
||||
- [Receber eventos via Webhook](./recursos-avancados/events-system.md)
|
||||
- [Integrar com RabbitMQ/NATS](./recursos-avancados/events-system.md)
|
||||
- [Armazenar mídias automaticamente](./recursos-avancados/media-storage.md)
|
||||
|
||||
### Deploy em Produção
|
||||
- [Deploy com Docker](./deploy-producao/docker-deployment.md)
|
||||
- [Segurança e compliance](./deploy-producao/security.md)
|
||||
- [Escalabilidade](./conceitos-core/architecture.md)
|
||||
|
||||
---
|
||||
|
||||
## 📚 Documentação Completa
|
||||
|
||||
### 🎯 Fundamentos
|
||||
|
||||
Documentação essencial para começar a usar o Evolution GO.
|
||||
|
||||
| Documento | Descrição |
|
||||
|-----------|-----------|
|
||||
| [**Introdução**](./fundamentos/introduction.md) | O que é o Evolution GO, recursos e casos de uso |
|
||||
| [**Instalação**](./fundamentos/installation.md) | Guia completo de instalação (Docker, Local, Swarm) |
|
||||
| [**Configuração**](./fundamentos/configuration.md) | Variáveis de ambiente e configurações |
|
||||
| [**Quickstart**](./fundamentos/quickstart.md) | Tutorial prático: primeira instância em minutos |
|
||||
|
||||
### 🏗️ Conceitos Core
|
||||
|
||||
Entenda como o Evolution GO funciona por dentro.
|
||||
|
||||
| Documento | Descrição |
|
||||
|-----------|-----------|
|
||||
| [**Arquitetura**](./conceitos-core/architecture.md) | Arquitetura em camadas, componentes e fluxos |
|
||||
| [**Instâncias**](./conceitos-core/instances.md) | Como funcionam as instâncias WhatsApp |
|
||||
| [**Autenticação**](./conceitos-core/authentication.md) | API Keys, tokens e segurança |
|
||||
| [**Banco de Dados**](./conceitos-core/database.md) | Estrutura dual: evogo_auth + evogo_users |
|
||||
|
||||
### 📡 API Reference
|
||||
|
||||
Referência completa de todos os endpoints disponíveis.
|
||||
|
||||
| API | Endpoints | Descrição |
|
||||
|-----|-----------|-----------|
|
||||
| [**Overview**](./guias-api/api-overview.md) | - | Visão geral da API REST |
|
||||
| [**Instâncias**](./guias-api/api-instances.md) | 16 | Criar, conectar, gerenciar instâncias |
|
||||
| [**Mensagens**](./guias-api/api-messages.md) | 16 | Enviar texto, mídia, enquetes, stickers |
|
||||
| [**Usuários**](./guias-api/api-user.md) | 13 | Perfil, contatos, privacidade, bloqueio |
|
||||
| [**Grupos**](./guias-api/api-groups.md) | 11 | Criar e administrar grupos |
|
||||
| [**Chats**](./guias-api/api-chats.md) | 7 | Pin, archive, mute, histórico |
|
||||
| [**Labels**](./guias-api/api-labels.md) | 6 | Etiquetar chats e mensagens |
|
||||
| [**Chamadas**](./guias-api/api-call.md) | 1 | Rejeitar chamadas recebidas |
|
||||
| [**Comunidades**](./guias-api/api-community.md) | 3 | Criar e gerenciar comunidades |
|
||||
| [**Newsletters**](./guias-api/api-newsletter.md) | 6 | Canais do WhatsApp |
|
||||
| [**Webhooks**](./guias-api/api-webhooks.md) | - | Configurar eventos em tempo real |
|
||||
|
||||
### 🚀 Recursos Avançados
|
||||
|
||||
Funcionalidades avançadas para casos de uso complexos.
|
||||
|
||||
| Documento | Descrição |
|
||||
|-----------|-----------|
|
||||
| [**Sistema de Eventos**](./recursos-avancados/events-system.md) | Webhooks, RabbitMQ, NATS, WebSocket |
|
||||
| [**Armazenamento de Mídia**](./recursos-avancados/media-storage.md) | MinIO/S3, presigned URLs |
|
||||
| [**Conexão QR Code**](./recursos-avancados/qrcode-connection.md) | Fluxo de autenticação detalhado |
|
||||
| [**Multi-Device**](./recursos-avancados/multi-device.md) | Protocolo Multi-Device do WhatsApp |
|
||||
|
||||
### 🐳 Deploy e Produção
|
||||
|
||||
Guias para colocar o Evolution GO em produção.
|
||||
|
||||
| Documento | Descrição |
|
||||
|-----------|-----------|
|
||||
| [**Deploy com Docker**](./deploy-producao/docker-deployment.md) | Docker Compose, Swarm, Kubernetes |
|
||||
| [**Segurança**](./deploy-producao/security.md) | SSL/TLS, API Keys, Firewall, Hardening |
|
||||
|
||||
### 💻 Desenvolvimento
|
||||
|
||||
Para desenvolvedores que querem contribuir ou personalizar.
|
||||
|
||||
| Documento | Descrição |
|
||||
|-----------|-----------|
|
||||
| [**Guia de Desenvolvimento**](./desenvolvimento/development-guide.md) | Setup do ambiente de desenvolvimento |
|
||||
| [**Como Contribuir**](./desenvolvimento/contributing.md) | Padrões de código e processo de PR |
|
||||
| [**Debugging**](./desenvolvimento/debugging.md) | Troubleshooting e profiling |
|
||||
|
||||
### 📖 Referência Técnica
|
||||
|
||||
Consulta rápida para desenvolvedores.
|
||||
|
||||
| Documento | Descrição |
|
||||
|-----------|-----------|
|
||||
| [**API Reference**](./referencia/api-reference.md) | Todos os 79 endpoints em uma página |
|
||||
| [**Environment Variables**](./referencia/environment-variables.md) | Lista completa de variáveis de ambiente |
|
||||
| [**Error Codes**](./referencia/error-codes.md) | Códigos HTTP e erros da aplicação |
|
||||
| [**FAQ**](./referencia/faq.md) | Perguntas frequentes e soluções |
|
||||
|
||||
---
|
||||
|
||||
## 💡 Precisa de Ajuda?
|
||||
|
||||
### 📖 Recursos de Aprendizado
|
||||
- **Novo no Evolution GO?** Comece pelo [Quickstart](./fundamentos/quickstart.md)
|
||||
- **Dúvidas frequentes?** Confira o [FAQ](./referencia/faq.md)
|
||||
- **Problemas técnicos?** Veja o guia de [Debugging](./desenvolvimento/debugging.md)
|
||||
|
||||
### 🔗 Links Importantes
|
||||
- 🌐 [Repositório Oficial](https://git.evoai.app/Evolution/evolution-go)
|
||||
- 📚 [Biblioteca Whatsmeow](https://github.com/tulir/whatsmeow)
|
||||
- 🔧 [API Swagger](http://localhost:4000/swagger/index.html) (quando servidor estiver rodando)
|
||||
- 🐛 [Reportar Issues](https://git.evoai.app/Evolution/evolution-go/issues)
|
||||
|
||||
### 💬 Suporte
|
||||
- **Issues técnicos**: Abra uma issue no repositório
|
||||
- **Dúvidas sobre API**: Consulte a [Referência da API](./referencia/api-reference.md)
|
||||
- **Erros e códigos**: Veja [Códigos de Erro](./referencia/error-codes.md)
|
||||
|
||||
## 🎯 Recursos Principais
|
||||
|
||||
- ✅ **79 endpoints** REST documentados
|
||||
- ✅ **Multi-instância** - Gerencie múltiplas contas WhatsApp
|
||||
- ✅ **Multi-device** - Suporte WhatsApp Multi-Device nativo
|
||||
- ✅ **Eventos em tempo real** - Webhooks, RabbitMQ, NATS, WebSocket
|
||||
- ✅ **Armazenamento de mídia** - MinIO/S3 integrado
|
||||
- ✅ **Alta performance** - Desenvolvido em Go
|
||||
- ✅ **Docker ready** - Deploy fácil em produção
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**Mantido por EvoAI Services** • **Versão da Documentação: 1.0.0**
|
||||
|
||||
[⬆️ Voltar ao topo](#-documentação-evolution-go)
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,540 @@
|
||||
# Arquitetura
|
||||
|
||||
Como o Evolution GO está organizado por dentro - explicado de forma simples.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Arquitetura em 3 Camadas](#arquitetura-em-3-camadas)
|
||||
- [Componentes Principais](#componentes-principais)
|
||||
- [Como Funciona uma Requisição](#como-funciona-uma-requisição)
|
||||
- [Organização de Pastas](#organização-de-pastas)
|
||||
- [Tecnologias Usadas](#tecnologias-usadas)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
O Evolution GO é organizado em **3 camadas** separadas. Pense nisso como uma lanchonete:
|
||||
|
||||
1. **Atendente** (Handler) - Recebe seu pedido
|
||||
2. **Cozinha** (Service) - Prepara o pedido
|
||||
3. **Estoque** (Repository) - Busca os ingredientes
|
||||
|
||||
Cada parte tem uma função específica e não faz o trabalho das outras.
|
||||
|
||||
### Por que Separar?
|
||||
|
||||
**Vantagens**:
|
||||
- **Organização**: Cada coisa no seu lugar
|
||||
- **Manutenção**: Fácil de encontrar e corrigir problemas
|
||||
- **Testes**: Pode testar cada parte separadamente
|
||||
- **Escalabilidade**: Fácil de crescer e adicionar funcionalidades
|
||||
|
||||
---
|
||||
|
||||
## Arquitetura em 3 Camadas
|
||||
|
||||
### Camada 1: Handler (Atendente)
|
||||
|
||||
**O que faz**: Recebe requisições HTTP e responde ao cliente.
|
||||
|
||||
**Responsabilidades**:
|
||||
- Receber dados do cliente (JSON, formulários)
|
||||
- Validar se os dados estão corretos
|
||||
- Chamar o Service para fazer o trabalho
|
||||
- Devolver a resposta (sucesso ou erro)
|
||||
|
||||
**Analogia**: Como o atendente de um restaurante
|
||||
- Recebe seu pedido
|
||||
- Anota tudo certinho
|
||||
- Passa para a cozinha
|
||||
- Traz sua comida quando fica pronta
|
||||
|
||||
**Exemplo do mundo real**:
|
||||
```
|
||||
Cliente: "Quero enviar uma mensagem para o número 11999999999"
|
||||
Handler: "Ok, deixa eu passar isso para o Service..."
|
||||
Service: "Mensagem enviada!"
|
||||
Handler: "Pronto, sua mensagem foi enviada!"
|
||||
```
|
||||
|
||||
### Camada 2: Service (Cozinha)
|
||||
|
||||
**O que faz**: Implementa a lógica de negócio - onde acontece a "mágica".
|
||||
|
||||
**Responsabilidades**:
|
||||
- Aplicar regras de negócio
|
||||
- Coordenar entre diferentes partes do sistema
|
||||
- Validar dados complexos
|
||||
- Gerenciar transações
|
||||
- Decidir o que fazer
|
||||
|
||||
**Analogia**: Como a cozinha do restaurante
|
||||
- Recebe o pedido do atendente
|
||||
- Prepara a comida seguindo a receita
|
||||
- Coordena entre fogão, forno, geladeira
|
||||
- Entrega o prato pronto
|
||||
|
||||
**Exemplo do mundo real**:
|
||||
```
|
||||
Service recebe: "Enviar mensagem para 11999999999"
|
||||
|
||||
Service faz:
|
||||
1. Busca a instância do WhatsApp
|
||||
2. Verifica se está conectada
|
||||
3. Formata o número corretamente
|
||||
4. Monta a mensagem
|
||||
5. Envia via WhatsApp
|
||||
6. Salva no banco de dados
|
||||
7. Avisa o webhook (se tiver)
|
||||
8. Retorna "Sucesso!"
|
||||
```
|
||||
|
||||
### Camada 3: Repository (Estoque)
|
||||
|
||||
**O que faz**: Gerencia os dados do banco de dados.
|
||||
|
||||
**Responsabilidades**:
|
||||
- Salvar dados no banco
|
||||
- Buscar dados do banco
|
||||
- Atualizar dados existentes
|
||||
- Deletar dados
|
||||
|
||||
**Analogia**: Como o estoque do restaurante
|
||||
- Guarda os ingredientes
|
||||
- Entrega quando a cozinha pede
|
||||
- Recebe novos ingredientes
|
||||
- Organiza tudo
|
||||
|
||||
**Exemplo do mundo real**:
|
||||
```
|
||||
Service: "Preciso das informações da instância 'vendas'"
|
||||
Repository: "Deixa eu buscar no banco... Aqui está!"
|
||||
|
||||
Service: "Salva essa mensagem no banco"
|
||||
Repository: "Ok, salvei!"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Componentes Principais
|
||||
|
||||
### 1. Whatsmeow Service
|
||||
|
||||
**O que é**: O componente que faz a conexão com o WhatsApp.
|
||||
|
||||
**Analogia**: É o "telefone" do sistema. Cada instância tem seu próprio "telefone" para falar com o WhatsApp.
|
||||
|
||||
**Funções**:
|
||||
- Conectar ao WhatsApp
|
||||
- Manter a conexão ativa
|
||||
- Enviar mensagens
|
||||
- Receber mensagens
|
||||
- Gerenciar sessões
|
||||
|
||||
### 2. Event Producer
|
||||
|
||||
**O que é**: Componente que avisa outros sistemas quando algo acontece.
|
||||
|
||||
**Analogia**: Como um carteiro que entrega notificações.
|
||||
|
||||
**Tipos de notificação**:
|
||||
- **Webhook**: Envia para uma URL sua
|
||||
- **RabbitMQ**: Envia para fila de mensagens
|
||||
- **WebSocket**: Envia em tempo real
|
||||
- **NATS**: Envia para sistema de eventos
|
||||
|
||||
**Exemplos de eventos**:
|
||||
- "Nova mensagem recebida!"
|
||||
- "QR Code gerado!"
|
||||
- "Cliente desconectou!"
|
||||
|
||||
### 3. Storage Service
|
||||
|
||||
**O que é**: Componente que guarda arquivos (fotos, vídeos, áudios).
|
||||
|
||||
**Opções**:
|
||||
- **MinIO/S3**: Para produção (servidor na nuvem)
|
||||
- **Local**: Para desenvolvimento (pasta no computador)
|
||||
|
||||
**Analogia**: Como um HD externo onde ficam salvos os arquivos.
|
||||
|
||||
### 4. Config Service
|
||||
|
||||
**O que é**: Componente que carrega as configurações do sistema.
|
||||
|
||||
**O que configura**:
|
||||
- Porta do servidor
|
||||
- Conexão com banco de dados
|
||||
- API Keys
|
||||
- URLs de webhooks
|
||||
- Configurações do WhatsApp
|
||||
|
||||
**Analogia**: Como as "regras da casa" - tudo que precisa ser configurado fica aqui.
|
||||
|
||||
---
|
||||
|
||||
## Como Funciona uma Requisição
|
||||
|
||||
### Exemplo: Enviar uma Mensagem de Texto
|
||||
|
||||
```
|
||||
1. VOCÊ
|
||||
│
|
||||
│ POST /send/text
|
||||
│ {"number": "11999999999", "text": "Olá!"}
|
||||
│
|
||||
▼
|
||||
2. HANDLER (Atendente)
|
||||
│
|
||||
│ "Recebeu um pedido, vou validar..."
|
||||
│ ✓ JSON está correto
|
||||
│ ✓ Campos obrigatórios presentes
|
||||
│
|
||||
▼
|
||||
3. SERVICE (Cozinha)
|
||||
│
|
||||
│ "Vou preparar o envio da mensagem..."
|
||||
│ 1. Buscar cliente WhatsApp
|
||||
│ 2. Verificar se está conectado
|
||||
│ 3. Formatar número (11999999999 → [email protected])
|
||||
│ 4. Montar mensagem
|
||||
│
|
||||
▼
|
||||
4. WHATSAPP
|
||||
│
|
||||
│ "Enviando mensagem..."
|
||||
│ ✓ Mensagem enviada
|
||||
│ Retorna ID: msg_123456
|
||||
│
|
||||
▼
|
||||
5. SERVICE (continuação)
|
||||
│
|
||||
│ "Mensagem enviada! Agora vou registrar..."
|
||||
│ → Salvar no banco via REPOSITORY
|
||||
│ → Avisar webhook via EVENT PRODUCER
|
||||
│
|
||||
▼
|
||||
6. HANDLER (continuação)
|
||||
│
|
||||
│ "Tudo certo! Vou responder o cliente..."
|
||||
│
|
||||
▼
|
||||
7. VOCÊ
|
||||
│
|
||||
│ Recebe resposta:
|
||||
│ {"status": "success", "messageId": "msg_123456"}
|
||||
```
|
||||
|
||||
### Tempo Total
|
||||
|
||||
Tudo isso acontece em menos de 1 segundo! ⚡
|
||||
|
||||
---
|
||||
|
||||
## Organização de Pastas
|
||||
|
||||
### Estrutura Simplificada
|
||||
|
||||
```
|
||||
evolution-go/
|
||||
│
|
||||
├── cmd/
|
||||
│ └── evolution-go/
|
||||
│ └── main.go ← Arquivo principal (inicia tudo)
|
||||
│
|
||||
├── pkg/ ← Código principal
|
||||
│ │
|
||||
│ ├── instance/ ← Gerenciar instâncias
|
||||
│ │ ├── handler/ ← Recebe requisições HTTP
|
||||
│ │ ├── service/ ← Lógica de negócio
|
||||
│ │ ├── repository/ ← Acesso ao banco
|
||||
│ │ └── model/ ← Estrutura de dados
|
||||
│ │
|
||||
│ ├── message/ ← Gerenciar mensagens
|
||||
│ │ ├── handler/
|
||||
│ │ ├── service/
|
||||
│ │ ├── repository/
|
||||
│ │ └── model/
|
||||
│ │
|
||||
│ ├── group/ ← Gerenciar grupos
|
||||
│ ├── user/ ← Gerenciar usuários
|
||||
│ ├── chat/ ← Gerenciar chats
|
||||
│ │
|
||||
│ ├── whatsmeow/ ← Conexão WhatsApp
|
||||
│ ├── events/ ← Sistema de eventos
|
||||
│ ├── storage/ ← Armazenar arquivos
|
||||
│ └── config/ ← Configurações
|
||||
│
|
||||
├── docs/ ← Documentação
|
||||
├── logs/ ← Arquivos de log
|
||||
└── .env ← Configurações (senhas, chaves)
|
||||
```
|
||||
|
||||
### Padrão de Organização
|
||||
|
||||
Cada funcionalidade tem a mesma estrutura:
|
||||
|
||||
```
|
||||
funcionalidade/
|
||||
├── handler/ ← Recebe requisições
|
||||
├── service/ ← Processa lógica
|
||||
├── repository/ ← Acessa banco
|
||||
└── model/ ← Define estruturas
|
||||
```
|
||||
|
||||
**Exemplo**: Para enviar mensagens, você tem:
|
||||
- `message/handler/` - Recebe a requisição
|
||||
- `message/service/` - Prepara e envia
|
||||
- `message/repository/` - Salva no banco
|
||||
- `message/model/` - Define como é uma mensagem
|
||||
|
||||
---
|
||||
|
||||
## Tecnologias Usadas
|
||||
|
||||
### Framework Web
|
||||
|
||||
**Gin** - Framework HTTP para Go
|
||||
- Rápido e leve
|
||||
- Fácil de usar
|
||||
- Gerencia rotas e middlewares
|
||||
|
||||
**O que faz**: Recebe requisições HTTP e encaminha para os handlers.
|
||||
|
||||
### Cliente WhatsApp
|
||||
|
||||
**Whatsmeow** - Biblioteca oficial
|
||||
- Implementa protocolo do WhatsApp Web
|
||||
- Multi-dispositivo
|
||||
- Criptografia ponta-a-ponta
|
||||
|
||||
**O que faz**: Conversa com os servidores do WhatsApp.
|
||||
|
||||
### Banco de Dados
|
||||
|
||||
**GORM** - ORM (Mapeador Objeto-Relacional)
|
||||
- Facilita trabalhar com banco de dados
|
||||
- Suporta PostgreSQL e SQLite
|
||||
- Migrations automáticas
|
||||
|
||||
**O que faz**: Converte dados entre o código e o banco de dados.
|
||||
|
||||
### Filas de Mensagem
|
||||
|
||||
**RabbitMQ** - Sistema de filas
|
||||
**NATS** - Sistema de eventos
|
||||
- Entregam notificações de forma confiável
|
||||
- Processamento assíncrono
|
||||
|
||||
**O que fazem**: Avisam outros sistemas quando algo acontece.
|
||||
|
||||
### Armazenamento de Arquivos
|
||||
|
||||
**MinIO** - Storage compatível com S3
|
||||
- Armazena fotos, vídeos, áudios
|
||||
- Escalável
|
||||
|
||||
**O que faz**: Guarda arquivos de mídia enviados/recebidos.
|
||||
|
||||
### Utilitários
|
||||
|
||||
**QRCode** - Gera QR Codes
|
||||
**UUID** - Gera IDs únicos
|
||||
**WebSocket** - Comunicação em tempo real
|
||||
**Zap Logger** - Logs estruturados
|
||||
|
||||
---
|
||||
|
||||
## Ciclo de Vida de uma Instância
|
||||
|
||||
### Estados
|
||||
|
||||
```
|
||||
1. CRIADA
|
||||
↓
|
||||
(usuário cria via API)
|
||||
↓
|
||||
2. DESCONECTADA
|
||||
↓
|
||||
(usuário conecta)
|
||||
↓
|
||||
3. CONECTANDO
|
||||
↓
|
||||
(gera QR Code)
|
||||
↓
|
||||
4. AGUARDANDO SCAN
|
||||
↓
|
||||
(usuário escaneia QR no celular)
|
||||
↓
|
||||
5. ABERTA/CONECTADA
|
||||
↓
|
||||
(pode enviar/receber mensagens)
|
||||
↓
|
||||
(se desconectar)
|
||||
↓
|
||||
6. DESCONECTADA
|
||||
↓
|
||||
(pode reconectar sem QR)
|
||||
↓
|
||||
5. ABERTA/CONECTADA
|
||||
```
|
||||
|
||||
### Ações Possíveis
|
||||
|
||||
| Estado | O que Pode Fazer |
|
||||
|--------|------------------|
|
||||
| **Criada** | Conectar, Deletar |
|
||||
| **Desconectada** | Conectar, Reconectar, Deletar |
|
||||
| **Conectando** | Aguardar, Cancelar |
|
||||
| **Aguardando QR** | Escanear QR, Timeout |
|
||||
| **Aberta** | Enviar mensagens, Desconectar, Logout |
|
||||
|
||||
---
|
||||
|
||||
## Segurança
|
||||
|
||||
### 1. Autenticação
|
||||
|
||||
Todas as requisições precisam de API Key:
|
||||
- Administrador: API Key Global
|
||||
- Instância: Token específico
|
||||
|
||||
### 2. Isolamento
|
||||
|
||||
Cada instância é completamente isolada:
|
||||
- Não pode acessar dados de outras instâncias
|
||||
- Tem seu próprio cliente WhatsApp
|
||||
- Sessão separada no banco
|
||||
|
||||
### 3. Validação
|
||||
|
||||
Todos os dados são validados antes de processar:
|
||||
- Formato de número de telefone
|
||||
- Tamanho de mensagens
|
||||
- Tipos de arquivo permitidos
|
||||
|
||||
### 4. Criptografia
|
||||
|
||||
WhatsApp usa criptografia ponta-a-ponta:
|
||||
- Mensagens criptografadas automaticamente
|
||||
- Chaves guardadas de forma segura
|
||||
- Ninguém pode interceptar
|
||||
|
||||
---
|
||||
|
||||
## Escalabilidade
|
||||
|
||||
### Horizontal (Mais Servidores)
|
||||
|
||||
Pode ter múltiplas cópias do Evolution GO:
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ Load Balancer │
|
||||
└────────┬─────────┘
|
||||
│
|
||||
┌───────────┼───────────┐
|
||||
│ │ │
|
||||
┌────▼───┐ ┌───▼────┐ ┌───▼────┐
|
||||
│Server 1│ │Server 2│ │Server 3│
|
||||
└────┬───┘ └───┬────┘ └───┬────┘
|
||||
│ │ │
|
||||
└──────────┼───────────┘
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ PostgreSQL │
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
**Vantagens**:
|
||||
- Suporta mais usuários
|
||||
- Se um servidor cair, outros continuam
|
||||
- Distribuição de carga
|
||||
|
||||
### Vertical (Servidor Mais Potente)
|
||||
|
||||
Melhorar o servidor existente:
|
||||
- Mais CPU
|
||||
- Mais RAM
|
||||
- Mais espaço em disco
|
||||
|
||||
**Quando usar**:
|
||||
- Até ~100 instâncias: Vertical
|
||||
- Mais de 100: Horizontal
|
||||
|
||||
---
|
||||
|
||||
## Resumo Visual
|
||||
|
||||
### Fluxo Completo
|
||||
|
||||
```
|
||||
REQUISIÇÃO
|
||||
↓
|
||||
┌────────┐
|
||||
│Handler │ ← Valida dados
|
||||
└───┬────┘
|
||||
↓
|
||||
┌────────┐
|
||||
│Service │ ← Aplica lógica
|
||||
└───┬────┘
|
||||
↓
|
||||
┌────────────┐
|
||||
│Repository │ ← Salva/busca dados
|
||||
└───┬────────┘
|
||||
↓
|
||||
┌────────┐
|
||||
│Database│
|
||||
└────────┘
|
||||
```
|
||||
|
||||
### Componentes Interconectados
|
||||
|
||||
```
|
||||
┌──────────────────────────────────┐
|
||||
│ Evolution GO Server │
|
||||
├──────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌───────────┐ │
|
||||
│ │Handler │─────>│ Service │ │
|
||||
│ └────────┘ └─────┬─────┘ │
|
||||
│ │ │
|
||||
│ ┌──────────────┼────────┐│
|
||||
│ │ │ ││
|
||||
│ ┌────▼───┐ ┌────▼────┐ ││
|
||||
│ │Whatsapp│ │Repository ││
|
||||
│ │Service │ └────┬────┘ ││
|
||||
│ └────┬───┘ │ ││
|
||||
└─────────┼─────────────┼────────┘│
|
||||
│ │
|
||||
┌───▼────┐ ┌───▼───┐
|
||||
│WhatsApp│ │ DB │
|
||||
│Servers │ │ │
|
||||
└────────┘ └───────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Resumo Rápido
|
||||
|
||||
| Conceito | Explicação Simples |
|
||||
|----------|-------------------|
|
||||
| **Handler** | Atendente - recebe pedidos |
|
||||
| **Service** | Cozinha - prepara tudo |
|
||||
| **Repository** | Estoque - guarda dados |
|
||||
| **Whatsmeow** | Telefone - fala com WhatsApp |
|
||||
| **Events** | Carteiro - avisa outros sistemas |
|
||||
| **Storage** | HD - guarda arquivos |
|
||||
|
||||
**Lembre-se**:
|
||||
- 📱 Cada camada tem uma função específica
|
||||
- 🔄 Requisição passa por todas as camadas
|
||||
- 🏗️ Organização facilita manutenção
|
||||
- 🚀 Pode escalar horizontal ou verticalmente
|
||||
- 🔒 Segurança em todas as camadas
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,452 @@
|
||||
# Autenticação
|
||||
|
||||
Sistema de autenticação do Evolution GO usando chaves de acesso (API Keys).
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Dois Tipos de Chave](#dois-tipos-de-chave)
|
||||
- [API Key Global](#api-key-global)
|
||||
- [Token de Instância](#token-de-instância)
|
||||
- [Como Usar](#como-usar)
|
||||
- [Fluxos de Autenticação](#fluxos-de-autenticação)
|
||||
- [Segurança](#segurança)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
O Evolution GO usa **chaves de acesso** (API Keys) para proteger sua API. Pense nisso como senhas especiais que você precisa enviar em cada requisição.
|
||||
|
||||
### Como Funciona
|
||||
|
||||
Imagine um prédio com dois tipos de chave:
|
||||
- **Chave Master (Admin)**: Abre todas as portas, permite criar/deletar salas
|
||||
- **Chave Individual (Instância)**: Abre apenas uma sala específica
|
||||
|
||||
É assim que funciona a autenticação no Evolution GO!
|
||||
|
||||
**Importante**: Não usamos login/senha tradicional, JWT ou cookies. Apenas chaves simples!
|
||||
|
||||
---
|
||||
|
||||
## Dois Tipos de Chave
|
||||
|
||||
### 1. API Key Global (Admin)
|
||||
|
||||
**O que é**: A chave mestre do sistema. Quem tem essa chave controla tudo.
|
||||
|
||||
**Para que serve**:
|
||||
- Criar novas instâncias do WhatsApp
|
||||
- Deletar instâncias existentes
|
||||
- Ver todas as instâncias do sistema
|
||||
- Gerenciar configurações globais
|
||||
|
||||
**Como usar**:
|
||||
```
|
||||
Envie no header da requisição:
|
||||
apikey: sua-chave-global-aqui
|
||||
```
|
||||
|
||||
**Exemplo prático**:
|
||||
```bash
|
||||
# Criar uma instância nova
|
||||
POST /instance/create
|
||||
Header: apikey: minha-chave-master-123
|
||||
```
|
||||
|
||||
### 2. Token de Instância
|
||||
|
||||
**O que é**: A chave individual de cada WhatsApp conectado.
|
||||
|
||||
**Para que serve**:
|
||||
- Enviar mensagens
|
||||
- Criar grupos
|
||||
- Gerenciar contatos
|
||||
- Todas as operações do WhatsApp dessa instância
|
||||
|
||||
**Como usar**:
|
||||
```
|
||||
Envie no header da requisição:
|
||||
apikey: token-da-sua-instancia
|
||||
```
|
||||
|
||||
**Exemplo prático**:
|
||||
```bash
|
||||
# Enviar uma mensagem
|
||||
POST /send/text
|
||||
Header: apikey: token-vendas-123
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API Key Global
|
||||
|
||||
### Configurando
|
||||
|
||||
A API Key Global é definida como uma variável de ambiente:
|
||||
|
||||
```env
|
||||
GLOBAL_API_KEY=minha-chave-super-secreta
|
||||
```
|
||||
|
||||
### Gerando uma Chave Segura
|
||||
|
||||
**Recomendado** (Linux/Mac):
|
||||
```bash
|
||||
# Gera uma chave aleatória forte
|
||||
openssl rand -base64 32
|
||||
```
|
||||
|
||||
Resultado exemplo:
|
||||
```
|
||||
dGhpc2lzYXNlY3VyZWtleXRoYXRpc3Zlcnlsb25nYW5kc2VjdXJl
|
||||
```
|
||||
|
||||
**Não use chaves óbvias**:
|
||||
- ❌ `123456`
|
||||
- ❌ `admin`
|
||||
- ❌ `minha-senha`
|
||||
|
||||
### Onde é Usado
|
||||
|
||||
**Endpoints que precisam da API Key Global**:
|
||||
- Criar instância: `POST /instance/create`
|
||||
- Deletar instância: `DELETE /instance/delete/:id`
|
||||
- Listar todas: `GET /instance/all`
|
||||
- Ver informações: `GET /instance/info/:id`
|
||||
- Configurar proxy: `POST /instance/proxy/:id`
|
||||
- Ver logs: `GET /instance/logs/:id`
|
||||
|
||||
---
|
||||
|
||||
## Token de Instância
|
||||
|
||||
### O que é
|
||||
|
||||
Cada instância do WhatsApp tem seu próprio token único. É como o CPF da instância - identifica ela no sistema.
|
||||
|
||||
### Como Obter
|
||||
|
||||
**Opção 1: Sistema gera automaticamente**
|
||||
```json
|
||||
POST /instance/create
|
||||
{
|
||||
"name": "vendas"
|
||||
}
|
||||
|
||||
Resposta:
|
||||
{
|
||||
"id": "abc-123",
|
||||
"name": "vendas",
|
||||
"token": "token-gerado-automaticamente-xyz789"
|
||||
}
|
||||
```
|
||||
|
||||
**Opção 2: Você define o token**
|
||||
```json
|
||||
POST /instance/create
|
||||
{
|
||||
"name": "vendas",
|
||||
"token": "meu-token-customizado-vendas"
|
||||
}
|
||||
```
|
||||
|
||||
⚠️ **Atenção**: O token deve ser único no sistema!
|
||||
|
||||
### Onde é Usado
|
||||
|
||||
**Endpoints que precisam do Token de Instância**:
|
||||
|
||||
**Mensagens**:
|
||||
- Enviar texto: `POST /send/text`
|
||||
- Enviar mídia: `POST /send/media`
|
||||
- Enviar áudio: `POST /send/audio`
|
||||
- Reagir: `POST /message/react`
|
||||
- Marcar como lida: `POST /message/markread`
|
||||
|
||||
**Grupos**:
|
||||
- Listar grupos: `GET /group/list`
|
||||
- Criar grupo: `POST /group/create`
|
||||
- Adicionar participante: `POST /group/participant`
|
||||
- Sair do grupo: `POST /group/leave`
|
||||
|
||||
**Usuários**:
|
||||
- Ver informações: `POST /user/info`
|
||||
- Bloquear: `POST /user/block`
|
||||
- Desbloquear: `POST /user/unblock`
|
||||
- Ver contatos: `GET /user/contacts`
|
||||
|
||||
---
|
||||
|
||||
## Como Usar
|
||||
|
||||
### Formato do Header HTTP
|
||||
|
||||
Todas as requisições devem incluir o header `apikey`:
|
||||
|
||||
```
|
||||
apikey: sua-chave-aqui
|
||||
```
|
||||
|
||||
**NÃO use**:
|
||||
```
|
||||
❌ Authorization: Bearer sua-chave
|
||||
❌ apikey: Bearer sua-chave
|
||||
```
|
||||
|
||||
### Exemplos Práticos
|
||||
|
||||
**1. Criando uma instância (usa API Key Global)**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: minha-chave-global" \
|
||||
-d '{"name": "vendas", "token": "token-vendas"}'
|
||||
```
|
||||
|
||||
**2. Enviando mensagem (usa Token da Instância)**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/send/text \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-vendas" \
|
||||
-d '{
|
||||
"number": "5511999999999",
|
||||
"text": "Olá!"
|
||||
}'
|
||||
```
|
||||
|
||||
**3. Com JavaScript**:
|
||||
```javascript
|
||||
fetch('http://localhost:4000/send/text', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'apikey': 'token-vendas'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
number: '5511999999999',
|
||||
text: 'Olá!'
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxos de Autenticação
|
||||
|
||||
### Fluxo 1: Criar Instância
|
||||
|
||||
```
|
||||
1. Você ─────> API
|
||||
POST /instance/create
|
||||
apikey: CHAVE-GLOBAL
|
||||
|
||||
2. API verifica ─────> ✓ Chave Global OK
|
||||
|
||||
3. API cria instância ─────> Banco de Dados
|
||||
|
||||
4. API retorna ─────> Você
|
||||
{
|
||||
"name": "vendas",
|
||||
"token": "token-vendas-123"
|
||||
}
|
||||
```
|
||||
|
||||
### Fluxo 2: Enviar Mensagem
|
||||
|
||||
```
|
||||
1. Você ─────> API
|
||||
POST /send/text
|
||||
apikey: token-vendas-123
|
||||
|
||||
2. API busca ─────> Banco de Dados
|
||||
"Qual instância tem esse token?"
|
||||
|
||||
3. Banco responde ─────> API
|
||||
"É a instância 'vendas'"
|
||||
|
||||
4. API envia mensagem ─────> WhatsApp
|
||||
|
||||
5. API retorna ─────> Você
|
||||
{"status": "success"}
|
||||
```
|
||||
|
||||
### Fluxo 3: Chave Inválida
|
||||
|
||||
```
|
||||
1. Você ─────> API
|
||||
POST /send/text
|
||||
apikey: token-errado
|
||||
|
||||
2. API busca ─────> Banco de Dados
|
||||
"Qual instância tem esse token?"
|
||||
|
||||
3. Banco responde ─────> API
|
||||
"Token não encontrado!"
|
||||
|
||||
4. API retorna ERRO ─────> Você
|
||||
401 Unauthorized
|
||||
{"error": "not authorized"}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Segurança
|
||||
|
||||
### 1. Protegendo a API Key Global
|
||||
|
||||
**❌ NUNCA faça isso**:
|
||||
- Compartilhar no Slack, email ou WhatsApp
|
||||
- Salvar em arquivos públicos no GitHub
|
||||
- Usar valores óbvios como "admin" ou "123456"
|
||||
- Colocar no código-fonte
|
||||
|
||||
**✅ SEMPRE faça isso**:
|
||||
- Salvar em arquivo `.env` (e adicionar ao `.gitignore`)
|
||||
- Usar gerenciadores de secrets (Vault, AWS Secrets)
|
||||
- Gerar chaves fortes (32+ caracteres aleatórios)
|
||||
- Rotacionar periodicamente (trocar a chave)
|
||||
|
||||
### 2. Protegendo Tokens de Instância
|
||||
|
||||
**❌ NUNCA faça isso**:
|
||||
- Colocar tokens na URL (`?token=...`)
|
||||
- Salvar tokens em logs
|
||||
- Expor tokens em páginas públicas
|
||||
|
||||
**✅ SEMPRE faça isso**:
|
||||
- Enviar apenas via header HTTP
|
||||
- Usar HTTPS em produção
|
||||
- Guardar em local seguro (variáveis de ambiente)
|
||||
|
||||
### 3. Use HTTPS em Produção
|
||||
|
||||
⚠️ **CRÍTICO**: Em produção, sempre use HTTPS!
|
||||
|
||||
```
|
||||
✅ https://api.suaempresa.com/send/text
|
||||
❌ http://api.suaempresa.com/send/text
|
||||
```
|
||||
|
||||
Sem HTTPS, suas chaves trafegam em **texto puro** pela internet e podem ser interceptadas.
|
||||
|
||||
### 4. Rotação de Chaves
|
||||
|
||||
Se uma chave foi comprometida:
|
||||
|
||||
**Para API Key Global**:
|
||||
1. Gere uma nova chave forte
|
||||
2. Atualize a variável `GLOBAL_API_KEY` no servidor
|
||||
3. Reinicie a aplicação
|
||||
4. Atualize todos os clientes que usam a API
|
||||
|
||||
**Para Token de Instância**:
|
||||
1. Crie uma nova instância com novo token
|
||||
2. Migre seus dados
|
||||
3. Delete a instância antiga
|
||||
|
||||
💡 Não há como "trocar" um token existente - você precisa criar uma nova instância.
|
||||
|
||||
### 5. Monitorando Acessos
|
||||
|
||||
**Sinais de problema**:
|
||||
- Muitas tentativas com chaves inválidas
|
||||
- Acessos de IPs desconhecidos
|
||||
- Horários estranhos de acesso
|
||||
|
||||
**Recomendação**: Configure logs e alertas para tentativas de acesso não autorizado.
|
||||
|
||||
---
|
||||
|
||||
## Exemplos do Dia a Dia
|
||||
|
||||
### Cenário 1: Primeiro Uso
|
||||
|
||||
```bash
|
||||
# 1. Configure a chave global no servidor
|
||||
echo "GLOBAL_API_KEY=$(openssl rand -base64 32)" >> .env
|
||||
|
||||
# 2. Inicie o servidor
|
||||
docker-compose up -d
|
||||
|
||||
# 3. Crie sua primeira instância
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "apikey: $(grep GLOBAL_API_KEY .env | cut -d '=' -f2)" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "vendas"}'
|
||||
|
||||
# Guarde o token que foi retornado!
|
||||
```
|
||||
|
||||
### Cenário 2: Múltiplas Instâncias
|
||||
|
||||
```bash
|
||||
# Vendas
|
||||
curl -X POST http://localhost:4000/send/text \
|
||||
-H "apikey: token-vendas" \
|
||||
-d '{"number": "5511111111", "text": "Equipe vendas"}'
|
||||
|
||||
# Suporte
|
||||
curl -X POST http://localhost:4000/send/text \
|
||||
-H "apikey: token-suporte" \
|
||||
-d '{"number": "5522222222", "text": "Equipe suporte"}'
|
||||
```
|
||||
|
||||
Cada instância é independente e usa seu próprio token!
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Erro: "not authorized"
|
||||
|
||||
**Possíveis causas**:
|
||||
1. Header `apikey` está faltando
|
||||
2. Valor da chave está errado
|
||||
3. Usando chave global onde precisa token de instância (ou vice-versa)
|
||||
|
||||
**Como resolver**:
|
||||
```bash
|
||||
# Verifique se o header está sendo enviado
|
||||
curl -v http://localhost:4000/send/text
|
||||
|
||||
# Confirme o valor no .env
|
||||
cat .env | grep GLOBAL_API_KEY
|
||||
|
||||
# Liste suas instâncias para ver os tokens
|
||||
curl -H "apikey: sua-chave-global" http://localhost:4000/instance/all
|
||||
```
|
||||
|
||||
### Token não funciona após reiniciar
|
||||
|
||||
**Causa**: Tokens ficam salvos no banco e não mudam.
|
||||
|
||||
**Solução**: Use o mesmo token que foi fornecido na criação da instância.
|
||||
|
||||
### Esqueci minha API Key Global
|
||||
|
||||
**Solução**:
|
||||
1. Acesse o servidor
|
||||
2. Veja o arquivo `.env`
|
||||
3. Procure por `GLOBAL_API_KEY`
|
||||
|
||||
---
|
||||
|
||||
## Resumo Rápido
|
||||
|
||||
| Tipo | Quando Usar | Exemplo |
|
||||
|------|-------------|---------|
|
||||
| **API Key Global** | Criar/deletar instâncias | `apikey: minha-chave-master` |
|
||||
| **Token Instância** | Enviar mensagens, criar grupos | `apikey: token-vendas-123` |
|
||||
|
||||
**Lembre-se**:
|
||||
- 🔑 API Key Global = Chave mestre (admin)
|
||||
- 🎫 Token Instância = Chave de uma sala específica
|
||||
- 🔒 Sempre use HTTPS em produção
|
||||
- 📝 Guarde suas chaves em local seguro
|
||||
- 🚫 Nunca compartilhe chaves publicamente
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,425 @@
|
||||
# Banco de Dados
|
||||
|
||||
Sistema de armazenamento de dados do Evolution GO usando bancos separados para diferentes finalidades.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Por que Dois Bancos](#por-que-dois-bancos)
|
||||
- [Banco Auth](#banco-auth)
|
||||
- [Banco Users](#banco-users)
|
||||
- [Tabelas Principais](#tabelas-principais)
|
||||
- [Como os Dados se Relacionam](#como-os-dados-se-relacionam)
|
||||
- [Boas Práticas](#boas-práticas)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
O Evolution GO usa **dois bancos de dados separados**. Pense nisso como ter dois armários diferentes:
|
||||
|
||||
1. **Banco Auth** (`evogo_auth`): Guarda os dados técnicos do WhatsApp
|
||||
2. **Banco Users** (`evogo_users`): Guarda os dados da sua aplicação
|
||||
|
||||
### Tipos de Banco Suportados
|
||||
|
||||
- **PostgreSQL**: Recomendado para produção (servidores reais)
|
||||
- **SQLite**: Usado para desenvolvimento e testes (arquivo local)
|
||||
|
||||
---
|
||||
|
||||
## Por que Dois Bancos
|
||||
|
||||
### Analogia do Armário
|
||||
|
||||
Imagine que você tem uma loja:
|
||||
- **Armário 1** (Auth): Guarda as chaves, segredos e equipamentos técnicos
|
||||
- **Armário 2** (Users): Guarda produtos, clientes e vendas
|
||||
|
||||
É mais organizado e seguro manter separado!
|
||||
|
||||
### Vantagens
|
||||
|
||||
1. **Organização**: Dados do WhatsApp separados dos dados da sua API
|
||||
2. **Segurança**: Backup independente para cada tipo de dado
|
||||
3. **Performance**: Cada banco pode ser otimizado para seu uso
|
||||
4. **Escalabilidade**: Pode colocar cada banco em um servidor diferente
|
||||
|
||||
---
|
||||
|
||||
## Banco Auth
|
||||
|
||||
### O que Guarda
|
||||
|
||||
Todos os dados técnicos do WhatsApp (biblioteca whatsmeow):
|
||||
|
||||
- **Chaves de criptografia** - Para proteger suas mensagens
|
||||
- **Informações do dispositivo** - Identificação do seu WhatsApp
|
||||
- **Sessões ativas** - Conexões abertas
|
||||
- **Contatos sincronizados** - Lista de contatos
|
||||
|
||||
### Tabelas Importantes
|
||||
|
||||
O WhatsApp cria automaticamente várias tabelas:
|
||||
|
||||
1. **whatsmeow_device** - Seu "telefone virtual"
|
||||
2. **whatsmeow_identity_keys** - Chaves de segurança
|
||||
3. **whatsmeow_sessions** - Sessões de conversa
|
||||
4. **whatsmeow_contacts** - Lista de contatos
|
||||
5. ... e outras 6-7 tabelas técnicas
|
||||
|
||||
⚠️ **IMPORTANTE**: Não mexa nessas tabelas manualmente! O WhatsApp gerencia tudo automaticamente.
|
||||
|
||||
### Por que é Crítico
|
||||
|
||||
Este banco contém as **chaves de criptografia**. Sem backup dele:
|
||||
- ✅ Com backup: Reconecta automaticamente após reiniciar
|
||||
- ❌ Sem backup: Precisa escanear QR Code novamente
|
||||
|
||||
---
|
||||
|
||||
## Banco Users
|
||||
|
||||
### O que Guarda
|
||||
|
||||
Todos os dados da **sua aplicação**:
|
||||
|
||||
- **Instâncias** - Cada WhatsApp conectado
|
||||
- **Mensagens** - Histórico de mensagens enviadas
|
||||
- **Labels** - Etiquetas/marcações
|
||||
- **Configurações** - Webhooks, eventos, etc.
|
||||
|
||||
### Tabelas Principais
|
||||
|
||||
#### 1. Tabela `instances`
|
||||
|
||||
**O que é**: A tabela mais importante! Cada linha é um WhatsApp conectado.
|
||||
|
||||
**Informações guardadas**:
|
||||
- **id**: Identificador único (tipo CPF)
|
||||
- **name**: Nome amigável (ex: "vendas", "suporte")
|
||||
- **token**: Chave de acesso da instância
|
||||
- **webhook**: URL para receber eventos
|
||||
- **jid**: Número do WhatsApp (ex: 5511999999999@s.whatsapp.net)
|
||||
- **connected**: Está conectado? (true/false)
|
||||
- **qrcode**: QR Code para conectar
|
||||
- **events**: Quais eventos quer receber
|
||||
|
||||
**Configurações Avançadas**:
|
||||
- **always_online**: Aparecer sempre online
|
||||
- **reject_call**: Rejeitar chamadas automaticamente
|
||||
- **read_messages**: Marcar mensagens como lidas
|
||||
- **ignore_groups**: Ignorar mensagens de grupo
|
||||
- **ignore_status**: Ignorar status/stories
|
||||
|
||||
#### 2. Tabela `messages`
|
||||
|
||||
**O que é**: Histórico de mensagens (opcional, pode ser desabilitado).
|
||||
|
||||
**Informações guardadas**:
|
||||
- **id**: Identificador único
|
||||
- **message_id**: ID da mensagem no WhatsApp
|
||||
- **timestamp**: Quando foi enviada
|
||||
- **status**: Status (enviada, entregue, lida)
|
||||
- **source**: De qual instância veio
|
||||
|
||||
💡 **Dica**: Por padrão, não salvamos o conteúdo completo das mensagens por questão de espaço.
|
||||
|
||||
#### 3. Tabela `labels`
|
||||
|
||||
**O que é**: Etiquetas/marcações do WhatsApp.
|
||||
|
||||
**Informações guardadas**:
|
||||
- **id**: Identificador único
|
||||
- **instance_id**: De qual instância
|
||||
- **label_name**: Nome da etiqueta (ex: "Cliente VIP")
|
||||
- **label_color**: Cor da etiqueta (0-19)
|
||||
|
||||
---
|
||||
|
||||
## Tabelas Principais
|
||||
|
||||
### Estrutura Visual
|
||||
|
||||
```
|
||||
┌──────────────┐
|
||||
│ instances │ (Tabela Principal)
|
||||
│ │
|
||||
│ - id │◄─────────┐
|
||||
│ - name │ │
|
||||
│ - token │ │ Relacionamento
|
||||
│ - connected │ │
|
||||
└──────────────┘ │
|
||||
│
|
||||
┌──────────────┴──────────────┐
|
||||
│ │
|
||||
┌──────▼──────┐ ┌───────▼──────┐
|
||||
│ messages │ │ labels │
|
||||
│ │ │ │
|
||||
│ - id │ │ - id │
|
||||
│ - source ───┼─────┐ │ - instance_id│───┐
|
||||
│ (FK) │ │ │ (FK) │ │
|
||||
└─────────────┘ │ └──────────────┘ │
|
||||
│ │
|
||||
└────── Aponta para ────────┘
|
||||
instances.id
|
||||
```
|
||||
|
||||
**FK = Foreign Key (Chave Estrangeira)**
|
||||
- Significa que aponta para outra tabela
|
||||
- Como um "link" entre tabelas
|
||||
|
||||
### Quando Deleta uma Instância
|
||||
|
||||
Se você deletar uma instância, automaticamente deleta:
|
||||
- ✅ Todas as mensagens dessa instância
|
||||
- ✅ Todas as labels dessa instância
|
||||
|
||||
Isso se chama **deleção em cascata** - como um efeito dominó!
|
||||
|
||||
---
|
||||
|
||||
## Como os Dados se Relacionam
|
||||
|
||||
### Exemplo Prático
|
||||
|
||||
Imagine que você tem:
|
||||
|
||||
**1 Instância**:
|
||||
```
|
||||
ID: abc-123
|
||||
Nome: vendas
|
||||
Token: token-vendas-123
|
||||
```
|
||||
|
||||
**3 Mensagens desta instância**:
|
||||
```
|
||||
Mensagem 1: source = abc-123
|
||||
Mensagem 2: source = abc-123
|
||||
Mensagem 3: source = abc-123
|
||||
```
|
||||
|
||||
**2 Labels desta instância**:
|
||||
```
|
||||
Label 1: instance_id = abc-123
|
||||
Label 2: instance_id = abc-123
|
||||
```
|
||||
|
||||
Se você deletar a instância `abc-123`:
|
||||
- ❌ Instância deletada
|
||||
- ❌ 3 mensagens deletadas automaticamente
|
||||
- ❌ 2 labels deletadas automaticamente
|
||||
|
||||
---
|
||||
|
||||
## Configuração
|
||||
|
||||
### Variáveis de Ambiente
|
||||
|
||||
```env
|
||||
# Banco Auth (Dados do WhatsApp)
|
||||
POSTGRES_AUTH_DB=postgresql://user:pass@localhost:5432/evogo_auth
|
||||
|
||||
# Banco Users (Dados da API)
|
||||
POSTGRES_USERS_DB=postgresql://user:pass@localhost:5432/evogo_users
|
||||
```
|
||||
|
||||
### Criação Automática de Tabelas
|
||||
|
||||
Quando você inicia o Evolution GO pela primeira vez:
|
||||
|
||||
1. Sistema verifica se as tabelas existem
|
||||
2. Se não existir, cria automaticamente
|
||||
3. Se existir, apenas conecta
|
||||
4. **Nunca remove ou altera tabelas existentes** (seguro!)
|
||||
|
||||
Isso se chama **Auto-Migration** (migração automática).
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Faça Backup Regular
|
||||
|
||||
**Recomendado**: Backup diário automático
|
||||
|
||||
```bash
|
||||
# Backup do banco Auth (CRÍTICO!)
|
||||
pg_dump -U postgres evogo_auth > backup_auth_$(date +%Y%m%d).sql
|
||||
|
||||
# Backup do banco Users
|
||||
pg_dump -U postgres evogo_users > backup_users_$(date +%Y%m%d).sql
|
||||
```
|
||||
|
||||
💡 O backup do **Auth** é mais crítico pois contém as chaves de criptografia!
|
||||
|
||||
### 2. Monitorar Espaço
|
||||
|
||||
Tabelas crescem com o tempo:
|
||||
|
||||
| Tabela | Crescimento |
|
||||
|--------|-------------|
|
||||
| **messages** | Rápido (se salvar mensagens) |
|
||||
| **instances** | Lento |
|
||||
| **labels** | Lento |
|
||||
| **whatsmeow_***| Médio |
|
||||
|
||||
**Recomendação**: Limpar mensagens antigas regularmente.
|
||||
|
||||
### 3. Connection Pooling
|
||||
|
||||
**O que é**: Reutilizar conexões ao banco ao invés de abrir/fechar toda hora.
|
||||
|
||||
**Configurações recomendadas**:
|
||||
|
||||
**Desenvolvimento** (computador local):
|
||||
- Máximo 20 conexões simultâneas
|
||||
- 5 conexões em stand-by
|
||||
|
||||
**Produção** (servidor):
|
||||
- Máximo 100 conexões simultâneas
|
||||
- 25 conexões em stand-by
|
||||
|
||||
### 4. Índices para Performance
|
||||
|
||||
**O que são índices**: Como um índice de livro - ajuda a encontrar coisas mais rápido!
|
||||
|
||||
**Índices importantes já criados**:
|
||||
- `instances.name` - Buscar por nome
|
||||
- `instances.token` - Buscar por token
|
||||
- `messages.source` - Buscar mensagens de uma instância
|
||||
- `labels.instance_id` - Buscar labels de uma instância
|
||||
|
||||
### 5. Limpeza de Dados
|
||||
|
||||
**Recomendações**:
|
||||
|
||||
```bash
|
||||
# Deletar mensagens com mais de 90 dias
|
||||
DELETE FROM messages WHERE timestamp < NOW() - INTERVAL '90 days';
|
||||
|
||||
# Deletar instâncias desconectadas há mais de 30 dias
|
||||
DELETE FROM instances
|
||||
WHERE connected = false
|
||||
AND updated_at < NOW() - INTERVAL '30 days';
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Erro: "too many connections"
|
||||
|
||||
**Problema**: Muitas conexões abertas ao banco.
|
||||
|
||||
**Soluções**:
|
||||
1. Verifique quantas conexões o PostgreSQL permite
|
||||
2. Reduza o número de conexões máximas no Evolution GO
|
||||
3. Aumente o limite no PostgreSQL
|
||||
|
||||
```bash
|
||||
# Ver limite atual
|
||||
psql -c "SHOW max_connections;"
|
||||
|
||||
# Aumentar para 200 (editar postgresql.conf)
|
||||
max_connections = 200
|
||||
```
|
||||
|
||||
### Erro: "table does not exist"
|
||||
|
||||
**Problema**: Tabela não foi criada.
|
||||
|
||||
**Solução**: Reinicie a aplicação. Ela cria as tabelas automaticamente.
|
||||
|
||||
### Banco crescendo muito
|
||||
|
||||
**Problema**: Banco de dados está ocupando muito espaço.
|
||||
|
||||
**Diagnóstico**:
|
||||
```sql
|
||||
-- Ver tamanho de cada tabela
|
||||
SELECT
|
||||
tablename,
|
||||
pg_size_pretty(pg_total_relation_size(tablename::text)) as size
|
||||
FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
ORDER BY pg_total_relation_size(tablename::text) DESC;
|
||||
```
|
||||
|
||||
**Solução**: Limpe mensagens antigas ou desabilite o salvamento de mensagens.
|
||||
|
||||
### Queries lentas
|
||||
|
||||
**Problema**: Operações demorando muito.
|
||||
|
||||
**Solução**: Provavelmente falta um índice. Consulte um DBA (administrador de banco de dados).
|
||||
|
||||
---
|
||||
|
||||
## Resumo Visual
|
||||
|
||||
### Separação de Responsabilidades
|
||||
|
||||
```
|
||||
┌────────────────────────┐ ┌────────────────────────┐
|
||||
│ Banco Auth │ │ Banco Users │
|
||||
│ (evogo_auth) │ │ (evogo_users) │
|
||||
├────────────────────────┤ ├────────────────────────┤
|
||||
│ │ │ │
|
||||
│ WhatsApp │ │ Sua Aplicação │
|
||||
│ Dados Técnicos │ │ Dados de Negócio │
|
||||
│ │ │ │
|
||||
│ • Chaves cripto │ │ • Instâncias │
|
||||
│ • Sessões │ │ • Mensagens │
|
||||
│ • Device info │ │ • Labels │
|
||||
│ • Contatos │ │ • Webhooks │
|
||||
│ │ │ • Configurações │
|
||||
└────────────────────────┘ └────────────────────────┘
|
||||
▲ ▲
|
||||
│ │
|
||||
└───────── Gerenciado por ──────────┘
|
||||
Evolution GO
|
||||
```
|
||||
|
||||
### Fluxo de Dados
|
||||
|
||||
```
|
||||
1. Usuário cria instância
|
||||
↓
|
||||
2. Salvo em: users → instances
|
||||
|
||||
3. Usuário conecta WhatsApp
|
||||
↓
|
||||
4. WhatsApp salva sessão em: auth → whatsmeow_device
|
||||
|
||||
5. Mensagem enviada
|
||||
↓
|
||||
6. Salvo em: users → messages
|
||||
|
||||
7. Label criada
|
||||
↓
|
||||
8. Salvo em: users → labels
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Resumo Rápido
|
||||
|
||||
| Conceito | Explicação |
|
||||
|----------|------------|
|
||||
| **2 Bancos** | Auth (WhatsApp) + Users (API) |
|
||||
| **Auto-Migration** | Cria tabelas automaticamente |
|
||||
| **Cascata** | Deletar instância → deleta tudo relacionado |
|
||||
| **Backup** | Crítico para Auth (chaves cripto) |
|
||||
| **Índices** | Fazem buscas ficarem rápidas |
|
||||
|
||||
**Lembre-se**:
|
||||
- 🔐 Banco Auth = Dados do WhatsApp (crítico!)
|
||||
- 📊 Banco Users = Dados da sua aplicação
|
||||
- 💾 Faça backup regular
|
||||
- 🧹 Limpe dados antigos
|
||||
- 📈 Monitore crescimento
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,790 @@
|
||||
# Instâncias WhatsApp
|
||||
|
||||
Como funcionam as conexões do WhatsApp no Evolution GO - explicado de forma simples.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [O que é uma Instância](#o-que-é-uma-instância)
|
||||
- [Informações de uma Instância](#informações-de-uma-instância)
|
||||
- [Estados da Instância](#estados-da-instância)
|
||||
- [Ciclo de Vida](#ciclo-de-vida)
|
||||
- [Configurações Avançadas](#configurações-avançadas)
|
||||
- [Sistema de Eventos](#sistema-de-eventos)
|
||||
- [Proxy](#proxy)
|
||||
- [Boas Práticas](#boas-práticas)
|
||||
|
||||
---
|
||||
|
||||
## O que é uma Instância
|
||||
|
||||
Uma **instância** é uma conexão independente com o WhatsApp. Pense assim:
|
||||
|
||||
### Analogia do Celular
|
||||
|
||||
Imagine que cada instância é como um celular separado:
|
||||
- 📱 Celular 1 = Instância "vendas"
|
||||
- 📱 Celular 2 = Instância "suporte"
|
||||
- 📱 Celular 3 = Instância "marketing"
|
||||
|
||||
Cada um:
|
||||
- Tem seu próprio número do WhatsApp
|
||||
- Envia e recebe mensagens independentemente
|
||||
- Não interfere nos outros
|
||||
- Tem suas próprias configurações
|
||||
|
||||
### Características
|
||||
|
||||
**Isolamento**: Cada instância é completamente separada
|
||||
- Não compartilham mensagens
|
||||
- Não compartilham contatos
|
||||
- Não compartilham configurações
|
||||
|
||||
**Persistência**: A conexão fica salva
|
||||
- Se o servidor reiniciar, reconecta automaticamente
|
||||
- Não precisa escanear QR Code novamente
|
||||
- Sessão guardada com segurança
|
||||
|
||||
**Multi-Device**: Usa o protocolo do WhatsApp Web
|
||||
- Funciona como WhatsApp no computador
|
||||
- Não desconecta o celular
|
||||
- Até 4 dispositivos por número
|
||||
|
||||
---
|
||||
|
||||
## Informações de uma Instância
|
||||
|
||||
### Dados Básicos
|
||||
|
||||
Toda instância tem essas informações:
|
||||
|
||||
**id** - Identificador único (como um CPF)
|
||||
```
|
||||
Exemplo: abc-123-def-456
|
||||
```
|
||||
|
||||
**name** - Nome amigável
|
||||
```
|
||||
Exemplo: "vendas", "suporte", "atendimento-24h"
|
||||
Deve ser único no sistema
|
||||
```
|
||||
|
||||
**token** - Chave de acesso
|
||||
```
|
||||
Exemplo: "token-vendas-secreto-123"
|
||||
Usado para autenticar requisições
|
||||
Deve ser único no sistema
|
||||
```
|
||||
|
||||
**jid** - ID do WhatsApp (seu número)
|
||||
```
|
||||
Formato: [email protected]
|
||||
Só aparece depois de conectar
|
||||
```
|
||||
|
||||
**connected** - Está conectado?
|
||||
```
|
||||
true = Conectado e funcionando
|
||||
false = Desconectado
|
||||
```
|
||||
|
||||
**qrcode** - QR Code para conectar
|
||||
```
|
||||
Formato: imagem_base64|codigo_texto
|
||||
Expira em ~40 segundos
|
||||
```
|
||||
|
||||
### Dados de Integração
|
||||
|
||||
**webhook** - URL para receber notificações
|
||||
```
|
||||
Exemplo: https://meusite.com/webhook
|
||||
Recebe eventos em tempo real
|
||||
```
|
||||
|
||||
**events** - Quais eventos quer receber
|
||||
```
|
||||
Exemplo: "MESSAGE,GROUP_UPDATE,CALL"
|
||||
Pode ser "ALL" para receber tudo
|
||||
```
|
||||
|
||||
**rabbitmqEnable** - Usar RabbitMQ?
|
||||
```
|
||||
"true" = Sim, enviar eventos
|
||||
"false" = Não usar
|
||||
```
|
||||
|
||||
**websocketEnable** - Usar WebSocket?
|
||||
```
|
||||
"true" = Sim, eventos em tempo real
|
||||
"false" = Não usar
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Estados da Instância
|
||||
|
||||
### Diagrama de Estados
|
||||
|
||||
```
|
||||
┌──────────────┐
|
||||
│ CRIADA │ ← Acabou de criar
|
||||
└──────┬───────┘
|
||||
│ (aguardando conexão)
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ DESCONECTADA │ ← Sem conexão WhatsApp
|
||||
└──────┬───────┘
|
||||
│ (conectar)
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ CONECTANDO │ ← Iniciando conexão
|
||||
└──────┬───────┘
|
||||
│ (gera QR Code)
|
||||
▼
|
||||
┌──────────────┐
|
||||
│AGUARDANDO QR │ ← Esperando escanear
|
||||
└──────┬───────┘
|
||||
│ (escaneia no celular)
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ ABERTA │ ← Conectado! ✓
|
||||
└──────┬───────┘
|
||||
│ (pode enviar/receber)
|
||||
│
|
||||
│ (se desconectar)
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ DESCONECTADA │
|
||||
└──────────────┘
|
||||
```
|
||||
|
||||
### Verificando o Estado
|
||||
|
||||
**Via API**:
|
||||
```bash
|
||||
GET /instance/status?instanceName=vendas
|
||||
|
||||
Resposta:
|
||||
{
|
||||
"connected": true,
|
||||
"loggedIn": true,
|
||||
"jid": "[email protected]",
|
||||
"name": "João Silva"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ciclo de Vida
|
||||
|
||||
### 1. Criar Instância
|
||||
|
||||
**Endpoint**: `POST /instance/create`
|
||||
|
||||
**O que acontece**:
|
||||
1. Sistema verifica se o nome já existe
|
||||
2. Gera um ID único automaticamente
|
||||
3. Salva no banco de dados
|
||||
4. Retorna informações da instância
|
||||
5. **Não conecta ainda** - apenas cria o registro
|
||||
|
||||
**Exemplo**:
|
||||
```json
|
||||
POST /instance/create
|
||||
{
|
||||
"name": "vendas",
|
||||
"token": "meu-token-vendas"
|
||||
}
|
||||
|
||||
Resposta:
|
||||
{
|
||||
"id": "abc-123",
|
||||
"name": "vendas",
|
||||
"token": "meu-token-vendas",
|
||||
"connected": false
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Conectar Instância
|
||||
|
||||
**Endpoint**: `POST /instance/connect`
|
||||
|
||||
**O que acontece**:
|
||||
1. Sistema inicia cliente WhatsApp
|
||||
2. Gera QR Code
|
||||
3. Salva QR Code no banco
|
||||
4. Aguarda você escanear
|
||||
|
||||
**Exemplo**:
|
||||
```json
|
||||
POST /instance/connect
|
||||
{
|
||||
"instanceName": "vendas",
|
||||
"webhookUrl": "https://meusite.com/webhook",
|
||||
"subscribe": ["MESSAGE", "GROUP_UPDATE"]
|
||||
}
|
||||
```
|
||||
|
||||
**Importante**: A conexão é assíncrona! O QR Code aparece depois de alguns segundos.
|
||||
|
||||
### 3. Obter QR Code
|
||||
|
||||
**Endpoint**: `GET /instance/qr?instanceName=vendas`
|
||||
|
||||
**O que acontece**:
|
||||
1. Sistema verifica se já está conectado
|
||||
2. Se não estiver, retorna o QR Code
|
||||
3. QR Code tem duas partes separadas por `|`
|
||||
|
||||
**Formato do QR Code**:
|
||||
```
|
||||
parte1|parte2
|
||||
|
||||
parte1 = imagem PNG em base64
|
||||
parte2 = código texto do QR
|
||||
```
|
||||
|
||||
**Uso prático**:
|
||||
```html
|
||||
<!-- Mostrar QR Code na página -->
|
||||
<img src="parte1" />
|
||||
|
||||
<!-- Ou usar a biblioteca JS -->
|
||||
<qrcode value="parte2"></qrcode>
|
||||
```
|
||||
|
||||
### 4. Parear com Código
|
||||
|
||||
**Endpoint**: `POST /instance/pair`
|
||||
|
||||
**Alternativa ao QR Code**: Você recebe um código de 8 dígitos para digitar no celular.
|
||||
|
||||
**Exemplo**:
|
||||
```json
|
||||
POST /instance/pair
|
||||
{
|
||||
"instanceName": "vendas",
|
||||
"phone": "5511999999999"
|
||||
}
|
||||
|
||||
Resposta:
|
||||
{
|
||||
"pairingCode": "1234-5678"
|
||||
}
|
||||
```
|
||||
|
||||
**Como usar**:
|
||||
1. Abra WhatsApp no celular
|
||||
2. Vá em Dispositivos Conectados
|
||||
3. Conectar Dispositivo
|
||||
4. Digite o código: 1234-5678
|
||||
|
||||
### 5. Reconectar
|
||||
|
||||
**Endpoint**: `POST /instance/reconnect`
|
||||
|
||||
**Diferença importante**:
|
||||
- **Connect**: Primeira vez, precisa de QR Code
|
||||
- **Reconnect**: Já conectou antes, reutiliza sessão
|
||||
|
||||
**Quando usar**:
|
||||
- Após reiniciar o servidor
|
||||
- Quando perder conexão temporária
|
||||
- Para forçar reconexão
|
||||
|
||||
**Não precisa de QR Code!** A sessão já está salva.
|
||||
|
||||
### 6. Desconectar
|
||||
|
||||
**Endpoint**: `POST /instance/disconnect`
|
||||
|
||||
**O que acontece**:
|
||||
1. Fecha a conexão com WhatsApp
|
||||
2. Para de receber mensagens
|
||||
3. **Mantém a sessão salva**
|
||||
4. Pode reconectar depois sem QR Code
|
||||
|
||||
**Quando usar**:
|
||||
- Manutenção temporária
|
||||
- Pausar operação
|
||||
- Trocar configurações
|
||||
|
||||
### 7. Logout
|
||||
|
||||
**Endpoint**: `POST /instance/logout`
|
||||
|
||||
**Diferença de Disconnect**:
|
||||
- **Disconnect**: Desliga mas mantém sessão
|
||||
- **Logout**: Remove a sessão completamente
|
||||
|
||||
**O que acontece**:
|
||||
1. Remove sessão do WhatsApp
|
||||
2. Desconecta completamente
|
||||
3. **Precisa de novo QR Code** para conectar de novo
|
||||
4. Como se nunca tivesse conectado
|
||||
|
||||
**Quando usar**:
|
||||
- Trocar de número
|
||||
- Limpar conexão completamente
|
||||
- Resetar instância
|
||||
|
||||
### 8. Deletar
|
||||
|
||||
**Endpoint**: `DELETE /instance/delete/:id`
|
||||
|
||||
**O que acontece**:
|
||||
1. Faz logout se estiver conectado
|
||||
2. Remove todas as mensagens dessa instância
|
||||
3. Remove todas as labels dessa instância
|
||||
4. **Deleta tudo do banco de dados**
|
||||
5. Operação irreversível!
|
||||
|
||||
**⚠️ ATENÇÃO**: Não tem como desfazer!
|
||||
|
||||
---
|
||||
|
||||
## Configurações Avançadas
|
||||
|
||||
### O que São
|
||||
|
||||
Configurações extras para mudar o comportamento da instância.
|
||||
|
||||
### Opções Disponíveis
|
||||
|
||||
**alwaysOnline** - Aparecer sempre online
|
||||
```
|
||||
true = Sempre mostra como "online"
|
||||
false = Normal (online quando está usando)
|
||||
```
|
||||
|
||||
**rejectCall** - Rejeitar chamadas automaticamente
|
||||
```
|
||||
true = Rejeita chamadas de voz/vídeo
|
||||
false = Aceita normalmente
|
||||
```
|
||||
|
||||
**msgRejectCall** - Mensagem ao rejeitar
|
||||
```
|
||||
Exemplo: "Desculpe, não atendo chamadas. Envie mensagem de texto."
|
||||
Enviada automaticamente quando rejeitar
|
||||
```
|
||||
|
||||
**readMessages** - Marcar como lidas automaticamente
|
||||
```
|
||||
true = Marca todas as mensagens recebidas como lidas
|
||||
false = Normal (você marca manualmente)
|
||||
```
|
||||
|
||||
**ignoreGroups** - Ignorar mensagens de grupo
|
||||
```
|
||||
true = Não processa eventos de grupos
|
||||
false = Normal (recebe tudo)
|
||||
```
|
||||
|
||||
**ignoreStatus** - Ignorar status/stories
|
||||
```
|
||||
true = Não processa atualizações de status
|
||||
false = Normal (recebe tudo)
|
||||
```
|
||||
|
||||
### Como Configurar
|
||||
|
||||
**Endpoint**: `POST /instance/:id/advanced-settings`
|
||||
|
||||
**Exemplo**:
|
||||
```json
|
||||
{
|
||||
"alwaysOnline": true,
|
||||
"rejectCall": true,
|
||||
"msgRejectCall": "Não atendo chamadas, envie mensagem!",
|
||||
"readMessages": false,
|
||||
"ignoreGroups": false,
|
||||
"ignoreStatus": true
|
||||
}
|
||||
```
|
||||
|
||||
**Efeito**: Aplica instantaneamente sem precisar reconectar!
|
||||
|
||||
---
|
||||
|
||||
## Sistema de Eventos
|
||||
|
||||
### O que São Eventos
|
||||
|
||||
Notificações que o Evolution GO envia quando algo acontece.
|
||||
|
||||
**Analogia**: Como notificações do celular
|
||||
- "Nova mensagem recebida!"
|
||||
- "Fulano entrou no grupo!"
|
||||
- "Chamada recebida!"
|
||||
|
||||
### Tipos de Eventos
|
||||
|
||||
**Mensagens**:
|
||||
- `MESSAGE` - Mensagem recebida
|
||||
- `MESSAGE_SENT` - Mensagem enviada
|
||||
- `MESSAGE_UPDATE` - Mensagem editada/deletada
|
||||
- `MESSAGE_REACTION` - Reação em mensagem
|
||||
|
||||
**Grupos**:
|
||||
- `GROUP_UPDATE` - Grupo atualizado
|
||||
- `GROUP_PARTICIPANT_UPDATE` - Alguém entrou/saiu
|
||||
|
||||
**Conexão**:
|
||||
- `CONNECTION_UPDATE` - Mudou status de conexão
|
||||
- `QR_CODE` - QR Code gerado
|
||||
- `QRCODE_UPDATED` - QR Code atualizado
|
||||
|
||||
**Outros**:
|
||||
- `PRESENCE_UPDATE` - Alguém ficou online/offline
|
||||
- `CALL` - Chamada recebida
|
||||
- `CONTACT_UPDATE` - Contato atualizado
|
||||
- `LABEL` - Label criada/atualizada
|
||||
|
||||
### Como Subscrever
|
||||
|
||||
**Ao conectar, escolha quais eventos quer**:
|
||||
|
||||
```json
|
||||
POST /instance/connect
|
||||
{
|
||||
"instanceName": "vendas",
|
||||
"subscribe": ["MESSAGE", "GROUP_UPDATE", "CALL"]
|
||||
}
|
||||
```
|
||||
|
||||
**Opções**:
|
||||
- Lista específica: `["MESSAGE", "CALL"]`
|
||||
- Todos os eventos: `["ALL"]`
|
||||
- Apenas mensagens (padrão): `["MESSAGE"]`
|
||||
|
||||
### Destinos dos Eventos
|
||||
|
||||
Pode enviar para vários lugares ao mesmo tempo:
|
||||
|
||||
**Webhook** (HTTP POST):
|
||||
```json
|
||||
{
|
||||
"webhookUrl": "https://meusite.com/webhook"
|
||||
}
|
||||
```
|
||||
|
||||
**RabbitMQ** (Fila de mensagens):
|
||||
```json
|
||||
{
|
||||
"rabbitmqEnable": "true"
|
||||
}
|
||||
```
|
||||
|
||||
**WebSocket** (Tempo real):
|
||||
```json
|
||||
{
|
||||
"websocketEnable": "true"
|
||||
}
|
||||
```
|
||||
|
||||
**NATS** (Sistema de eventos):
|
||||
```json
|
||||
{
|
||||
"natsEnable": "true"
|
||||
}
|
||||
```
|
||||
|
||||
**Pode ativar todos juntos!** Cada evento será enviado para todos os destinos configurados.
|
||||
|
||||
---
|
||||
|
||||
## Proxy
|
||||
|
||||
### O que é Proxy
|
||||
|
||||
Um servidor intermediário entre você e o WhatsApp.
|
||||
|
||||
**Analogia**: Como usar uma empresa de correio
|
||||
- Você → Correio → Destinatário
|
||||
- Seu IP fica escondido
|
||||
- WhatsApp vê o IP do proxy
|
||||
|
||||
### Quando Usar
|
||||
|
||||
**Recomendado se**:
|
||||
- Tem muitas instâncias (>10)
|
||||
- Quer esconder seu IP real
|
||||
- Precisa de múltiplos IPs
|
||||
- WhatsApp bloqueou seu IP
|
||||
|
||||
### Como Configurar
|
||||
|
||||
**Endpoint**: `POST /instance/proxy/:id`
|
||||
|
||||
**Exemplo**:
|
||||
```json
|
||||
{
|
||||
"host": "proxy.exemplo.com",
|
||||
"port": "8080",
|
||||
"username": "usuario", // Opcional
|
||||
"password": "senha" // Opcional
|
||||
}
|
||||
```
|
||||
|
||||
**Importante**: Precisa reconectar para aplicar!
|
||||
|
||||
### Como Remover
|
||||
|
||||
**Endpoint**: `DELETE /instance/proxy/:id`
|
||||
|
||||
Remove o proxy e volta a conexão direta.
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Nomeação
|
||||
|
||||
Use nomes descritivos:
|
||||
|
||||
**✅ Bom**:
|
||||
- `vendas-regiao-sul`
|
||||
- `suporte-nivel-1`
|
||||
- `marketing-campanhas`
|
||||
- `atendimento-24h`
|
||||
|
||||
**❌ Ruim**:
|
||||
- `teste`
|
||||
- `instance1`
|
||||
- `minha-instancia`
|
||||
- `zap`
|
||||
|
||||
### 2. Gerenciar Eventos
|
||||
|
||||
**Subscreva apenas o necessário**:
|
||||
|
||||
```json
|
||||
// ✅ Bom - Apenas o que precisa
|
||||
{"subscribe": ["MESSAGE", "GROUP_UPDATE"]}
|
||||
|
||||
// ❌ Ruim - Muito tráfego desnecessário
|
||||
{"subscribe": ["ALL"]}
|
||||
```
|
||||
|
||||
Menos eventos = menos processamento = mais rápido
|
||||
|
||||
### 3. Configurações Avançadas
|
||||
|
||||
**Otimize para seu caso**:
|
||||
|
||||
```json
|
||||
// Bot de atendimento
|
||||
{
|
||||
"ignoreGroups": true, // Não precisa de grupos
|
||||
"ignoreStatus": true, // Não precisa de status
|
||||
"readMessages": true // Marca como lido automaticamente
|
||||
}
|
||||
|
||||
// Monitoramento de grupos
|
||||
{
|
||||
"ignoreGroups": false, // Precisa de grupos
|
||||
"ignoreStatus": true, // Não precisa de status
|
||||
"readMessages": false // Não marca como lido
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Use Proxy
|
||||
|
||||
**Se tiver muitas instâncias** (>10):
|
||||
|
||||
- Evita bloqueio de IP
|
||||
- Distribui a carga
|
||||
- Mais estável
|
||||
|
||||
### 5. Monitore Logs
|
||||
|
||||
**Acompanhe sua instância**:
|
||||
|
||||
```bash
|
||||
GET /instance/logs/vendas?level=ERROR&limit=50
|
||||
```
|
||||
|
||||
Veja erros antes que causem problemas!
|
||||
|
||||
### 6. Limpeza Regular
|
||||
|
||||
**Delete instâncias não usadas**:
|
||||
|
||||
```bash
|
||||
DELETE /instance/delete/teste-antigo
|
||||
```
|
||||
|
||||
Libera recursos e organiza o sistema.
|
||||
|
||||
### 7. Reconexão vs Logout
|
||||
|
||||
**Entenda a diferença**:
|
||||
|
||||
| Situação | Use |
|
||||
|----------|-----|
|
||||
| Reiniciou servidor | Reconnect |
|
||||
| Perdeu conexão | Reconnect |
|
||||
| Trocar de número | Logout |
|
||||
| Limpar tudo | Logout + Delete |
|
||||
|
||||
---
|
||||
|
||||
## Limitações
|
||||
|
||||
### Limites do WhatsApp
|
||||
|
||||
**Dispositivos**:
|
||||
- Máximo 4 dispositivos por número
|
||||
- Evolution GO conta como 1 dispositivo
|
||||
|
||||
**QR Code**:
|
||||
- Expira em ~40 segundos
|
||||
- Máximo de tentativas por hora
|
||||
|
||||
**Reconexão**:
|
||||
- Não reconecte mais de 1x por minuto
|
||||
- Pode ser bloqueado temporariamente
|
||||
|
||||
### Limites do Evolution GO
|
||||
|
||||
**Por Servidor**:
|
||||
- Depende da RAM disponível
|
||||
- Cada instância usa ~50-100MB
|
||||
- Exemplo: 16GB RAM = ~100 instâncias
|
||||
|
||||
**Banco de Dados**:
|
||||
- PostgreSQL: 100 conexões simultâneas (padrão)
|
||||
- Pode configurar mais se necessário
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "no active session found"
|
||||
|
||||
**Problema**: Cliente não existe.
|
||||
|
||||
**Causa**: Não conectou ainda ou sessão expirou.
|
||||
|
||||
**Solução**:
|
||||
1. Conecte via `POST /instance/connect`
|
||||
2. Escaneie QR Code
|
||||
3. Aguarde conectar
|
||||
|
||||
### "client disconnected"
|
||||
|
||||
**Problema**: Perdeu conexão com WhatsApp.
|
||||
|
||||
**Causa**: Internet caiu ou WhatsApp instável.
|
||||
|
||||
**Solução**:
|
||||
```bash
|
||||
POST /instance/reconnect
|
||||
```
|
||||
|
||||
### QR Code não aparece
|
||||
|
||||
**Problema**: QR Code vazio ou nulo.
|
||||
|
||||
**Causa**: Cliente ainda inicializando.
|
||||
|
||||
**Solução**:
|
||||
1. Aguarde 2-3 segundos após `/connect`
|
||||
2. Tente `/instance/qr` novamente
|
||||
3. Se persistir, tente reconectar
|
||||
|
||||
### Não reconecta após reiniciar
|
||||
|
||||
**Problema**: Precisa escanear QR Code de novo.
|
||||
|
||||
**Causa**: Sessão corrompida ou expirada.
|
||||
|
||||
**Solução**:
|
||||
```bash
|
||||
# 1. Logout completo
|
||||
POST /instance/logout
|
||||
|
||||
# 2. Conectar de novo
|
||||
POST /instance/connect
|
||||
|
||||
# 3. Escanear novo QR Code
|
||||
```
|
||||
|
||||
### Mensagens não chegam
|
||||
|
||||
**Problema**: Eventos não são recebidos.
|
||||
|
||||
**Causa**: Configuração de eventos errada.
|
||||
|
||||
**Solução**:
|
||||
1. Verifique se inscreveu no evento `MESSAGE`
|
||||
2. Teste o webhook/RabbitMQ
|
||||
3. Veja os logs da instância
|
||||
|
||||
---
|
||||
|
||||
## Exemplo Completo
|
||||
|
||||
### Do Zero até Enviar Mensagem
|
||||
|
||||
```bash
|
||||
# 1. Criar instância
|
||||
POST /instance/create
|
||||
{
|
||||
"name": "vendas",
|
||||
"token": "token-vendas-123"
|
||||
}
|
||||
|
||||
# 2. Conectar
|
||||
POST /instance/connect
|
||||
{
|
||||
"instanceName": "vendas",
|
||||
"webhookUrl": "https://meusite.com/webhook",
|
||||
"subscribe": ["MESSAGE"]
|
||||
}
|
||||
|
||||
# 3. Aguardar 2 segundos...
|
||||
|
||||
# 4. Pegar QR Code
|
||||
GET /instance/qr?instanceName=vendas
|
||||
|
||||
# 5. Escanear QR Code no celular
|
||||
|
||||
# 6. Aguardar conectar (~5 segundos)
|
||||
|
||||
# 7. Enviar mensagem! 🎉
|
||||
POST /send/text
|
||||
Headers: apikey: token-vendas-123
|
||||
{
|
||||
"number": "5511999999999",
|
||||
"text": "Olá! Primeira mensagem!"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Resumo Rápido
|
||||
|
||||
| Conceito | Explicação |
|
||||
|----------|------------|
|
||||
| **Instância** | Uma conexão WhatsApp independente |
|
||||
| **QR Code** | Código para parear com celular |
|
||||
| **Connect** | Primeira conexão (precisa QR) |
|
||||
| **Reconnect** | Reconexão (não precisa QR) |
|
||||
| **Logout** | Remove sessão completamente |
|
||||
| **Delete** | Apaga tudo (irreversível) |
|
||||
| **Eventos** | Notificações quando algo acontece |
|
||||
| **Proxy** | Servidor intermediário |
|
||||
|
||||
**Lembre-se**:
|
||||
- 📱 Cada instância = 1 WhatsApp
|
||||
- 🔄 Reconnect não precisa de QR Code
|
||||
- 🚪 Logout remove tudo
|
||||
- 📊 Configure apenas eventos necessários
|
||||
- 🔒 Use proxy para muitas instâncias
|
||||
- 🗑️ Delete instâncias não usadas
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,814 @@
|
||||
# Deploy com Docker
|
||||
|
||||
Guia de deploy do Evolution GO usando Docker, Docker Compose, Swarm e Kubernetes.
|
||||
|
||||
## Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Deploy com Docker Compose](#deploy-com-docker-compose)
|
||||
- [Deploy com Docker Swarm](#deploy-com-docker-swarm)
|
||||
- [Deploy com Kubernetes](#deploy-com-kubernetes)
|
||||
- [Otimização e Gestão](#otimização-e-gestão)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
### Estratégias de Deploy
|
||||
|
||||
| Estratégia | Uso Recomendado | Complexidade | Escalabilidade |
|
||||
|------------|-----------------|--------------|----------------|
|
||||
| **Docker Compose** | Desenvolvimento, testes, deploys pequenos | Baixa | Limitada (single-host) |
|
||||
| **Docker Swarm** | Produção pequena/média, HA | Média | Boa (multi-host) |
|
||||
| **Kubernetes** | Produção enterprise, orquestração avançada | Alta | Excelente |
|
||||
|
||||
### Arquitetura de Componentes
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ EVOLUTION GO STACK │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Evolution GO │◄────►│ PostgreSQL │ │ RabbitMQ │ │
|
||||
│ │ (API) │ │ (Auth DB) │ │ (Events) │ │
|
||||
│ │ Port: 4000 │ │ (Users DB) │ │ Port: 5672 │ │
|
||||
│ └──────┬───────┘ └──────────────┘ └──────────────┘ │
|
||||
│ │ │
|
||||
│ │ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ └─────────────►│ MinIO │ │ NATS │ │
|
||||
│ │ (Media) │ │ (Optional) │ │
|
||||
│ │ Port: 9000 │ │ Port: 4222 │ │
|
||||
│ └──────────────┘ └──────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Imagem Docker
|
||||
|
||||
- **Registry**: `evoapicloud/evolution-go`
|
||||
- **Tags**: `latest`, `v1.x.x`
|
||||
- **Base**: Alpine Linux 3.19.1
|
||||
- **Tamanho**: ~50MB (compactada)
|
||||
- **Arquiteturas**: amd64, arm64
|
||||
|
||||
---
|
||||
|
||||
## Deploy com Docker Compose
|
||||
|
||||
### Setup Básico
|
||||
|
||||
Configuração mínima com Evolution GO + PostgreSQL.
|
||||
|
||||
#### docker-compose.yml
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
evolution-go:
|
||||
image: evoapicloud/evolution-go:latest
|
||||
container_name: evolution-go
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "4000:4000"
|
||||
environment:
|
||||
SERVER_PORT: 4000
|
||||
CLIENT_NAME: "evolution"
|
||||
GLOBAL_API_KEY: "SUBSTITUA-POR-UUID-FORTE"
|
||||
|
||||
POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable"
|
||||
POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable"
|
||||
DATABASE_SAVE_MESSAGES: "false"
|
||||
|
||||
WADEBUG: "INFO"
|
||||
LOGTYPE: "console"
|
||||
CONNECT_ON_STARTUP: "false"
|
||||
WEBHOOK_FILES: "true"
|
||||
|
||||
volumes:
|
||||
- evolution_data:/app/dbdata
|
||||
- evolution_logs:/app/logs
|
||||
networks:
|
||||
- evolution_network
|
||||
depends_on:
|
||||
- postgres
|
||||
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: postgres
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
|
||||
networks:
|
||||
- evolution_network
|
||||
|
||||
volumes:
|
||||
evolution_data:
|
||||
evolution_logs:
|
||||
postgres_data:
|
||||
|
||||
networks:
|
||||
evolution_network:
|
||||
driver: bridge
|
||||
```
|
||||
|
||||
#### init-db.sql
|
||||
|
||||
```sql
|
||||
CREATE DATABASE evogo_auth;
|
||||
CREATE DATABASE evogo_users;
|
||||
SELECT 'Databases criados com sucesso!' as message;
|
||||
```
|
||||
|
||||
#### Deploy
|
||||
|
||||
```bash
|
||||
# Gerar API Key
|
||||
uuidgen
|
||||
|
||||
# Editar docker-compose.yml e inserir API Key
|
||||
|
||||
# Iniciar
|
||||
docker-compose up -d
|
||||
|
||||
# Verificar
|
||||
docker-compose logs -f evolution-go
|
||||
curl http://localhost:4000/server/ok
|
||||
```
|
||||
|
||||
### Setup Completo
|
||||
|
||||
Incluindo RabbitMQ, MinIO e NATS.
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
evolution-go:
|
||||
image: evoapicloud/evolution-go:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "4000:4000"
|
||||
environment:
|
||||
SERVER_PORT: 4000
|
||||
GLOBAL_API_KEY: "SUA-CHAVE-AQUI"
|
||||
|
||||
POSTGRES_AUTH_DB: "postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable"
|
||||
POSTGRES_USERS_DB: "postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable"
|
||||
DATABASE_SAVE_MESSAGES: "true"
|
||||
|
||||
AMQP_URL: "amqp://admin:admin@rabbitmq:5672/default"
|
||||
AMQP_GLOBAL_ENABLED: "true"
|
||||
AMQP_GLOBAL_EVENTS: "messages.upsert,messages.update,connection.update"
|
||||
|
||||
MINIO_ENABLED: "true"
|
||||
MINIO_ENDPOINT: "minio:9000"
|
||||
MINIO_ACCESS_KEY: "minioadmin"
|
||||
MINIO_SECRET_KEY: "minioadmin"
|
||||
MINIO_BUCKET: "evolution-media"
|
||||
MINIO_USE_SSL: "false"
|
||||
|
||||
volumes:
|
||||
- evolution_data:/app/dbdata
|
||||
- evolution_logs:/app/logs
|
||||
depends_on:
|
||||
- postgres
|
||||
- rabbitmq
|
||||
- minio
|
||||
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: senha
|
||||
POSTGRES_DB: postgres
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:3-management-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: admin
|
||||
RABBITMQ_DEFAULT_PASS: admin
|
||||
RABBITMQ_DEFAULT_VHOST: default
|
||||
ports:
|
||||
- "5672:5672"
|
||||
- "15672:15672"
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
|
||||
minio:
|
||||
image: minio/minio:latest
|
||||
restart: unless-stopped
|
||||
command: server /data --console-address ":9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: minioadmin
|
||||
MINIO_ROOT_PASSWORD: minioadmin
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
|
||||
nats:
|
||||
image: nats:2-alpine
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "4222:4222"
|
||||
- "8222:8222"
|
||||
|
||||
volumes:
|
||||
evolution_data:
|
||||
evolution_logs:
|
||||
postgres_data:
|
||||
rabbitmq_data:
|
||||
minio_data:
|
||||
```
|
||||
|
||||
**Acessos:**
|
||||
- Evolution GO: http://localhost:4000
|
||||
- Swagger: http://localhost:4000/swagger/index.html
|
||||
- RabbitMQ: http://localhost:15672 (admin/admin)
|
||||
- MinIO: http://localhost:9001 (minioadmin/minioadmin)
|
||||
|
||||
### Configurações Avançadas
|
||||
|
||||
#### Arquivo .env
|
||||
|
||||
```bash
|
||||
# .env
|
||||
EVOLUTION_VERSION=latest
|
||||
POSTGRES_VERSION=15-alpine
|
||||
|
||||
# Portas
|
||||
EVOLUTION_PORT=4000
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
# Credenciais
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=senha_forte
|
||||
RABBITMQ_USER=admin
|
||||
RABBITMQ_PASS=senha_forte
|
||||
|
||||
# Evolution GO
|
||||
GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db
|
||||
CLIENT_NAME=evolution-prod
|
||||
```
|
||||
|
||||
Referência no compose:
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
image: evoapicloud/evolution-go:${EVOLUTION_VERSION:-latest}
|
||||
ports:
|
||||
- "${EVOLUTION_PORT:-4000}:4000"
|
||||
environment:
|
||||
GLOBAL_API_KEY: "${GLOBAL_API_KEY}"
|
||||
```
|
||||
|
||||
#### Health Checks
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--spider", "http://localhost:4000/server/ok"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
|
||||
postgres:
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
rabbitmq:
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "ping"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
```
|
||||
|
||||
#### Resource Limits
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '2.0'
|
||||
memory: 2G
|
||||
reservations:
|
||||
cpus: '0.5'
|
||||
memory: 512M
|
||||
|
||||
postgres:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '1.0'
|
||||
memory: 1G
|
||||
reservations:
|
||||
cpus: '0.25'
|
||||
memory: 256M
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Deploy com Docker Swarm
|
||||
|
||||
### Inicialização
|
||||
|
||||
```bash
|
||||
# Manager node
|
||||
docker swarm init --advertise-addr 192.168.1.10
|
||||
|
||||
# Worker nodes
|
||||
docker swarm join --token SWMTKN-1-xxxxx 192.168.1.10:2377
|
||||
|
||||
# Verificar cluster
|
||||
docker node ls
|
||||
```
|
||||
|
||||
### Preparação
|
||||
|
||||
```bash
|
||||
# Volumes
|
||||
docker volume create evolution_go_data
|
||||
docker volume create evolution_go_logs
|
||||
|
||||
# Rede
|
||||
docker network create --driver overlay network_public
|
||||
```
|
||||
|
||||
### docker-compose.swarm.yml
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
evolution_go:
|
||||
image: evoapicloud/evolution-go:latest
|
||||
networks:
|
||||
- network_public
|
||||
environment:
|
||||
SERVER_PORT: 4000
|
||||
GLOBAL_API_KEY: "sua-chave-api"
|
||||
POSTGRES_AUTH_DB: "postgresql://user:pass@postgres:5432/evogo_auth"
|
||||
POSTGRES_USERS_DB: "postgresql://user:pass@postgres:5432/evogo_users"
|
||||
|
||||
volumes:
|
||||
- evolution_go_data:/app/dbdata
|
||||
- evolution_go_logs:/app/logs
|
||||
|
||||
deploy:
|
||||
replicas: 3
|
||||
placement:
|
||||
constraints:
|
||||
- node.role == worker
|
||||
restart_policy:
|
||||
condition: on-failure
|
||||
delay: 5s
|
||||
max_attempts: 3
|
||||
window: 120s
|
||||
update_config:
|
||||
parallelism: 1
|
||||
delay: 10s
|
||||
failure_action: rollback
|
||||
order: start-first
|
||||
rollback_config:
|
||||
parallelism: 1
|
||||
delay: 5s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.evolution.rule=Host(`evolution.domain.com`)
|
||||
- traefik.http.routers.evolution.entrypoints=websecure
|
||||
- traefik.http.routers.evolution.tls.certresolver=letsencrypt
|
||||
- traefik.http.services.evolution.loadbalancer.server.port=4000
|
||||
|
||||
volumes:
|
||||
evolution_go_data:
|
||||
external: true
|
||||
evolution_go_logs:
|
||||
external: true
|
||||
|
||||
networks:
|
||||
network_public:
|
||||
external: true
|
||||
```
|
||||
|
||||
### Deploy e Gerenciamento
|
||||
|
||||
```bash
|
||||
# Deploy
|
||||
docker stack deploy -c docker-compose.swarm.yml evolution
|
||||
|
||||
# Status
|
||||
docker stack ls
|
||||
docker service ls
|
||||
docker service ps evolution_evolution_go
|
||||
|
||||
# Logs
|
||||
docker service logs evolution_evolution_go -f
|
||||
|
||||
# Escalar
|
||||
docker service scale evolution_evolution_go=5
|
||||
|
||||
# Atualizar (rolling update)
|
||||
docker service update --image evoapicloud/evolution-go:v1.2.0 evolution_evolution_go
|
||||
|
||||
# Remover
|
||||
docker stack rm evolution
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Deploy com Kubernetes
|
||||
|
||||
### Manifests Básicos
|
||||
|
||||
#### Namespace
|
||||
|
||||
```yaml
|
||||
# namespace.yaml
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: evolution-go
|
||||
```
|
||||
|
||||
#### ConfigMap
|
||||
|
||||
```yaml
|
||||
# configmap.yaml
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: evolution-config
|
||||
namespace: evolution-go
|
||||
data:
|
||||
SERVER_PORT: "4000"
|
||||
CLIENT_NAME: "evolution"
|
||||
WADEBUG: "INFO"
|
||||
LOGTYPE: "console"
|
||||
CONNECT_ON_STARTUP: "false"
|
||||
WEBHOOK_FILES: "true"
|
||||
DATABASE_SAVE_MESSAGES: "false"
|
||||
```
|
||||
|
||||
#### Secrets
|
||||
|
||||
```bash
|
||||
kubectl create secret generic evolution-secrets \
|
||||
--from-literal=GLOBAL_API_KEY=$(uuidgen) \
|
||||
--from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 32) \
|
||||
--namespace=evolution-go
|
||||
```
|
||||
|
||||
#### Deployment
|
||||
|
||||
```yaml
|
||||
# deployment.yaml
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: evolution-go
|
||||
namespace: evolution-go
|
||||
spec:
|
||||
replicas: 3
|
||||
selector:
|
||||
matchLabels:
|
||||
app: evolution-go
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: evolution-go
|
||||
spec:
|
||||
containers:
|
||||
- name: evolution-go
|
||||
image: evoapicloud/evolution-go:latest
|
||||
ports:
|
||||
- containerPort: 4000
|
||||
env:
|
||||
- name: SERVER_PORT
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: evolution-config
|
||||
key: SERVER_PORT
|
||||
- name: GLOBAL_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: evolution-secrets
|
||||
key: GLOBAL_API_KEY
|
||||
resources:
|
||||
requests:
|
||||
memory: "512Mi"
|
||||
cpu: "500m"
|
||||
limits:
|
||||
memory: "2Gi"
|
||||
cpu: "2000m"
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /server/ok
|
||||
port: 4000
|
||||
initialDelaySeconds: 30
|
||||
periodSeconds: 10
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /server/ok
|
||||
port: 4000
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- name: evolution-data
|
||||
mountPath: /app/dbdata
|
||||
- name: evolution-logs
|
||||
mountPath: /app/logs
|
||||
volumes:
|
||||
- name: evolution-data
|
||||
persistentVolumeClaim:
|
||||
claimName: evolution-data-pvc
|
||||
- name: evolution-logs
|
||||
persistentVolumeClaim:
|
||||
claimName: evolution-logs-pvc
|
||||
```
|
||||
|
||||
#### Service
|
||||
|
||||
```yaml
|
||||
# service.yaml
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: evolution-go-service
|
||||
namespace: evolution-go
|
||||
spec:
|
||||
type: LoadBalancer
|
||||
selector:
|
||||
app: evolution-go
|
||||
ports:
|
||||
- port: 4000
|
||||
targetPort: 4000
|
||||
```
|
||||
|
||||
#### Ingress
|
||||
|
||||
```yaml
|
||||
# ingress.yaml
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: evolution-ingress
|
||||
namespace: evolution-go
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: "nginx"
|
||||
cert-manager.io/cluster-issuer: "letsencrypt-prod"
|
||||
spec:
|
||||
tls:
|
||||
- hosts:
|
||||
- evolution.domain.com
|
||||
secretName: evolution-tls
|
||||
rules:
|
||||
- host: evolution.domain.com
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: evolution-go-service
|
||||
port:
|
||||
number: 4000
|
||||
```
|
||||
|
||||
#### HorizontalPodAutoscaler
|
||||
|
||||
```yaml
|
||||
# hpa.yaml
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
metadata:
|
||||
name: evolution-hpa
|
||||
namespace: evolution-go
|
||||
spec:
|
||||
scaleTargetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: evolution-go
|
||||
minReplicas: 3
|
||||
maxReplicas: 10
|
||||
metrics:
|
||||
- type: Resource
|
||||
resource:
|
||||
name: cpu
|
||||
target:
|
||||
type: Utilization
|
||||
averageUtilization: 70
|
||||
- type: Resource
|
||||
resource:
|
||||
name: memory
|
||||
target:
|
||||
type: Utilization
|
||||
averageUtilization: 80
|
||||
```
|
||||
|
||||
### Deploy Kubernetes
|
||||
|
||||
```bash
|
||||
# Aplicar manifests
|
||||
kubectl apply -f namespace.yaml
|
||||
kubectl apply -f configmap.yaml
|
||||
kubectl apply -f secrets.yaml
|
||||
kubectl apply -f deployment.yaml
|
||||
kubectl apply -f service.yaml
|
||||
kubectl apply -f ingress.yaml
|
||||
kubectl apply -f hpa.yaml
|
||||
|
||||
# Verificar
|
||||
kubectl get all -n evolution-go
|
||||
kubectl get pods -n evolution-go
|
||||
|
||||
# Logs
|
||||
kubectl logs -f deployment/evolution-go -n evolution-go
|
||||
|
||||
# Escalar
|
||||
kubectl scale deployment evolution-go --replicas=5 -n evolution-go
|
||||
|
||||
# Atualizar
|
||||
kubectl set image deployment/evolution-go \
|
||||
evolution-go=evoapicloud/evolution-go:v1.2.0 \
|
||||
-n evolution-go
|
||||
|
||||
# Rollback
|
||||
kubectl rollout undo deployment/evolution-go -n evolution-go
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Otimização e Gestão
|
||||
|
||||
### Gestão de Volumes
|
||||
|
||||
#### Backup
|
||||
|
||||
```bash
|
||||
# Backup volume
|
||||
docker run --rm \
|
||||
-v evolution_data:/data \
|
||||
-v $(pwd):/backup \
|
||||
alpine tar czf /backup/backup-$(date +%Y%m%d).tar.gz -C /data .
|
||||
|
||||
# Restaurar
|
||||
docker run --rm \
|
||||
-v evolution_data:/data \
|
||||
-v $(pwd):/backup \
|
||||
alpine tar xzf /backup/backup-20250111.tar.gz -C /data
|
||||
```
|
||||
|
||||
### Logging
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
```
|
||||
|
||||
### Boas Práticas
|
||||
|
||||
**Segurança:**
|
||||
- Não executar containers como root
|
||||
- Usar secrets para credenciais
|
||||
- Habilitar HTTPS em produção
|
||||
- Configurar resource limits
|
||||
- Implementar health checks
|
||||
|
||||
**Performance:**
|
||||
- Definir resource requests/limits
|
||||
- Usar health checks
|
||||
- Implementar HPA (Kubernetes)
|
||||
- Configurar connection pooling
|
||||
|
||||
**Monitoramento:**
|
||||
- Coletar logs centralizados
|
||||
- Implementar métricas (Prometheus)
|
||||
- Configurar alertas
|
||||
- Dashboard de visualização (Grafana)
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Container Reiniciando
|
||||
|
||||
```bash
|
||||
# Ver logs
|
||||
docker-compose logs evolution-go
|
||||
|
||||
# Verificar variáveis obrigatórias
|
||||
# - GLOBAL_API_KEY
|
||||
# - POSTGRES_*_DB
|
||||
```
|
||||
|
||||
### Conectividade PostgreSQL
|
||||
|
||||
```bash
|
||||
# Testar conexão
|
||||
docker-compose exec evolution-go ping postgres
|
||||
|
||||
# Verificar porta
|
||||
docker-compose exec evolution-go nc -zv postgres 5432
|
||||
|
||||
# Inspecionar rede
|
||||
docker network inspect evolution_network
|
||||
```
|
||||
|
||||
### Sem Espaço em Disco
|
||||
|
||||
```bash
|
||||
# Ver uso
|
||||
docker system df
|
||||
|
||||
# Limpar
|
||||
docker container prune
|
||||
docker image prune
|
||||
docker volume prune # CUIDADO: apaga volumes não utilizados
|
||||
docker system prune -a
|
||||
```
|
||||
|
||||
### OOM (Out of Memory)
|
||||
|
||||
```bash
|
||||
# Ver eventos OOM
|
||||
docker events --filter 'event=oom'
|
||||
|
||||
# Ver uso de memória
|
||||
docker stats evolution-go
|
||||
|
||||
# Aumentar limite
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 4G
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Comandos Úteis
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
docker-compose up -d # Iniciar
|
||||
docker-compose ps # Status
|
||||
docker-compose logs -f # Logs
|
||||
docker-compose stop # Parar
|
||||
docker-compose restart # Reiniciar
|
||||
docker-compose down # Remover
|
||||
docker-compose pull # Atualizar imagens
|
||||
```
|
||||
|
||||
### Docker Swarm
|
||||
|
||||
```bash
|
||||
docker stack deploy -c file.yml name # Deploy
|
||||
docker stack ls # Listar stacks
|
||||
docker service ls # Listar serviços
|
||||
docker service logs name -f # Logs
|
||||
docker service scale name=N # Escalar
|
||||
docker stack rm name # Remover
|
||||
```
|
||||
|
||||
### Kubernetes
|
||||
|
||||
```bash
|
||||
kubectl apply -f file.yaml # Aplicar
|
||||
kubectl get all -n namespace # Listar recursos
|
||||
kubectl logs -f deployment/name # Logs
|
||||
kubectl scale deployment name --replicas=N # Escalar
|
||||
kubectl delete -f file.yaml # Deletar
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,732 @@
|
||||
# Segurança e Hardening
|
||||
|
||||
Guia de práticas de segurança para ambientes de produção do Evolution GO.
|
||||
|
||||
## Índice
|
||||
|
||||
- [Princípios de Segurança](#princípios-de-segurança)
|
||||
- [Autenticação e API Keys](#autenticação-e-api-keys)
|
||||
- [Gestão de Secrets](#gestão-de-secrets)
|
||||
- [Segurança de Rede](#segurança-de-rede)
|
||||
- [Hardening de Containers](#hardening-de-containers)
|
||||
- [SSL/TLS](#ssltls)
|
||||
- [Segurança do Banco de Dados](#segurança-do-banco-de-dados)
|
||||
- [Backup Seguro](#backup-seguro)
|
||||
- [Proteção contra Ataques](#proteção-contra-ataques)
|
||||
- [Auditoria e Compliance](#auditoria-e-compliance)
|
||||
- [Resposta a Incidentes](#resposta-a-incidentes)
|
||||
|
||||
---
|
||||
|
||||
## Princípios de Segurança
|
||||
|
||||
### Defense in Depth
|
||||
|
||||
Implementar múltiplas camadas de proteção:
|
||||
- Autenticação forte
|
||||
- Firewall e isolamento de rede
|
||||
- Criptografia em trânsito e repouso
|
||||
- Monitoramento e auditoria
|
||||
- Backup e disaster recovery
|
||||
|
||||
### Least Privilege
|
||||
|
||||
Conceder apenas permissões mínimas necessárias:
|
||||
- Containers não executam como root
|
||||
- Credenciais com escopo limitado
|
||||
- Acesso à rede restrito
|
||||
- Segregação de ambientes
|
||||
|
||||
### Security by Default
|
||||
|
||||
- Configurações seguras desde a instalação
|
||||
- HTTPS obrigatório em produção
|
||||
- Logs de auditoria habilitados
|
||||
- Credenciais fortes exigidas
|
||||
|
||||
### Requisitos por Ambiente
|
||||
|
||||
| Ambiente | Segurança Mínima |
|
||||
|----------|------------------|
|
||||
| **Desenvolvimento** | API Key forte, senhas não-padrão |
|
||||
| **Staging** | + Firewall, backup, logs |
|
||||
| **Produção** | + HTTPS, monitoramento, auditoria, secrets management |
|
||||
|
||||
---
|
||||
|
||||
## Autenticação e API Keys
|
||||
|
||||
### Geração de API Keys
|
||||
|
||||
Utilize chaves criptograficamente seguras:
|
||||
|
||||
```bash
|
||||
# UUID v4 (recomendado)
|
||||
uuidgen
|
||||
|
||||
# 64 caracteres hexadecimais
|
||||
openssl rand -hex 32
|
||||
|
||||
# URL-safe base64
|
||||
python3 -c "import secrets; print(secrets.token_urlsafe(32))"
|
||||
```
|
||||
|
||||
**Exemplo de chave forte:**
|
||||
```
|
||||
df16caad-d0d2-41b2-bec5-75b90048a0db
|
||||
```
|
||||
|
||||
**Evitar:**
|
||||
- Valores padrão ou previsíveis
|
||||
- Senhas comuns ou sequências
|
||||
- Reutilização de chaves entre ambientes
|
||||
|
||||
### Rotação de Chaves
|
||||
|
||||
**Política recomendada:**
|
||||
- Rotação periódica (90 dias)
|
||||
- Rotação imediata em caso de comprometimento
|
||||
- Manter período de transição para atualização de clientes
|
||||
|
||||
**Processo de rotação:**
|
||||
|
||||
1. Gerar nova chave
|
||||
2. Atualizar configuração do servidor
|
||||
3. Notificar clientes integradores
|
||||
4. Estabelecer deadline para migração
|
||||
5. Desabilitar chave antiga
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
Implementar limitação de requisições por API Key via NGINX:
|
||||
|
||||
```nginx
|
||||
http {
|
||||
map $http_apikey $limit_key {
|
||||
default $http_apikey;
|
||||
"" $binary_remote_addr;
|
||||
}
|
||||
|
||||
limit_req_zone $limit_key zone=api_limit:10m rate=100r/s;
|
||||
|
||||
server {
|
||||
location / {
|
||||
limit_req zone=api_limit burst=200 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_pass http://evolution-go:4000;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Gestão de Secrets
|
||||
|
||||
### Docker Secrets (Swarm)
|
||||
|
||||
```bash
|
||||
# Criar secrets
|
||||
echo "senha_postgres" | docker secret create postgres_password -
|
||||
echo "$(uuidgen)" | docker secret create evolution_api_key -
|
||||
|
||||
# docker-compose.swarm.yml
|
||||
services:
|
||||
evolution-go:
|
||||
secrets:
|
||||
- evolution_api_key
|
||||
- postgres_password
|
||||
environment:
|
||||
GLOBAL_API_KEY_FILE: /run/secrets/evolution_api_key
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
|
||||
secrets:
|
||||
evolution_api_key:
|
||||
external: true
|
||||
postgres_password:
|
||||
external: true
|
||||
```
|
||||
|
||||
### Kubernetes Secrets
|
||||
|
||||
```bash
|
||||
# Criar secrets
|
||||
kubectl create secret generic evolution-secrets \
|
||||
--from-literal=GLOBAL_API_KEY=$(uuidgen) \
|
||||
--from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 32) \
|
||||
--namespace=evolution-go
|
||||
|
||||
# Habilitar encryption at rest
|
||||
# https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/
|
||||
```
|
||||
|
||||
```yaml
|
||||
# deployment.yaml
|
||||
env:
|
||||
- name: GLOBAL_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: evolution-secrets
|
||||
key: GLOBAL_API_KEY
|
||||
- name: POSTGRES_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: evolution-secrets
|
||||
key: POSTGRES_PASSWORD
|
||||
```
|
||||
|
||||
### HashiCorp Vault
|
||||
|
||||
```yaml
|
||||
# vault-agent-config.hcl
|
||||
vault {
|
||||
address = "https://vault.seudominio.com:8200"
|
||||
}
|
||||
|
||||
auto_auth {
|
||||
method {
|
||||
type = "kubernetes"
|
||||
config = {
|
||||
role = "evolution-go"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template {
|
||||
source = "/vault/configs/.env.tpl"
|
||||
destination = "/app/.env"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Segurança de Rede
|
||||
|
||||
### Firewall (iptables)
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# firewall-setup.sh
|
||||
|
||||
# Políticas padrão
|
||||
iptables -P INPUT DROP
|
||||
iptables -P FORWARD DROP
|
||||
iptables -P OUTPUT ACCEPT
|
||||
|
||||
# Loopback
|
||||
iptables -A INPUT -i lo -j ACCEPT
|
||||
|
||||
# Conexões estabelecidas
|
||||
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
|
||||
|
||||
# SSH com rate limiting
|
||||
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set
|
||||
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
|
||||
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
|
||||
|
||||
# HTTP/HTTPS restrito à rede interna
|
||||
iptables -A INPUT -p tcp --dport 80 -s 10.0.1.0/24 -j ACCEPT
|
||||
iptables -A INPUT -p tcp --dport 443 -s 10.0.1.0/24 -j ACCEPT
|
||||
|
||||
# Docker network
|
||||
iptables -A INPUT -s 172.16.0.0/12 -j ACCEPT
|
||||
|
||||
# Drop inválidos
|
||||
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
|
||||
|
||||
# Salvar regras
|
||||
iptables-save > /etc/iptables/rules.v4
|
||||
```
|
||||
|
||||
### UFW (Alternativa Simplificada)
|
||||
|
||||
```bash
|
||||
sudo apt-get install ufw
|
||||
|
||||
# Configurar padrões
|
||||
sudo ufw default deny incoming
|
||||
sudo ufw default allow outgoing
|
||||
|
||||
# Permitir serviços
|
||||
sudo ufw allow 22/tcp # SSH
|
||||
sudo ufw allow 80/tcp # HTTP
|
||||
sudo ufw allow 443/tcp # HTTPS
|
||||
|
||||
# Ativar
|
||||
sudo ufw enable
|
||||
|
||||
# Status
|
||||
sudo ufw status
|
||||
```
|
||||
|
||||
### Isolamento de Redes Docker
|
||||
|
||||
```yaml
|
||||
networks:
|
||||
frontend:
|
||||
driver: overlay
|
||||
driver_opts:
|
||||
encrypted: "true"
|
||||
|
||||
backend:
|
||||
driver: overlay
|
||||
driver_opts:
|
||||
encrypted: "true"
|
||||
internal: true # Sem acesso externo
|
||||
|
||||
services:
|
||||
evolution-go:
|
||||
networks:
|
||||
- frontend
|
||||
- backend
|
||||
|
||||
postgres:
|
||||
networks:
|
||||
- backend # Apenas rede interna
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Hardening de Containers
|
||||
|
||||
### Não Executar como Root
|
||||
|
||||
```dockerfile
|
||||
FROM alpine:3.19.1
|
||||
|
||||
RUN addgroup -g 1000 evolution && \
|
||||
adduser -D -u 1000 -G evolution evolution
|
||||
|
||||
WORKDIR /app
|
||||
COPY --chown=evolution:evolution server .
|
||||
|
||||
USER evolution
|
||||
|
||||
ENTRYPOINT ["/app/server"]
|
||||
```
|
||||
|
||||
### Filesystem Read-Only
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
volumes:
|
||||
- evolution_data:/app/dbdata
|
||||
- evolution_logs:/app/logs
|
||||
```
|
||||
|
||||
### Security Options
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
- apparmor:docker-default
|
||||
- seccomp:default.json
|
||||
cap_drop:
|
||||
- ALL
|
||||
cap_add:
|
||||
- NET_BIND_SERVICE # Apenas se necessário
|
||||
```
|
||||
|
||||
### Limites de Recursos
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '2.0'
|
||||
memory: 2G
|
||||
pids: 100
|
||||
reservations:
|
||||
cpus: '1.0'
|
||||
memory: 1G
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 1024
|
||||
hard: 2048
|
||||
nproc: 64
|
||||
```
|
||||
|
||||
### Scan de Vulnerabilidades
|
||||
|
||||
```bash
|
||||
# Trivy
|
||||
trivy image evoapicloud/evolution-go:latest
|
||||
|
||||
# Apenas críticas
|
||||
trivy image --severity CRITICAL evoapicloud/evolution-go:latest
|
||||
|
||||
# Docker Scout
|
||||
docker scout cves evoapicloud/evolution-go:latest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SSL/TLS
|
||||
|
||||
### Obtenção de Certificados (Let's Encrypt)
|
||||
|
||||
```bash
|
||||
# Instalar Certbot
|
||||
sudo apt-get install certbot
|
||||
|
||||
# Gerar certificado
|
||||
sudo certbot certonly --standalone -d evolution.seudominio.com
|
||||
|
||||
# Certificados em:
|
||||
# /etc/letsencrypt/live/evolution.seudominio.com/
|
||||
```
|
||||
|
||||
### Configuração NGINX
|
||||
|
||||
```nginx
|
||||
# Redirecionar HTTP → HTTPS
|
||||
server {
|
||||
listen 80;
|
||||
server_name evolution.seudominio.com;
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
|
||||
# HTTPS
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name evolution.seudominio.com;
|
||||
|
||||
# Certificados
|
||||
ssl_certificate /etc/letsencrypt/live/evolution.seudominio.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/evolution.seudominio.com/privkey.pem;
|
||||
|
||||
# Protocolos e ciphers
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
|
||||
ssl_prefer_server_ciphers off;
|
||||
|
||||
# HSTS
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
|
||||
|
||||
# OCSP Stapling
|
||||
ssl_stapling on;
|
||||
ssl_stapling_verify on;
|
||||
ssl_trusted_certificate /etc/letsencrypt/live/evolution.seudominio.com/chain.pem;
|
||||
|
||||
# Security Headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "no-referrer-when-downgrade" always;
|
||||
|
||||
# Ocultar server tokens
|
||||
server_tokens off;
|
||||
|
||||
location / {
|
||||
proxy_pass http://evolution-go:4000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_hide_header X-Powered-By;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Renovação Automática
|
||||
|
||||
```bash
|
||||
# Testar renovação
|
||||
sudo certbot renew --dry-run
|
||||
|
||||
# Agendar via cron
|
||||
sudo crontab -e
|
||||
|
||||
# Adicionar (renovação diária às 3h)
|
||||
0 3 * * * certbot renew --quiet && systemctl reload nginx
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Segurança do Banco de Dados
|
||||
|
||||
### PostgreSQL Hardening
|
||||
|
||||
```ini
|
||||
# postgresql.conf
|
||||
|
||||
# SSL obrigatório
|
||||
ssl = on
|
||||
ssl_cert_file = '/etc/ssl/certs/server.crt'
|
||||
ssl_key_file = '/etc/ssl/private/server.key'
|
||||
|
||||
# Auditoria
|
||||
log_connections = on
|
||||
log_disconnections = on
|
||||
log_duration = on
|
||||
log_statement = 'mod' # INSERT, UPDATE, DELETE
|
||||
|
||||
# Senha forte obrigatória
|
||||
password_encryption = scram-sha-256
|
||||
```
|
||||
|
||||
```ini
|
||||
# pg_hba.conf
|
||||
|
||||
# Apenas SSL
|
||||
hostssl evogo_auth evolution 10.0.0.0/8 scram-sha-256
|
||||
hostssl evogo_users evolution 10.0.0.0/8 scram-sha-256
|
||||
|
||||
# Rejeitar sem SSL
|
||||
hostnossl all all 0.0.0.0/0 reject
|
||||
```
|
||||
|
||||
### Backup Criptografado
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# backup-encrypted.sh
|
||||
|
||||
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||
BACKUP_FILE="postgres_${TIMESTAMP}.sql.gz.gpg"
|
||||
|
||||
# Dump e criptografar
|
||||
docker exec postgres pg_dumpall -U postgres | \
|
||||
gzip | \
|
||||
gpg --symmetric --cipher-algo AES256 --output "/backups/${BACKUP_FILE}"
|
||||
|
||||
# Upload S3 com SSE
|
||||
aws s3 cp "/backups/${BACKUP_FILE}" \
|
||||
"s3://bucket-backup/postgres/${BACKUP_FILE}" \
|
||||
--server-side-encryption AES256
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Backup Seguro
|
||||
|
||||
### Estratégia 3-2-1
|
||||
|
||||
- 3 cópias dos dados
|
||||
- 2 mídias diferentes
|
||||
- 1 cópia offsite
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# backup-secure.sh
|
||||
|
||||
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||
BACKUP_DIR="/backups"
|
||||
S3_BUCKET="s3://backup-bucket"
|
||||
GPG_KEY="[email protected]"
|
||||
|
||||
# PostgreSQL
|
||||
docker exec postgres pg_dumpall -U postgres | \
|
||||
gzip | \
|
||||
gpg --encrypt --recipient $GPG_KEY --output "${BACKUP_DIR}/postgres_${TIMESTAMP}.sql.gz.gpg"
|
||||
|
||||
# Volumes
|
||||
docker run --rm \
|
||||
-v evolution_data:/data \
|
||||
-v ${BACKUP_DIR}:/backup \
|
||||
alpine tar czf - -C /data . | \
|
||||
gpg --encrypt --recipient $GPG_KEY --output "${BACKUP_DIR}/evolution_data_${TIMESTAMP}.tar.gz.gpg"
|
||||
|
||||
# Upload S3 com KMS
|
||||
aws s3 cp "${BACKUP_DIR}/postgres_${TIMESTAMP}.sql.gz.gpg" \
|
||||
"${S3_BUCKET}/postgres/" \
|
||||
--server-side-encryption aws:kms \
|
||||
--ssekms-key-id alias/backup-key
|
||||
|
||||
# Limpeza (30 dias)
|
||||
find ${BACKUP_DIR} -name "*.gpg" -mtime +30 -delete
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Proteção contra Ataques
|
||||
|
||||
### DDoS Protection
|
||||
|
||||
**NGINX Rate Limiting:**
|
||||
|
||||
```nginx
|
||||
http {
|
||||
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
|
||||
limit_conn conn_limit 10;
|
||||
|
||||
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
|
||||
|
||||
server {
|
||||
location / {
|
||||
limit_req zone=req_limit burst=20 nodelay;
|
||||
proxy_pass http://evolution-go:4000;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Cloudflare:** Habilitar proteção DDoS no painel.
|
||||
|
||||
### SQL Injection
|
||||
|
||||
Evolution GO usa GORM (ORM) que previne SQL injection por padrão através de prepared statements.
|
||||
|
||||
### Brute-Force Protection (Fail2ban)
|
||||
|
||||
```bash
|
||||
sudo apt-get install fail2ban
|
||||
```
|
||||
|
||||
```ini
|
||||
# /etc/fail2ban/jail.local
|
||||
[nginx-req-limit]
|
||||
enabled = true
|
||||
filter = nginx-req-limit
|
||||
logpath = /var/log/nginx/error.log
|
||||
maxretry = 5
|
||||
findtime = 600
|
||||
bantime = 3600
|
||||
```
|
||||
|
||||
```ini
|
||||
# /etc/fail2ban/filter.d/nginx-req-limit.conf
|
||||
[Definition]
|
||||
failregex = limiting requests, excess:.* by zone.*client: <HOST>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Auditoria e Compliance
|
||||
|
||||
### LGPD/GDPR
|
||||
|
||||
**Direito ao esquecimento:**
|
||||
|
||||
```sql
|
||||
CREATE PROCEDURE delete_user_data(user_phone VARCHAR)
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
DELETE FROM messages WHERE phone = user_phone;
|
||||
DELETE FROM contacts WHERE phone = user_phone;
|
||||
DELETE FROM instances WHERE owner_phone = user_phone;
|
||||
|
||||
INSERT INTO audit_log (action, details, timestamp)
|
||||
VALUES ('user_data_deleted', user_phone, NOW());
|
||||
|
||||
COMMIT;
|
||||
END;
|
||||
$$;
|
||||
```
|
||||
|
||||
**Retenção de dados:**
|
||||
|
||||
```sql
|
||||
-- Deletar mensagens antigas (30 dias)
|
||||
DELETE FROM messages WHERE timestamp < NOW() - INTERVAL '30 days';
|
||||
```
|
||||
|
||||
### Logging de Auditoria
|
||||
|
||||
```yaml
|
||||
services:
|
||||
evolution-go:
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
labels: "service,environment"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Resposta a Incidentes
|
||||
|
||||
### Plano de Resposta
|
||||
|
||||
**1. Detecção**
|
||||
- Alertas automatizados
|
||||
- Monitoramento de logs
|
||||
- Relatórios de usuários
|
||||
|
||||
**2. Contenção**
|
||||
- Isolar sistemas afetados
|
||||
- Revogar credenciais comprometidas
|
||||
- Bloquear IPs maliciosos
|
||||
- Capturar evidências
|
||||
|
||||
**3. Erradicação**
|
||||
- Aplicar patches
|
||||
- Atualizar imagens
|
||||
- Revisar logs de auditoria
|
||||
- Remover backdoors
|
||||
|
||||
**4. Recuperação**
|
||||
- Restaurar de backup
|
||||
- Validar integridade
|
||||
- Monitorar por 48h
|
||||
|
||||
**5. Pós-Incidente**
|
||||
- Documentar lições aprendidas
|
||||
- Atualizar runbooks
|
||||
- Treinar equipe
|
||||
|
||||
### Forensics
|
||||
|
||||
```bash
|
||||
# Capturar estado do container
|
||||
docker commit container_suspeito forensics-image
|
||||
docker save forensics-image > forensics-image.tar
|
||||
|
||||
# Coletar logs
|
||||
docker logs container_suspeito > logs_suspeito.txt
|
||||
|
||||
# Inspecionar
|
||||
docker inspect container_suspeito > inspect_suspeito.json
|
||||
|
||||
# Exportar filesystem
|
||||
docker export container_suspeito > filesystem_suspeito.tar
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checklist de Segurança
|
||||
|
||||
### Crítico
|
||||
- [ ] API Keys fortes (UUID)
|
||||
- [ ] HTTPS habilitado
|
||||
- [ ] Secrets em vault/secrets manager
|
||||
- [ ] Firewall configurado
|
||||
- [ ] Backups automáticos funcionando
|
||||
|
||||
### Importante
|
||||
- [ ] Containers não executam como root
|
||||
- [ ] Isolamento de redes Docker
|
||||
- [ ] Limites de recursos definidos
|
||||
- [ ] Logs de auditoria ativos
|
||||
- [ ] Monitoramento configurado
|
||||
|
||||
### Recomendado
|
||||
- [ ] Scan de vulnerabilidades regular
|
||||
- [ ] Plano de resposta a incidentes
|
||||
- [ ] Testes de restauração de backup
|
||||
- [ ] Documentação de segurança
|
||||
- [ ] Treinamento da equipe
|
||||
|
||||
---
|
||||
|
||||
## Recursos Adicionais
|
||||
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
- [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker)
|
||||
- [Kubernetes Security Best Practices](https://kubernetes.io/docs/concepts/security/)
|
||||
- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,297 @@
|
||||
# Como Contribuir
|
||||
|
||||
Guia para contribuir com o Evolution GO.
|
||||
|
||||
## Índice
|
||||
|
||||
- [Como Contribuir](#como-contribuir)
|
||||
- [Código de Conduta](#código-de-conduta)
|
||||
- [Reportando Bugs](#reportando-bugs)
|
||||
- [Sugerindo Features](#sugerindo-features)
|
||||
- [Pull Requests](#pull-requests)
|
||||
- [Padrões de Código](#padrões-de-código)
|
||||
- [Processo de Review](#processo-de-review)
|
||||
|
||||
---
|
||||
|
||||
## Como Contribuir
|
||||
|
||||
Contribuições são bem-vindas! Você pode contribuir:
|
||||
|
||||
- 🐛 Reportando bugs
|
||||
- 💡 Sugerindo novas features
|
||||
- 📝 Melhorando documentação
|
||||
- 🔧 Corrigindo bugs
|
||||
- ✨ Implementando features
|
||||
|
||||
---
|
||||
|
||||
## Código de Conduta
|
||||
|
||||
- Seja respeitoso e profissional
|
||||
- Aceite feedback construtivo
|
||||
- Foque no que é melhor para a comunidade
|
||||
- Mostre empatia com outros membros
|
||||
|
||||
---
|
||||
|
||||
## Reportando Bugs
|
||||
|
||||
### Antes de Reportar
|
||||
|
||||
1. Verifique se o bug já foi reportado nas [Issues](https://git.evoai.app/Evolution/evolution-go/issues)
|
||||
2. Teste na versão mais recente
|
||||
3. Colete informações: logs, versão do Go, sistema operacional
|
||||
|
||||
### Template de Bug Report
|
||||
|
||||
```markdown
|
||||
**Descrição do Bug**
|
||||
Descrição clara e concisa do bug.
|
||||
|
||||
**Como Reproduzir**
|
||||
1. Faça X
|
||||
2. Execute Y
|
||||
3. Veja erro Z
|
||||
|
||||
**Comportamento Esperado**
|
||||
O que deveria acontecer.
|
||||
|
||||
**Comportamento Atual**
|
||||
O que está acontecendo.
|
||||
|
||||
**Screenshots/Logs**
|
||||
Se aplicável, adicione screenshots ou logs.
|
||||
|
||||
**Ambiente**
|
||||
- OS: [ex: Ubuntu 22.04]
|
||||
- Go Version: [ex: 1.24.0]
|
||||
- Evolution GO Version: [ex: v1.0.0]
|
||||
- PostgreSQL Version: [ex: 15.2]
|
||||
|
||||
**Informações Adicionais**
|
||||
Qualquer outro contexto sobre o problema.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sugerindo Features
|
||||
|
||||
### Template de Feature Request
|
||||
|
||||
```markdown
|
||||
**Descrição da Feature**
|
||||
Descrição clara da feature proposta.
|
||||
|
||||
**Problema que Resolve**
|
||||
Qual problema esta feature resolve?
|
||||
|
||||
**Solução Proposta**
|
||||
Como você imagina que esta feature funcionaria?
|
||||
|
||||
**Alternativas Consideradas**
|
||||
Outras abordagens que você considerou?
|
||||
|
||||
**Informações Adicionais**
|
||||
Mockups, exemplos, referências, etc.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pull Requests
|
||||
|
||||
### Processo
|
||||
|
||||
1. **Fork** o repositório
|
||||
2. **Clone** seu fork: `git clone https://git.evochat.com/SEU-USUARIO/evolution-go.git`
|
||||
3. **Crie branch**: `git checkout -b feature/minha-feature`
|
||||
4. **Desenvolva** e **commit** suas mudanças
|
||||
5. **Push**: `git push origin feature/minha-feature`
|
||||
6. **Abra PR** no repositório original
|
||||
|
||||
### Checklist do PR
|
||||
|
||||
- [ ] Código segue os padrões do projeto
|
||||
- [ ] Código foi formatado (`make fmt`)
|
||||
- [ ] Lint passou sem erros (`make lint`)
|
||||
- [ ] Documentação foi atualizada (se necessário)
|
||||
- [ ] Swagger foi atualizado (`make swagger`) se alterou endpoints
|
||||
- [ ] Commit messages são descritivas
|
||||
|
||||
### Padrão de Commit
|
||||
|
||||
Use [Conventional Commits](https://www.conventionalcommits.org/):
|
||||
|
||||
```bash
|
||||
# Feature
|
||||
git commit -m "feat: adiciona suporte para envio de áudio"
|
||||
|
||||
# Bug fix
|
||||
git commit -m "fix: corrige erro ao deletar instância"
|
||||
|
||||
# Documentação
|
||||
git commit -m "docs: atualiza guia de instalação"
|
||||
|
||||
# Refatoração
|
||||
git commit -m "refactor: simplifica lógica de conexão"
|
||||
|
||||
# Chore (manutenção)
|
||||
git commit -m "chore: atualiza dependências"
|
||||
|
||||
# Performance
|
||||
git commit -m "perf: otimiza query de listagem de mensagens"
|
||||
```
|
||||
|
||||
### Mensagens de Commit Detalhadas
|
||||
|
||||
```bash
|
||||
git commit -m "feat: adiciona endpoint de busca de mensagens
|
||||
|
||||
- Implementa GET /message/search
|
||||
- Adiciona filtros por data, remetente e texto
|
||||
- Inclui paginação (limit/offset)
|
||||
- Atualiza documentação Swagger
|
||||
|
||||
Closes #42"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Padrões de Código
|
||||
|
||||
### Go Formatting
|
||||
|
||||
```bash
|
||||
# Sempre formate antes de commit
|
||||
make fmt
|
||||
|
||||
# Ou manualmente
|
||||
go fmt ./...
|
||||
goimports -w .
|
||||
```
|
||||
|
||||
### Linting
|
||||
|
||||
```bash
|
||||
# Execute lint
|
||||
make lint
|
||||
|
||||
# Corrige automaticamente quando possível
|
||||
golangci-lint run --fix
|
||||
```
|
||||
|
||||
### Estrutura de Código
|
||||
|
||||
Siga o padrão **Handler → Service → Repository**:
|
||||
|
||||
```go
|
||||
// pkg/mymodule/handler.go
|
||||
package mymodule
|
||||
|
||||
type MyHandler struct {
|
||||
service MyService
|
||||
}
|
||||
|
||||
func (h *MyHandler) Create(c *gin.Context) {
|
||||
// Valida input
|
||||
// Chama service
|
||||
// Retorna response
|
||||
}
|
||||
|
||||
// pkg/mymodule/service.go
|
||||
type MyService interface {
|
||||
Create(dto CreateDTO) (*Model, error)
|
||||
}
|
||||
|
||||
type myService struct {
|
||||
repo MyRepository
|
||||
}
|
||||
|
||||
func (s *myService) Create(dto CreateDTO) (*Model, error) {
|
||||
// Lógica de negócio
|
||||
// Chama repository
|
||||
return model, nil
|
||||
}
|
||||
|
||||
// pkg/mymodule/repository.go
|
||||
type MyRepository interface {
|
||||
Save(model *Model) error
|
||||
}
|
||||
|
||||
type myRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (r *myRepository) Save(model *Model) error {
|
||||
return r.db.Create(model).Error
|
||||
}
|
||||
```
|
||||
|
||||
### Documentação Swagger
|
||||
|
||||
Sempre documente endpoints públicos:
|
||||
|
||||
```go
|
||||
// GetInstance retorna uma instância por ID.
|
||||
//
|
||||
// @Summary Buscar instância
|
||||
// @Description Retorna detalhes de uma instância WhatsApp
|
||||
// @Tags instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceName path string true "Nome da instância"
|
||||
// @Success 200 {object} Instance
|
||||
// @Failure 404 {object} ErrorResponse
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /instance/{instanceName} [get]
|
||||
func (h *InstanceHandler) GetInstance(c *gin.Context) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Processo de Review
|
||||
|
||||
### O que os Reviewers Avaliam
|
||||
|
||||
- ✅ **Funcionalidade**: O código faz o que deveria?
|
||||
- ✅ **Qualidade**: Código limpo, legível e manutenível?
|
||||
- ✅ **Performance**: Há problemas de performance?
|
||||
- ✅ **Segurança**: Há vulnerabilidades?
|
||||
- ✅ **Testes**: Há cobertura adequada? (quando testes existirem)
|
||||
- ✅ **Documentação**: Está atualizada?
|
||||
|
||||
### Timeline Esperado
|
||||
|
||||
- **Primeira revisão**: 1-3 dias úteis
|
||||
- **Revisões subsequentes**: 1-2 dias úteis
|
||||
- **Merge**: Após aprovação de 1+ mantainer
|
||||
|
||||
### Respondendo a Feedbacks
|
||||
|
||||
- Seja receptivo a sugestões
|
||||
- Faça perguntas se não entender
|
||||
- Atualize o código conforme feedback
|
||||
- Force push (`git push -f`) é OK durante review
|
||||
|
||||
### Após o Merge
|
||||
|
||||
- Delete sua branch: `git branch -d feature/minha-feature`
|
||||
- Atualize seu fork: `git pull upstream main`
|
||||
|
||||
---
|
||||
|
||||
## Recursos Úteis
|
||||
|
||||
- **Issues**: https://git.evoai.app/Evolution/evolution-go/issues
|
||||
- **Pull Requests**: https://git.evoai.app/Evolution/evolution-go/merge_requests
|
||||
- **Documentação**: https://git.evoai.app/Evolution/evolution-go/-/wikis
|
||||
- **Go Style Guide**: https://google.github.io/styleguide/go/
|
||||
- **Effective Go**: https://go.dev/doc/effective_go
|
||||
|
||||
---
|
||||
|
||||
**Obrigado por contribuir!** 🎉
|
||||
|
||||
**Mantido por**: Equipe EvoAI Services
|
||||
@@ -0,0 +1,407 @@
|
||||
# Debugging e Troubleshooting
|
||||
|
||||
Guia para resolver problemas comuns no Evolution GO.
|
||||
|
||||
## Índice
|
||||
|
||||
- [Logs e Debug Mode](#logs-e-debug-mode)
|
||||
- [Problemas Comuns](#problemas-comuns)
|
||||
- [Debugging com IDE](#debugging-com-ide)
|
||||
- [Profiling de Performance](#profiling-de-performance)
|
||||
- [Análise de Banco de Dados](#análise-de-banco-de-dados)
|
||||
- [Network Debugging](#network-debugging)
|
||||
- [Ferramentas Úteis](#ferramentas-úteis)
|
||||
|
||||
---
|
||||
|
||||
## Logs e Debug Mode
|
||||
|
||||
### Habilitar Debug Mode
|
||||
|
||||
```env
|
||||
# .env
|
||||
WADEBUG=DEBUG
|
||||
LOGTYPE=console # ou 'file'
|
||||
```
|
||||
|
||||
### Visualizar Logs
|
||||
|
||||
```bash
|
||||
# Logs em console
|
||||
make dev
|
||||
|
||||
# Logs em arquivo
|
||||
tail -f logs/evolution-go.log
|
||||
|
||||
# Docker
|
||||
docker-compose logs -f evolution-go
|
||||
|
||||
# Filtrar logs de erro
|
||||
docker-compose logs evolution-go | grep ERROR
|
||||
```
|
||||
|
||||
### Níveis de Log
|
||||
|
||||
- **DEBUG**: Detalhes de execução (desenvolvimento)
|
||||
- **INFO**: Informações gerais (produção)
|
||||
- **WARN**: Avisos (produção)
|
||||
- **ERROR**: Erros (sempre)
|
||||
|
||||
---
|
||||
|
||||
## Problemas Comuns
|
||||
|
||||
### 1. Erro: "port 4000 already in use"
|
||||
|
||||
**Causa**: Outra aplicação usando a porta 4000.
|
||||
|
||||
**Solução**:
|
||||
|
||||
```bash
|
||||
# Verificar processo usando a porta
|
||||
lsof -i :4000
|
||||
|
||||
# Ou
|
||||
netstat -tuln | grep 4000
|
||||
|
||||
# Matar processo
|
||||
kill -9 <PID>
|
||||
|
||||
# Ou alterar porta no .env
|
||||
SERVER_PORT=4001
|
||||
```
|
||||
|
||||
### 2. Erro: "connection refused" (PostgreSQL)
|
||||
|
||||
**Causa**: PostgreSQL não está rodando ou inacessível.
|
||||
|
||||
**Solução**:
|
||||
|
||||
```bash
|
||||
# Verificar se PostgreSQL está rodando
|
||||
sudo systemctl status postgresql
|
||||
|
||||
# Ou via Docker
|
||||
docker ps | grep postgres
|
||||
|
||||
# Iniciar PostgreSQL
|
||||
sudo systemctl start postgresql
|
||||
|
||||
# Ou via Docker
|
||||
docker start postgres
|
||||
|
||||
# Testar conexão
|
||||
psql -h localhost -U postgres -d evogo_auth
|
||||
```
|
||||
|
||||
### 3. Erro: "database does not exist"
|
||||
|
||||
**Causa**: Databases `evogo_auth` ou `evogo_users` não criados.
|
||||
|
||||
**Solução**:
|
||||
|
||||
```bash
|
||||
# Criar databases
|
||||
sudo -u postgres psql << EOF
|
||||
CREATE DATABASE evogo_auth;
|
||||
CREATE DATABASE evogo_users;
|
||||
EOF
|
||||
|
||||
# Ou via Docker
|
||||
docker exec -i postgres psql -U postgres << EOF
|
||||
CREATE DATABASE evogo_auth;
|
||||
CREATE DATABASE evogo_users;
|
||||
EOF
|
||||
```
|
||||
|
||||
### 4. Erro: "invalid API key"
|
||||
|
||||
**Causa**: API key incorreta ou não configurada.
|
||||
|
||||
**Solução**:
|
||||
|
||||
```bash
|
||||
# Verificar .env
|
||||
cat .env | grep GLOBAL_API_KEY
|
||||
|
||||
# Testar com API key correta
|
||||
curl -H "apikey: SUA-CHAVE" http://localhost:4000/server/ok
|
||||
```
|
||||
|
||||
### 5. QR Code não Aparece
|
||||
|
||||
**Causa**: Instância já conectada ou erro de criação.
|
||||
|
||||
**Solução**:
|
||||
|
||||
```bash
|
||||
# Verificar logs
|
||||
docker-compose logs -f evolution-go | grep QR
|
||||
|
||||
# Deletar e recriar instância
|
||||
curl -X DELETE http://localhost:4000/instance/delete/NOME \
|
||||
-H "apikey: SUA-CHAVE"
|
||||
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE" \
|
||||
-d '{"instanceName": "NOME"}'
|
||||
```
|
||||
|
||||
### 6. Webhook não Funciona
|
||||
|
||||
**Causa**: URL inválida ou endpoint indisponível.
|
||||
|
||||
**Solução**:
|
||||
|
||||
```bash
|
||||
# Testar webhook manualmente
|
||||
curl -X POST https://seu-webhook.com/endpoint \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"test": true}'
|
||||
|
||||
# Verificar logs
|
||||
docker-compose logs evolution-go | grep webhook
|
||||
|
||||
# Verificar configuração
|
||||
curl http://localhost:4000/instance/connectionState/NOME \
|
||||
-H "apikey: SUA-CHAVE"
|
||||
```
|
||||
|
||||
### 7. Mensagem não Envia
|
||||
|
||||
**Causa**: Instância desconectada, número inválido, ou erro de rede.
|
||||
|
||||
**Solução**:
|
||||
|
||||
```bash
|
||||
# Verificar conexão
|
||||
curl http://localhost:4000/instance/connectionState/NOME \
|
||||
-H "apikey: SUA-CHAVE"
|
||||
|
||||
# Verificar logs
|
||||
docker-compose logs -f evolution-go
|
||||
|
||||
# Verificar formato do número
|
||||
# Correto: 5511999999999 (DDI + DDD + número)
|
||||
# Errado: 11999999999, +55 11 99999-9999
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Debugging com IDE
|
||||
|
||||
### VSCode
|
||||
|
||||
1. Abrir `Run and Debug` (Ctrl+Shift+D)
|
||||
2. Selecionar "Launch Evolution GO"
|
||||
3. Adicionar breakpoints (F9)
|
||||
4. Iniciar debug (F5)
|
||||
|
||||
**launch.json**:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Debug Evolution GO",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "debug",
|
||||
"program": "${workspaceFolder}/cmd/evolution-go",
|
||||
"args": ["-dev"],
|
||||
"showLog": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### GoLand
|
||||
|
||||
1. **Run → Debug 'Evolution GO'**
|
||||
2. Adicionar breakpoints (Ctrl+F8)
|
||||
3. Debug com F5
|
||||
|
||||
---
|
||||
|
||||
## Profiling de Performance
|
||||
|
||||
### CPU Profiling
|
||||
|
||||
```bash
|
||||
# Executar com pprof
|
||||
go run cmd/evolution-go/main.go -dev &
|
||||
PID=$!
|
||||
|
||||
# Gerar CPU profile (30 segundos)
|
||||
curl http://localhost:4000/debug/pprof/profile?seconds=30 > cpu.prof
|
||||
|
||||
# Analisar
|
||||
go tool pprof cpu.prof
|
||||
|
||||
# Comandos no pprof:
|
||||
# top10 - Top 10 funções
|
||||
# list <func> - Código da função
|
||||
# web - Visualização gráfica (requer graphviz)
|
||||
```
|
||||
|
||||
### Memory Profiling
|
||||
|
||||
```bash
|
||||
# Heap snapshot
|
||||
curl http://localhost:4000/debug/pprof/heap > heap.prof
|
||||
|
||||
# Analisar
|
||||
go tool pprof heap.prof
|
||||
|
||||
# Visualizar em browser
|
||||
go tool pprof -http=:8081 heap.prof
|
||||
```
|
||||
|
||||
### Goroutine Leaks
|
||||
|
||||
```bash
|
||||
# Ver goroutines ativas
|
||||
curl http://localhost:4000/debug/pprof/goroutine?debug=1
|
||||
|
||||
# Profile de goroutines
|
||||
curl http://localhost:4000/debug/pprof/goroutine > goroutine.prof
|
||||
go tool pprof goroutine.prof
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Análise de Banco de Dados
|
||||
|
||||
### Queries Lentas
|
||||
|
||||
```sql
|
||||
-- Habilitar log de queries lentas (PostgreSQL)
|
||||
ALTER DATABASE evogo_users SET log_min_duration_statement = 1000;
|
||||
|
||||
-- Ver queries lentas
|
||||
SELECT query, calls, total_time, mean_time
|
||||
FROM pg_stat_statements
|
||||
ORDER BY mean_time DESC
|
||||
LIMIT 10;
|
||||
```
|
||||
|
||||
### Ver Conexões Ativas
|
||||
|
||||
```sql
|
||||
-- PostgreSQL
|
||||
SELECT count(*) FROM pg_stat_activity;
|
||||
|
||||
SELECT datname, usename, state, query
|
||||
FROM pg_stat_activity
|
||||
WHERE datname IN ('evogo_auth', 'evogo_users');
|
||||
```
|
||||
|
||||
### Índices Faltantes
|
||||
|
||||
```sql
|
||||
-- Verificar scans sequenciais (ruim)
|
||||
SELECT schemaname, tablename, seq_scan, seq_tup_read
|
||||
FROM pg_stat_user_tables
|
||||
WHERE seq_scan > 0
|
||||
ORDER BY seq_tup_read DESC
|
||||
LIMIT 10;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Network Debugging
|
||||
|
||||
### Testar Conectividade
|
||||
|
||||
```bash
|
||||
# Testar se porta está aberta
|
||||
nc -zv localhost 4000
|
||||
|
||||
# Testar endpoint
|
||||
curl -v http://localhost:4000/server/ok
|
||||
|
||||
# Com proxy
|
||||
curl -x http://proxy:8080 http://localhost:4000/server/ok
|
||||
```
|
||||
|
||||
### Capturar Tráfego HTTP
|
||||
|
||||
```bash
|
||||
# tcpdump
|
||||
sudo tcpdump -i any -A 'port 4000'
|
||||
|
||||
# Wireshark
|
||||
# Filtro: tcp.port == 4000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ferramentas Úteis
|
||||
|
||||
### 1. delve (Go Debugger)
|
||||
|
||||
```bash
|
||||
# Instalar
|
||||
go install github.com/go-delve/delve/cmd/dlv@latest
|
||||
|
||||
# Debug
|
||||
dlv debug cmd/evolution-go/main.go -- -dev
|
||||
|
||||
# Comandos:
|
||||
# break main.main - Breakpoint
|
||||
# continue - Continuar
|
||||
# next - Próxima linha
|
||||
# print var - Imprimir variável
|
||||
```
|
||||
|
||||
### 2. Postman/Insomnia
|
||||
|
||||
Importar collection Swagger:
|
||||
- URL: http://localhost:4000/swagger/doc.json
|
||||
|
||||
### 3. pgAdmin / DBeaver
|
||||
|
||||
Conectar ao PostgreSQL:
|
||||
- Host: localhost
|
||||
- Port: 5432
|
||||
- Database: evogo_users
|
||||
- Username: postgres
|
||||
|
||||
### 4. Docker Stats
|
||||
|
||||
```bash
|
||||
# Ver uso de recursos
|
||||
docker stats evolution-go
|
||||
|
||||
# Inspecionar container
|
||||
docker inspect evolution-go
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checklist de Troubleshooting
|
||||
|
||||
Quando algo não funciona:
|
||||
|
||||
1. ✅ Verificar logs: `docker-compose logs -f`
|
||||
2. ✅ Verificar .env: variáveis corretas?
|
||||
3. ✅ Verificar PostgreSQL: está rodando?
|
||||
4. ✅ Verificar porta: 4000 livre?
|
||||
5. ✅ Verificar API key: está correta?
|
||||
6. ✅ Testar health check: `/server/ok`
|
||||
7. ✅ Verificar Swagger: documentação atualizada?
|
||||
8. ✅ Verificar versão Go: 1.24+?
|
||||
|
||||
---
|
||||
|
||||
## Recursos Adicionais
|
||||
|
||||
- **Go Debugging**: https://go.dev/doc/gdb
|
||||
- **GORM Debugging**: https://gorm.io/docs/logger.html
|
||||
- **Gin Debugging**: https://gin-gonic.com/docs/examples/
|
||||
|
||||
---
|
||||
|
||||
**Mantido por**: Equipe EvoAI Services
|
||||
@@ -0,0 +1,773 @@
|
||||
# Guia de Desenvolvimento
|
||||
|
||||
Guia completo para desenvolver e contribuir com o Evolution GO.
|
||||
|
||||
## Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Requisitos](#requisitos)
|
||||
- [Setup Inicial](#setup-inicial)
|
||||
- [Estrutura do Projeto](#estrutura-do-projeto)
|
||||
- [Executando Localmente](#executando-localmente)
|
||||
- [Makefile e Comandos](#makefile-e-comandos)
|
||||
- [Configuração de IDE](#configuração-de-ide)
|
||||
- [Convenções de Código](#convenções-de-código)
|
||||
- [Workflow de Desenvolvimento](#workflow-de-desenvolvimento)
|
||||
- [Próximos Passos](#próximos-passos)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
O Evolution GO é um **gateway de API WhatsApp** escrito em Go, utilizando:
|
||||
|
||||
- **Linguagem**: Go 1.24+
|
||||
- **Framework Web**: Gin
|
||||
- **ORM**: GORM
|
||||
- **Banco de Dados**: PostgreSQL / SQLite
|
||||
- **WhatsApp Library**: whatsmeow
|
||||
- **Documentação API**: Swagger
|
||||
|
||||
---
|
||||
|
||||
## Requisitos
|
||||
|
||||
### Obrigatórios
|
||||
|
||||
- **Go 1.24+** ([Download](https://go.dev/dl/))
|
||||
- **Git** ([Download](https://git-scm.com/downloads))
|
||||
- **PostgreSQL 12+** ([Download](https://www.postgresql.org/download/))
|
||||
- Ou usar Docker: `docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:15-alpine`
|
||||
|
||||
### Opcionais
|
||||
|
||||
- **Make** (incluído no Linux/Mac, Windows: `choco install make`)
|
||||
- **Docker** e **Docker Compose** (para desenvolvimento com containers)
|
||||
- **RabbitMQ** (para testar sistema de eventos)
|
||||
- **MinIO** (para testar armazenamento de mídia)
|
||||
|
||||
### Ferramentas Recomendadas
|
||||
|
||||
- **IDE**: VSCode, GoLand, ou Vim/Neovim
|
||||
- **Postman** ou **Insomnia** (para testar API)
|
||||
- **PostgreSQL Client**: pgAdmin, DBeaver, ou psql
|
||||
- **Git GUI**: GitKraken, Sourcetree (opcional)
|
||||
|
||||
---
|
||||
|
||||
## Setup Inicial
|
||||
|
||||
### 1. Clonar o Repositório
|
||||
|
||||
```bash
|
||||
# Via HTTPS
|
||||
git clone https://git.evoai.app/Evolution/evolution-go.git
|
||||
cd evolution-go
|
||||
|
||||
# Ou via SSH (se configurado)
|
||||
git clone [email protected]:Evolution/evolution-go.git
|
||||
cd evolution-go
|
||||
```
|
||||
|
||||
### 2. Instalar Dependências Go
|
||||
|
||||
```bash
|
||||
# Baixar dependências
|
||||
go mod download
|
||||
|
||||
# Ou usando Make
|
||||
make deps
|
||||
```
|
||||
|
||||
### 3. Configurar PostgreSQL
|
||||
|
||||
**Opção A: PostgreSQL Local**
|
||||
|
||||
```bash
|
||||
# Ubuntu/Debian
|
||||
sudo apt-get install postgresql postgresql-contrib
|
||||
sudo systemctl start postgresql
|
||||
|
||||
# macOS
|
||||
brew install postgresql@15
|
||||
brew services start postgresql@15
|
||||
|
||||
# Criar databases
|
||||
sudo -u postgres psql << EOF
|
||||
CREATE DATABASE evogo_auth;
|
||||
CREATE DATABASE evogo_users;
|
||||
EOF
|
||||
```
|
||||
|
||||
**Opção B: PostgreSQL via Docker**
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name postgres \
|
||||
-p 5432:5432 \
|
||||
-e POSTGRES_PASSWORD=postgres \
|
||||
-v postgres_data:/var/lib/postgresql/data \
|
||||
postgres:15-alpine
|
||||
|
||||
# Criar databases
|
||||
docker exec -i postgres psql -U postgres << EOF
|
||||
CREATE DATABASE evogo_auth;
|
||||
CREATE DATABASE evogo_users;
|
||||
EOF
|
||||
```
|
||||
|
||||
### 4. Configurar Variáveis de Ambiente
|
||||
|
||||
```bash
|
||||
# Copiar arquivo de exemplo
|
||||
cp .env.example .env
|
||||
|
||||
# Editar configurações
|
||||
nano .env
|
||||
```
|
||||
|
||||
**Configuração mínima (.env)**:
|
||||
|
||||
```env
|
||||
# Servidor
|
||||
SERVER_PORT=4000
|
||||
CLIENT_NAME=evolution-dev
|
||||
|
||||
# API Key (gere uma segura)
|
||||
GLOBAL_API_KEY=dev-key-12345
|
||||
|
||||
# PostgreSQL
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:postgres@localhost:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://postgres:postgres@localhost:5432/evogo_users?sslmode=disable
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
|
||||
# Logs
|
||||
WADEBUG=DEBUG
|
||||
LOGTYPE=console
|
||||
|
||||
# Configurações de desenvolvimento
|
||||
CONNECT_ON_STARTUP=false
|
||||
WEBHOOK_FILES=true
|
||||
OS_NAME=Linux
|
||||
```
|
||||
|
||||
### 5. Verificar Instalação
|
||||
|
||||
```bash
|
||||
# Verificar versão do Go
|
||||
go version
|
||||
# Deve mostrar: go version go1.24.x ...
|
||||
|
||||
# Verificar dependências
|
||||
go mod verify
|
||||
|
||||
# Compilar (teste)
|
||||
go build ./cmd/evolution-go
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Estrutura do Projeto
|
||||
|
||||
```
|
||||
evolution-go/
|
||||
├── cmd/
|
||||
│ └── evolution-go/
|
||||
│ └── main.go # Entry point da aplicação
|
||||
│
|
||||
├── pkg/ # Pacotes principais
|
||||
│ ├── config/ # Configuração e env vars
|
||||
│ │ ├── config.go
|
||||
│ │ └── env.go
|
||||
│ │
|
||||
│ ├── instance/ # Gerenciamento de instâncias
|
||||
│ │ ├── handler.go # HTTP handlers
|
||||
│ │ ├── service.go # Lógica de negócio
|
||||
│ │ ├── repository.go # Acesso ao banco
|
||||
│ │ └── model/
|
||||
│ │ └── instance_model.go
|
||||
│ │
|
||||
│ ├── whatsmeow/ # Cliente WhatsApp
|
||||
│ │ ├── whatsmeow.go
|
||||
│ │ └── events.go
|
||||
│ │
|
||||
│ ├── message/ # Mensagens
|
||||
│ │ ├── handler.go
|
||||
│ │ ├── service.go
|
||||
│ │ ├── repository.go
|
||||
│ │ └── model/
|
||||
│ │
|
||||
│ ├── sendMessage/ # Envio de mensagens
|
||||
│ │ ├── handler.go
|
||||
│ │ └── service.go
|
||||
│ │
|
||||
│ ├── events/ # Produtores de eventos
|
||||
│ │ ├── webhook/
|
||||
│ │ ├── rabbitmq/
|
||||
│ │ ├── nats/
|
||||
│ │ └── websocket/
|
||||
│ │
|
||||
│ ├── storage/ # Armazenamento de mídia
|
||||
│ │ ├── media_storage.go
|
||||
│ │ └── minio/
|
||||
│ │
|
||||
│ └── utils/ # Utilitários
|
||||
│ ├── logger/
|
||||
│ └── validator/
|
||||
│
|
||||
├── docs/ # Documentação Swagger
|
||||
│ ├── docs.go
|
||||
│ ├── swagger.json
|
||||
│ └── swagger.yaml
|
||||
│
|
||||
├── docker/ # Configurações Docker
|
||||
│ └── examples/
|
||||
│ ├── docker-compose.yml
|
||||
│ ├── docker-compose.swarm.yml
|
||||
│ └── .env.example
|
||||
│
|
||||
├── Dockerfile # Imagem Docker
|
||||
├── Makefile # Comandos de automação
|
||||
├── go.mod # Dependências Go
|
||||
├── go.sum # Checksums de dependências
|
||||
├── .env.example # Exemplo de variáveis de ambiente
|
||||
└── README.md # Documentação principal
|
||||
```
|
||||
|
||||
### Arquitetura em Camadas
|
||||
|
||||
Cada módulo segue o padrão **Handler → Service → Repository**:
|
||||
|
||||
```
|
||||
┌─────────────┐
|
||||
│ Handler │ ← Recebe requests HTTP (Gin)
|
||||
└──────┬──────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ Service │ ← Lógica de negócio
|
||||
└──────┬──────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ Repository │ ← Acesso ao banco (GORM)
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Executando Localmente
|
||||
|
||||
### Modo Desenvolvimento (Hot Reload)
|
||||
|
||||
```bash
|
||||
# Executar em modo dev
|
||||
make dev
|
||||
|
||||
# Ou diretamente
|
||||
go run cmd/evolution-go/main.go -dev
|
||||
```
|
||||
|
||||
**Saída esperada**:
|
||||
|
||||
```
|
||||
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
|
||||
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
|
||||
[GIN-debug] GET /swagger/*any --> github.com/swaggo/gin-swagger.CustomWrapHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /server/ok --> main.main.func1 (3 handlers)
|
||||
[GIN-debug] POST /instance/create --> evolution-go/pkg/instance.(*InstanceHandler).Create-fm (4 handlers)
|
||||
...
|
||||
[GIN-debug] Listening and serving HTTP on :4000
|
||||
```
|
||||
|
||||
### Build e Executar
|
||||
|
||||
```bash
|
||||
# Build local
|
||||
make build-local
|
||||
|
||||
# Executar binário
|
||||
./build/evolution-go
|
||||
```
|
||||
|
||||
### Com Docker Compose
|
||||
|
||||
```bash
|
||||
# Copiar exemplo
|
||||
cp docker/examples/docker-compose.yml ./
|
||||
|
||||
# Editar GLOBAL_API_KEY
|
||||
nano docker-compose.yml
|
||||
|
||||
# Iniciar
|
||||
docker-compose up -d
|
||||
|
||||
# Ver logs
|
||||
docker-compose logs -f evolution-go
|
||||
```
|
||||
|
||||
### Acessar a Aplicação
|
||||
|
||||
- **API Base**: http://localhost:4000
|
||||
- **Health Check**: http://localhost:4000/server/ok
|
||||
- **Swagger UI**: http://localhost:4000/swagger/index.html
|
||||
|
||||
---
|
||||
|
||||
## Makefile e Comandos
|
||||
|
||||
### Comandos de Desenvolvimento
|
||||
|
||||
```bash
|
||||
# Executar em modo dev (hot reload)
|
||||
make dev
|
||||
|
||||
# Build para produção (Linux)
|
||||
make build
|
||||
|
||||
# Build local (seu SO)
|
||||
make build-local
|
||||
|
||||
# Build e executar
|
||||
make run
|
||||
```
|
||||
|
||||
### Comandos de Qualidade
|
||||
|
||||
```bash
|
||||
# Instalar dependências
|
||||
make deps
|
||||
|
||||
# Atualizar dependências
|
||||
make deps-update
|
||||
|
||||
# Formatar código
|
||||
make fmt
|
||||
|
||||
# Lint (fmt + vet)
|
||||
make lint
|
||||
|
||||
# Verificar tudo (deps + lint)
|
||||
make check
|
||||
```
|
||||
|
||||
### Comandos de Documentação
|
||||
|
||||
```bash
|
||||
# Gerar documentação Swagger
|
||||
make swagger
|
||||
|
||||
# Requer: go install github.com/swaggo/swag/cmd/swag@latest
|
||||
```
|
||||
|
||||
### Comandos Docker
|
||||
|
||||
```bash
|
||||
# Build imagem Docker
|
||||
make docker-build
|
||||
|
||||
# Executar container
|
||||
make docker-run
|
||||
|
||||
# Executar em modo dev
|
||||
make docker-run-dev
|
||||
|
||||
# Limpar imagens
|
||||
make docker-clean
|
||||
```
|
||||
|
||||
### Comandos Auxiliares
|
||||
|
||||
```bash
|
||||
# Ver logs
|
||||
make logs
|
||||
|
||||
# Limpar builds
|
||||
make clean
|
||||
|
||||
# Setup completo (deps + tools)
|
||||
make setup
|
||||
|
||||
# Quick start
|
||||
make quick-start
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuração de IDE
|
||||
|
||||
### Visual Studio Code
|
||||
|
||||
#### Extensões Recomendadas
|
||||
|
||||
```json
|
||||
{
|
||||
"recommendations": [
|
||||
"golang.go", // Go support
|
||||
"ms-vscode.makefile-tools", // Makefile support
|
||||
"humao.rest-client", // REST client
|
||||
"42crunch.vscode-openapi", // Swagger/OpenAPI
|
||||
"streetsidesoftware.code-spell-checker"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Salvar em `.vscode/extensions.json`.
|
||||
|
||||
#### Settings
|
||||
|
||||
```json
|
||||
{
|
||||
"go.useLanguageServer": true,
|
||||
"go.lintTool": "golangci-lint",
|
||||
"go.lintOnSave": "package",
|
||||
"go.formatTool": "goimports",
|
||||
"editor.formatOnSave": true,
|
||||
"go.testFlags": ["-v"],
|
||||
"go.coverOnSave": false,
|
||||
"[go]": {
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.organizeImports": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Salvar em `.vscode/settings.json`.
|
||||
|
||||
#### Tasks
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "Run Dev",
|
||||
"type": "shell",
|
||||
"command": "make dev",
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "Build",
|
||||
"type": "shell",
|
||||
"command": "make build-local"
|
||||
},
|
||||
{
|
||||
"label": "Lint",
|
||||
"type": "shell",
|
||||
"command": "make lint"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Salvar em `.vscode/tasks.json`.
|
||||
|
||||
#### Launch (Debug)
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch Evolution GO",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "debug",
|
||||
"program": "${workspaceFolder}/cmd/evolution-go",
|
||||
"args": ["-dev"],
|
||||
"env": {
|
||||
"WADEBUG": "DEBUG"
|
||||
},
|
||||
"showLog": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Salvar em `.vscode/launch.json`.
|
||||
|
||||
### GoLand / IntelliJ IDEA
|
||||
|
||||
#### Run Configuration
|
||||
|
||||
1. **Run → Edit Configurations**
|
||||
2. **Add New Configuration → Go Build**
|
||||
3. Configurar:
|
||||
- **Name**: Evolution GO Dev
|
||||
- **Run kind**: Directory
|
||||
- **Directory**: `cmd/evolution-go`
|
||||
- **Program arguments**: `-dev`
|
||||
- **Environment**: `WADEBUG=DEBUG`
|
||||
- **Working directory**: Raiz do projeto
|
||||
|
||||
#### File Watchers (opcional)
|
||||
|
||||
1. **Settings → Tools → File Watchers**
|
||||
2. **Add → go fmt**
|
||||
3. **Add → goimports**
|
||||
|
||||
---
|
||||
|
||||
## Convenções de Código
|
||||
|
||||
### Estrutura de Pacotes
|
||||
|
||||
```go
|
||||
// Cada módulo deve ter:
|
||||
package instance
|
||||
|
||||
// handler.go - HTTP handlers
|
||||
type InstanceHandler struct {
|
||||
service InstanceService
|
||||
}
|
||||
|
||||
func (h *InstanceHandler) Create(c *gin.Context) { }
|
||||
|
||||
// service.go - Lógica de negócio
|
||||
type InstanceService interface {
|
||||
Create(data CreateInstanceDTO) (*Instance, error)
|
||||
}
|
||||
|
||||
// repository.go - Banco de dados
|
||||
type InstanceRepository interface {
|
||||
Save(instance *Instance) error
|
||||
FindByID(id string) (*Instance, error)
|
||||
}
|
||||
|
||||
// model/instance_model.go - Structs
|
||||
type Instance struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
```
|
||||
|
||||
### Nomenclatura
|
||||
|
||||
```go
|
||||
// Variáveis: camelCase
|
||||
var instanceName string
|
||||
|
||||
// Constantes: PascalCase ou UPPER_CASE
|
||||
const MaxRetries = 5
|
||||
const DEFAULT_TIMEOUT = 30
|
||||
|
||||
// Structs: PascalCase
|
||||
type InstanceConfig struct { }
|
||||
|
||||
// Interfaces: PascalCase + sufixo "er" ou nome descritivo
|
||||
type InstanceRepository interface { }
|
||||
type MessageSender interface { }
|
||||
|
||||
// Métodos: PascalCase
|
||||
func (h *Handler) CreateInstance() { }
|
||||
|
||||
// Funções privadas: camelCase
|
||||
func parseConfig() { }
|
||||
|
||||
// Funções públicas: PascalCase
|
||||
func NewInstanceHandler() { }
|
||||
```
|
||||
|
||||
### Comentários
|
||||
|
||||
```go
|
||||
// Comentários de package (em <package>_doc.go ou no arquivo principal)
|
||||
// Package instance fornece gerenciamento de instâncias WhatsApp.
|
||||
package instance
|
||||
|
||||
// Comentários de funções exportadas (obrigatório para Swagger)
|
||||
// CreateInstance cria uma nova instância WhatsApp.
|
||||
//
|
||||
// @Summary Criar instância
|
||||
// @Description Cria uma nova instância WhatsApp
|
||||
// @Tags instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param data body CreateInstanceDTO true "Dados da instância"
|
||||
// @Success 201 {object} Instance
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Router /instance/create [post]
|
||||
func (h *InstanceHandler) CreateInstance(c *gin.Context) {
|
||||
// Implementação...
|
||||
}
|
||||
|
||||
// Comentários inline para lógica complexa
|
||||
// Gera UUID v4 para identificação única
|
||||
instanceID := uuid.New().String()
|
||||
```
|
||||
|
||||
### Tratamento de Erros
|
||||
|
||||
```go
|
||||
// Sempre retornar erros, não panic
|
||||
func CreateInstance(name string) (*Instance, error) {
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("name cannot be empty")
|
||||
}
|
||||
|
||||
instance := &Instance{Name: name}
|
||||
if err := repository.Save(instance); err != nil {
|
||||
return nil, fmt.Errorf("failed to save instance: %w", err)
|
||||
}
|
||||
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// Em handlers HTTP
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
var dto CreateDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
instance, err := h.service.Create(dto)
|
||||
if err != nil {
|
||||
logger.LogError("Failed to create instance: %v", err)
|
||||
c.JSON(500, gin.H{"error": "Internal server error"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(201, instance)
|
||||
}
|
||||
```
|
||||
|
||||
### Logging
|
||||
|
||||
```go
|
||||
import "evolution-go/pkg/utils/logger"
|
||||
|
||||
// Níveis de log
|
||||
logger.LogInfo("Instance %s created successfully", instanceName)
|
||||
logger.LogWarn("Webhook URL not configured for instance %s", instanceName)
|
||||
logger.LogError("Failed to connect to database: %v", err)
|
||||
logger.LogDebug("Processing message: %+v", message)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Workflow de Desenvolvimento
|
||||
|
||||
### 1. Criar Branch
|
||||
|
||||
```bash
|
||||
# Atualizar main
|
||||
git checkout main
|
||||
git pull origin main
|
||||
|
||||
# Criar feature branch
|
||||
git checkout -b feature/nome-da-feature
|
||||
|
||||
# Ou bugfix
|
||||
git checkout -b fix/nome-do-bug
|
||||
```
|
||||
|
||||
### 2. Desenvolver
|
||||
|
||||
```bash
|
||||
# Executar em modo dev
|
||||
make dev
|
||||
|
||||
# Em outro terminal, fazer mudanças no código
|
||||
# O servidor reinicia automaticamente com hot-reload
|
||||
```
|
||||
|
||||
### 3. Testar Manualmente
|
||||
|
||||
```bash
|
||||
# Testar health check
|
||||
curl http://localhost:4000/server/ok
|
||||
|
||||
# Criar instância
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: dev-key-12345" \
|
||||
-d '{"instanceName": "teste"}'
|
||||
|
||||
# Verificar Swagger
|
||||
open http://localhost:4000/swagger/index.html
|
||||
```
|
||||
|
||||
### 4. Formatar e Lint
|
||||
|
||||
```bash
|
||||
# Formatar código
|
||||
make fmt
|
||||
|
||||
# Lint
|
||||
make lint
|
||||
```
|
||||
|
||||
### 5. Atualizar Swagger (se alterou endpoints)
|
||||
|
||||
```bash
|
||||
# Gerar documentação
|
||||
make swagger
|
||||
|
||||
# Verificar se docs/ foi atualizado
|
||||
git status
|
||||
```
|
||||
|
||||
### 6. Commit
|
||||
|
||||
```bash
|
||||
# Add mudanças
|
||||
git add .
|
||||
|
||||
# Commit com mensagem descritiva
|
||||
git commit -m "feat: adiciona endpoint de listagem de instâncias
|
||||
|
||||
- Implementa GET /instance/list
|
||||
- Adiciona paginação
|
||||
- Atualiza documentação Swagger"
|
||||
|
||||
# Padrões de commit:
|
||||
# feat: nova feature
|
||||
# fix: correção de bug
|
||||
# docs: documentação
|
||||
# refactor: refatoração
|
||||
# chore: tarefas de manutenção
|
||||
```
|
||||
|
||||
### 7. Push e Pull Request
|
||||
|
||||
```bash
|
||||
# Push para origin
|
||||
git push origin feature/nome-da-feature
|
||||
|
||||
# Criar PR no GitLab/GitHub
|
||||
# Preencher descrição detalhada
|
||||
# Aguardar code review
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
Após setup completo:
|
||||
|
||||
1. **[Como Contribuir](./contributing.md)** - Processo de contribuição e PR
|
||||
2. **[Debugging](./debugging.md)** - Troubleshooting e resolução de problemas
|
||||
3. **[Arquitetura](../conceitos-core/architecture.md)** - Entenda a arquitetura
|
||||
4. **[API Overview](../guias-api/api-overview.md)** - Comece a desenvolver na API
|
||||
|
||||
---
|
||||
|
||||
## Recursos Adicionais
|
||||
|
||||
- **Documentação Go**: https://go.dev/doc/
|
||||
- **GORM**: https://gorm.io/docs/
|
||||
- **Gin Framework**: https://gin-gonic.com/docs/
|
||||
- **Whatsmeow**: https://github.com/tulir/whatsmeow
|
||||
- **Swagger**: https://swagger.io/docs/
|
||||
|
||||
---
|
||||
|
||||
**Dica**: Use `make help` para ver todos os comandos disponíveis!
|
||||
|
||||
**Mantido por**: Equipe EvoAI Services
|
||||
**Versão**: 1.0.0
|
||||
@@ -0,0 +1,558 @@
|
||||
# Configuração
|
||||
|
||||
Referência completa de variáveis de ambiente do Evolution GO.
|
||||
|
||||
Para exemplos práticos, consulte: `docker/examples/.env.example`
|
||||
|
||||
## Configuração via Ambiente
|
||||
|
||||
As configurações podem ser definidas através de:
|
||||
- **Variáveis de ambiente** (Docker, Kubernetes)
|
||||
- **Arquivo `.env`** (instalação local)
|
||||
|
||||
---
|
||||
|
||||
## Variáveis Obrigatórias
|
||||
|
||||
### GLOBAL_API_KEY
|
||||
|
||||
Chave de autenticação para acesso à API.
|
||||
|
||||
- **Tipo**: String (UUID recomendado)
|
||||
- **Obrigatório**: Sim
|
||||
|
||||
```env
|
||||
GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db
|
||||
```
|
||||
|
||||
**Geração:**
|
||||
```bash
|
||||
# UUID v4
|
||||
uuidgen
|
||||
|
||||
# Ou via Python
|
||||
python3 -c "import uuid; print(uuid.uuid4())"
|
||||
```
|
||||
|
||||
### DATABASE_SAVE_MESSAGES
|
||||
|
||||
Habilita persistência de mensagens no banco de dados.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Obrigatório**: Sim
|
||||
- **Padrão**: `false`
|
||||
|
||||
```env
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
```
|
||||
|
||||
**Nota**: `true` aumenta significativamente o uso de storage. Recomendado apenas quando necessário manter histórico completo.
|
||||
|
||||
---
|
||||
|
||||
## Servidor
|
||||
|
||||
### SERVER_PORT
|
||||
|
||||
Porta HTTP do servidor API.
|
||||
|
||||
- **Tipo**: Integer
|
||||
- **Padrão**: `4000`
|
||||
|
||||
```env
|
||||
SERVER_PORT=4000
|
||||
```
|
||||
|
||||
### CLIENT_NAME
|
||||
|
||||
Identificador do cliente/instalação.
|
||||
|
||||
- **Tipo**: String
|
||||
|
||||
```env
|
||||
CLIENT_NAME=evolution-production
|
||||
```
|
||||
|
||||
### OS_NAME
|
||||
|
||||
Sistema operacional do ambiente.
|
||||
|
||||
- **Tipo**: String
|
||||
- **Valores**: `Linux`, `Windows`, `macOS`
|
||||
|
||||
```env
|
||||
OS_NAME=Linux
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Banco de Dados PostgreSQL
|
||||
|
||||
### POSTGRES_AUTH_DB
|
||||
|
||||
String de conexão para banco de autenticação.
|
||||
|
||||
- **Formato**: `postgresql://user:pass@host:port/database?sslmode=disable`
|
||||
|
||||
```env
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable
|
||||
```
|
||||
|
||||
### POSTGRES_USERS_DB
|
||||
|
||||
String de conexão para banco de dados de usuários.
|
||||
|
||||
```env
|
||||
POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable
|
||||
```
|
||||
|
||||
**Componentes da URL:**
|
||||
- `postgres` - usuário
|
||||
- `senha` - password (substituir)
|
||||
- `postgres` - hostname (ou `localhost`)
|
||||
- `5432` - porta
|
||||
- `evogo_auth` / `evogo_users` - database name
|
||||
|
||||
---
|
||||
|
||||
## Logs e Debug
|
||||
|
||||
### WADEBUG
|
||||
|
||||
Nível de logging do WhatsApp.
|
||||
|
||||
- **Valores**: `ERROR`, `INFO`, `DEBUG`
|
||||
- **Padrão**: `INFO`
|
||||
|
||||
```env
|
||||
WADEBUG=INFO
|
||||
```
|
||||
|
||||
- `ERROR` - Apenas erros críticos
|
||||
- `INFO` - Informações importantes
|
||||
- `DEBUG` - Detalhamento completo (uso em desenvolvimento)
|
||||
|
||||
### LOGTYPE
|
||||
|
||||
Destino de saída dos logs.
|
||||
|
||||
- **Valores**: `console`, `file`
|
||||
- **Padrão**: `console`
|
||||
|
||||
```env
|
||||
LOGTYPE=console
|
||||
```
|
||||
|
||||
### LOG_DIRECTORY
|
||||
|
||||
Diretório para arquivos de log (quando `LOGTYPE=file`).
|
||||
|
||||
- **Padrão**: `./logs`
|
||||
|
||||
```env
|
||||
LOG_DIRECTORY=/app/logs
|
||||
```
|
||||
|
||||
### LOG_MAX_SIZE
|
||||
|
||||
Tamanho máximo de cada arquivo de log em MB.
|
||||
|
||||
- **Padrão**: `100`
|
||||
|
||||
```env
|
||||
LOG_MAX_SIZE=100
|
||||
```
|
||||
|
||||
### LOG_MAX_BACKUPS
|
||||
|
||||
Número de arquivos de log rotacionados a manter.
|
||||
|
||||
- **Padrão**: `5`
|
||||
|
||||
```env
|
||||
LOG_MAX_BACKUPS=5
|
||||
```
|
||||
|
||||
### LOG_MAX_AGE
|
||||
|
||||
Dias de retenção de arquivos de log.
|
||||
|
||||
- **Padrão**: `30`
|
||||
|
||||
```env
|
||||
LOG_MAX_AGE=30
|
||||
```
|
||||
|
||||
### LOG_COMPRESS
|
||||
|
||||
Compressão de logs rotacionados.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `true`
|
||||
|
||||
```env
|
||||
LOG_COMPRESS=true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Conexão e Comportamento
|
||||
|
||||
### CONNECT_ON_STARTUP
|
||||
|
||||
Conecta automaticamente todas as instâncias ao iniciar o servidor.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `false`
|
||||
|
||||
```env
|
||||
CONNECT_ON_STARTUP=false
|
||||
```
|
||||
|
||||
**Recomendação**: `false` para maior controle sobre o ciclo de vida das instâncias.
|
||||
|
||||
### WEBHOOK_FILES
|
||||
|
||||
Envia URLs de mídia nos payloads de webhook.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `true`
|
||||
|
||||
```env
|
||||
WEBHOOK_FILES=true
|
||||
```
|
||||
|
||||
### QRCODE_MAX_COUNT
|
||||
|
||||
Número máximo de tentativas de geração de QR Code antes de exigir reconexão manual.
|
||||
|
||||
- **Tipo**: Integer
|
||||
- **Padrão**: `5`
|
||||
|
||||
```env
|
||||
QRCODE_MAX_COUNT=5
|
||||
```
|
||||
|
||||
### CHECK_USER_EXISTS
|
||||
|
||||
Valida existência do destinatário no WhatsApp antes de enviar mensagem.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `true`
|
||||
|
||||
```env
|
||||
CHECK_USER_EXISTS=true
|
||||
```
|
||||
|
||||
**Nota**: `false` pode resultar em erros de envio para números inválidos.
|
||||
|
||||
### EVENT_IGNORE_GROUP
|
||||
|
||||
Ignora eventos originados de grupos.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `false`
|
||||
|
||||
```env
|
||||
EVENT_IGNORE_GROUP=false
|
||||
```
|
||||
|
||||
### EVENT_IGNORE_STATUS
|
||||
|
||||
Ignora eventos de status/stories.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `true`
|
||||
|
||||
```env
|
||||
EVENT_IGNORE_STATUS=true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Webhooks
|
||||
|
||||
### WEBHOOK_URL
|
||||
|
||||
URL de destino para callbacks HTTP de eventos.
|
||||
|
||||
```env
|
||||
WEBHOOK_URL=https://api.seudominio.com/webhook
|
||||
```
|
||||
|
||||
Eventos serão enviados via POST com payload JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "messages.upsert",
|
||||
"instanceName": "nome-instancia",
|
||||
"data": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## RabbitMQ (AMQP)
|
||||
|
||||
Sistema de filas para processamento assíncrono de eventos.
|
||||
|
||||
### AMQP_URL
|
||||
|
||||
URL de conexão RabbitMQ.
|
||||
|
||||
- **Formato**: `amqp://user:pass@host:port/vhost`
|
||||
|
||||
```env
|
||||
AMQP_URL=amqp://admin:admin@rabbitmq:5672/default
|
||||
```
|
||||
|
||||
### AMQP_GLOBAL_ENABLED
|
||||
|
||||
Habilita publicação global de eventos via RabbitMQ.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `false`
|
||||
|
||||
```env
|
||||
AMQP_GLOBAL_ENABLED=true
|
||||
```
|
||||
|
||||
### AMQP_GLOBAL_EVENTS
|
||||
|
||||
Lista de eventos a serem publicados (separados por vírgula).
|
||||
|
||||
```env
|
||||
AMQP_GLOBAL_EVENTS=messages.upsert,messages.update,connection.update
|
||||
```
|
||||
|
||||
**Eventos disponíveis:**
|
||||
- `messages.upsert` - Nova mensagem recebida
|
||||
- `messages.update` - Atualização de mensagem (leitura, entrega)
|
||||
- `connection.update` - Mudança de status de conexão
|
||||
- Entre outros
|
||||
|
||||
---
|
||||
|
||||
## NATS
|
||||
|
||||
Sistema de mensageria para eventos distribuídos.
|
||||
|
||||
### NATS_URL
|
||||
|
||||
URL do servidor NATS.
|
||||
|
||||
```env
|
||||
NATS_URL=nats://localhost:4222
|
||||
```
|
||||
|
||||
### NATS_GLOBAL_ENABLED
|
||||
|
||||
Habilita publicação de eventos via NATS.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `false`
|
||||
|
||||
```env
|
||||
NATS_GLOBAL_ENABLED=true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MinIO/S3
|
||||
|
||||
Armazenamento de objetos para mídia.
|
||||
|
||||
### MINIO_ENABLED
|
||||
|
||||
Habilita integração com MinIO/S3.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `false`
|
||||
|
||||
```env
|
||||
MINIO_ENABLED=true
|
||||
```
|
||||
|
||||
### MINIO_ENDPOINT
|
||||
|
||||
Endpoint do servidor de objetos.
|
||||
|
||||
```env
|
||||
# MinIO local
|
||||
MINIO_ENDPOINT=localhost:9000
|
||||
|
||||
# AWS S3
|
||||
MINIO_ENDPOINT=s3.amazonaws.com
|
||||
```
|
||||
|
||||
### MINIO_ACCESS_KEY
|
||||
|
||||
Access Key para autenticação.
|
||||
|
||||
```env
|
||||
MINIO_ACCESS_KEY=minioadmin
|
||||
```
|
||||
|
||||
### MINIO_SECRET_KEY
|
||||
|
||||
Secret Key para autenticação.
|
||||
|
||||
```env
|
||||
MINIO_SECRET_KEY=minioadmin
|
||||
```
|
||||
|
||||
### MINIO_BUCKET
|
||||
|
||||
Nome do bucket para armazenamento de mídia.
|
||||
|
||||
```env
|
||||
MINIO_BUCKET=evolution-media
|
||||
```
|
||||
|
||||
**Nota**: O bucket deve existir antes de habilitar a integração.
|
||||
|
||||
### MINIO_USE_SSL
|
||||
|
||||
Utiliza HTTPS para conexões ao S3/MinIO.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `false`
|
||||
|
||||
```env
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
### MINIO_REGION
|
||||
|
||||
Região do bucket S3 (AWS).
|
||||
|
||||
- **Padrão**: `us-east-1`
|
||||
|
||||
```env
|
||||
MINIO_REGION=us-east-1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Proxy
|
||||
|
||||
Configuração de proxy HTTP para instâncias WhatsApp.
|
||||
|
||||
### PROXY_HOST
|
||||
|
||||
Hostname do servidor proxy.
|
||||
|
||||
```env
|
||||
PROXY_HOST=proxy.empresa.com
|
||||
```
|
||||
|
||||
### PROXY_PORT
|
||||
|
||||
Porta do proxy.
|
||||
|
||||
```env
|
||||
PROXY_PORT=8080
|
||||
```
|
||||
|
||||
### PROXY_USERNAME
|
||||
|
||||
Usuário para autenticação (se requerido).
|
||||
|
||||
```env
|
||||
PROXY_USERNAME=usuario
|
||||
```
|
||||
|
||||
### PROXY_PASSWORD
|
||||
|
||||
Senha para autenticação (se requerido).
|
||||
|
||||
```env
|
||||
PROXY_PASSWORD=senha
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Recursos Adicionais
|
||||
|
||||
### API_AUDIO_CONVERTER
|
||||
|
||||
URL de serviço externo para conversão de áudio.
|
||||
|
||||
```env
|
||||
API_AUDIO_CONVERTER=https://converter.seudominio.com
|
||||
```
|
||||
|
||||
### API_AUDIO_CONVERTER_KEY
|
||||
|
||||
Chave de autenticação do serviço de conversão.
|
||||
|
||||
```env
|
||||
API_AUDIO_CONVERTER_KEY=chave-do-servico
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Versão WhatsApp (Avançado)
|
||||
|
||||
**⚠️ Atenção**: Modificar a versão do WhatsApp pode resultar em bloqueio de conta. Use apenas quando estritamente necessário.
|
||||
|
||||
### WHATSAPP_VERSION_MAJOR
|
||||
|
||||
```env
|
||||
WHATSAPP_VERSION_MAJOR=2
|
||||
```
|
||||
|
||||
### WHATSAPP_VERSION_MINOR
|
||||
|
||||
```env
|
||||
WHATSAPP_VERSION_MINOR=2412
|
||||
```
|
||||
|
||||
### WHATSAPP_VERSION_PATCH
|
||||
|
||||
```env
|
||||
WHATSAPP_VERSION_PATCH=54
|
||||
```
|
||||
|
||||
**Recomendação**: Deixar não configurado para utilizar versão automática da biblioteca whatsmeow.
|
||||
|
||||
---
|
||||
|
||||
## Exemplo de Configuração Mínima
|
||||
|
||||
```env
|
||||
# Obrigatórias
|
||||
GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
|
||||
# Servidor
|
||||
SERVER_PORT=4000
|
||||
CLIENT_NAME=evolution
|
||||
OS_NAME=Linux
|
||||
|
||||
# Banco de Dados
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable
|
||||
|
||||
# Logs
|
||||
WADEBUG=INFO
|
||||
LOGTYPE=console
|
||||
|
||||
# Comportamento
|
||||
CONNECT_ON_STARTUP=false
|
||||
WEBHOOK_FILES=true
|
||||
CHECK_USER_EXISTS=true
|
||||
EVENT_IGNORE_STATUS=true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Referências
|
||||
|
||||
- **[Instalação](./installation.md)** - Guia de instalação
|
||||
- **[Início Rápido](./quickstart.md)** - Primeiro uso
|
||||
- **[.env.example](../../../docker/examples/.env.example)** - Exemplo completo com todas variáveis
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,491 @@
|
||||
# Guia de Instalação
|
||||
|
||||
Métodos de instalação do Evolution GO para diferentes ambientes.
|
||||
|
||||
## Índice
|
||||
|
||||
- [Requisitos](#requisitos)
|
||||
- [Instalação com Docker (Recomendado)](#instalação-com-docker-recomendado)
|
||||
- [Instalação Local](#instalação-local)
|
||||
- [Instalação com Docker Swarm](#instalação-com-docker-swarm)
|
||||
- [Stack Completa](#stack-completa)
|
||||
- [Verificação](#verificação)
|
||||
- [Solução de Problemas](#solução-de-problemas)
|
||||
|
||||
---
|
||||
|
||||
## Requisitos
|
||||
|
||||
### Docker (Recomendado)
|
||||
|
||||
- Docker 20.10+
|
||||
- Docker Compose 2.0+
|
||||
- PostgreSQL 12+ (containerizado)
|
||||
- Mínimo 1GB RAM
|
||||
- Mínimo 2GB disco
|
||||
|
||||
### Instalação Local
|
||||
|
||||
- Go 1.24+
|
||||
- PostgreSQL 12+
|
||||
- Git
|
||||
- Mínimo 1GB RAM
|
||||
- Mínimo 2GB disco
|
||||
|
||||
### Opcionais
|
||||
|
||||
- RabbitMQ - Sistema de filas
|
||||
- NATS - Mensageria distribuída
|
||||
- MinIO - Storage S3-compatible
|
||||
|
||||
---
|
||||
|
||||
## Instalação com Docker (Recomendado)
|
||||
|
||||
Método mais simples e adequado para produção.
|
||||
|
||||
### 1. Obter Arquivos
|
||||
|
||||
**Opção A: Clonar repositório**
|
||||
|
||||
```bash
|
||||
git clone https://git.evoai.app/Evolution/evolution-go.git
|
||||
cd evolution-go
|
||||
```
|
||||
|
||||
**Opção B: Download direto**
|
||||
|
||||
```bash
|
||||
mkdir evolution-go-deploy && cd evolution-go-deploy
|
||||
|
||||
curl -o docker-compose.yml https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/docker-compose.yml
|
||||
curl -o init-db.sql https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/init-db.sql
|
||||
```
|
||||
|
||||
### 2. Configurar API Key
|
||||
|
||||
Gere uma chave segura:
|
||||
|
||||
```bash
|
||||
# Linux/Mac
|
||||
uuidgen
|
||||
|
||||
# Python
|
||||
python3 -c "import uuid; print(uuid.uuid4())"
|
||||
|
||||
# Resultado exemplo: df16caad-d0d2-41b2-bec5-75b90048a0db
|
||||
```
|
||||
|
||||
Edite `docker-compose.yml`:
|
||||
|
||||
```bash
|
||||
nano docker-compose.yml
|
||||
```
|
||||
|
||||
Localize e substitua:
|
||||
```yaml
|
||||
GLOBAL_API_KEY: "SUA-CHAVE-API-SEGURA-AQUI"
|
||||
```
|
||||
|
||||
Por:
|
||||
```yaml
|
||||
GLOBAL_API_KEY: "df16caad-d0d2-41b2-bec5-75b90048a0db"
|
||||
```
|
||||
|
||||
### 3. Iniciar Serviços
|
||||
|
||||
```bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
Aguarde ~30 segundos para inicialização completa.
|
||||
|
||||
### 4. Verificar Logs
|
||||
|
||||
```bash
|
||||
# Evolution GO
|
||||
docker-compose logs -f evolution-go
|
||||
|
||||
# PostgreSQL
|
||||
docker-compose logs -f postgres
|
||||
```
|
||||
|
||||
### 5. Acessar Aplicação
|
||||
|
||||
- **API**: http://localhost:4000
|
||||
- **Swagger**: http://localhost:4000/swagger/index.html
|
||||
- **Health Check**: http://localhost:4000/server/ok
|
||||
|
||||
---
|
||||
|
||||
## Instalação Local
|
||||
|
||||
Para ambientes de desenvolvimento.
|
||||
|
||||
### 1. Instalar PostgreSQL
|
||||
|
||||
**Ubuntu/Debian:**
|
||||
```bash
|
||||
sudo apt-get update
|
||||
sudo apt-get install postgresql postgresql-contrib
|
||||
```
|
||||
|
||||
**macOS:**
|
||||
```bash
|
||||
brew install postgresql@15
|
||||
brew services start postgresql@15
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
Download: https://www.postgresql.org/download/windows/
|
||||
|
||||
### 2. Configurar Banco de Dados
|
||||
|
||||
```bash
|
||||
sudo -u postgres psql
|
||||
```
|
||||
|
||||
```sql
|
||||
CREATE DATABASE evogo_auth;
|
||||
CREATE DATABASE evogo_users;
|
||||
\q
|
||||
```
|
||||
|
||||
### 3. Instalar Go
|
||||
|
||||
Download: https://go.dev/dl/
|
||||
|
||||
Verificar:
|
||||
```bash
|
||||
go version
|
||||
```
|
||||
|
||||
### 4. Clonar Repositório
|
||||
|
||||
```bash
|
||||
git clone https://git.evoai.app/Evolution/evolution-go.git
|
||||
cd evolution-go
|
||||
```
|
||||
|
||||
### 5. Instalar Dependências
|
||||
|
||||
```bash
|
||||
go mod download
|
||||
```
|
||||
|
||||
Ou:
|
||||
```bash
|
||||
make deps
|
||||
```
|
||||
|
||||
### 6. Configurar Ambiente
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
Configuração mínima:
|
||||
|
||||
```env
|
||||
SERVER_PORT=4000
|
||||
GLOBAL_API_KEY=sua-chave-gerada
|
||||
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:postgres@localhost:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://postgres:postgres@localhost:5432/evogo_users?sslmode=disable
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
|
||||
WADEBUG=DEBUG
|
||||
LOGTYPE=console
|
||||
CONNECT_ON_STARTUP=false
|
||||
WEBHOOK_FILES=true
|
||||
OS_NAME=Linux
|
||||
```
|
||||
|
||||
### 7. Executar
|
||||
|
||||
**Modo desenvolvimento:**
|
||||
```bash
|
||||
make dev
|
||||
```
|
||||
|
||||
Ou:
|
||||
```bash
|
||||
go run cmd/evolution-go/main.go -dev
|
||||
```
|
||||
|
||||
**Build produção:**
|
||||
```bash
|
||||
make build-local
|
||||
./build/evolution-go
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Instalação com Docker Swarm
|
||||
|
||||
Para ambientes com alta disponibilidade.
|
||||
|
||||
### 1. Inicializar Swarm
|
||||
|
||||
```bash
|
||||
docker swarm init
|
||||
```
|
||||
|
||||
### 2. Criar Recursos
|
||||
|
||||
```bash
|
||||
docker volume create evolution_go_data
|
||||
docker volume create evolution_go_logs
|
||||
docker network create --driver overlay network_public
|
||||
```
|
||||
|
||||
### 3. Configurar Stack
|
||||
|
||||
```bash
|
||||
cp docker/examples/docker-compose.swarm.yml ./docker-compose.swarm.yml
|
||||
nano docker-compose.swarm.yml
|
||||
```
|
||||
|
||||
Configure:
|
||||
- `GLOBAL_API_KEY`
|
||||
- `POSTGRES_AUTH_DB`
|
||||
- `POSTGRES_USERS_DB`
|
||||
- Labels Traefik (se aplicável)
|
||||
|
||||
### 4. Deploy
|
||||
|
||||
```bash
|
||||
docker stack deploy -c docker-compose.swarm.yml evolution
|
||||
```
|
||||
|
||||
### 5. Verificar
|
||||
|
||||
```bash
|
||||
docker service ls
|
||||
docker service logs evolution_evolution_go -f
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stack Completa
|
||||
|
||||
Incluindo RabbitMQ, MinIO e NATS.
|
||||
|
||||
```bash
|
||||
curl -o docker-compose-full.yml https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/docker-compose.full.yml
|
||||
|
||||
nano docker-compose-full.yml # Configurar API Key
|
||||
|
||||
docker-compose -f docker-compose-full.yml up -d
|
||||
```
|
||||
|
||||
**Serviços incluídos:**
|
||||
|
||||
| Serviço | Porta | Função |
|
||||
|---------|-------|--------|
|
||||
| Evolution GO | 4000 | API principal |
|
||||
| PostgreSQL | 5432 | Banco de dados |
|
||||
| RabbitMQ | 5672, 15672 | Filas de mensagens |
|
||||
| MinIO | 9000, 9001 | Storage de objetos |
|
||||
| NATS | 4222 | Mensageria (opcional) |
|
||||
|
||||
**Acessos:**
|
||||
|
||||
- Evolution GO: http://localhost:4000
|
||||
- Swagger: http://localhost:4000/swagger/index.html
|
||||
- RabbitMQ: http://localhost:15672 (admin/admin)
|
||||
- MinIO: http://localhost:9001 (minioadmin/minioadmin)
|
||||
|
||||
**Configuração MinIO (primeira vez):**
|
||||
|
||||
1. Acesse http://localhost:9001
|
||||
2. Login: minioadmin / minioadmin
|
||||
3. Create bucket: `evolution-media`
|
||||
4. Configurar política de acesso
|
||||
|
||||
---
|
||||
|
||||
## Verificação
|
||||
|
||||
### Health Check
|
||||
|
||||
```bash
|
||||
curl http://localhost:4000/server/ok
|
||||
```
|
||||
|
||||
Resposta esperada:
|
||||
```json
|
||||
{
|
||||
"status": "ok"
|
||||
}
|
||||
```
|
||||
|
||||
### Swagger UI
|
||||
|
||||
Acesse: http://localhost:4000/swagger/index.html
|
||||
|
||||
### Criar Instância de Teste
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: sua-chave-api-global" \
|
||||
-d '{
|
||||
"name": "teste",
|
||||
"token": "token-unico-para-esta-instancia"
|
||||
}'
|
||||
```
|
||||
|
||||
> **Nota:** Use a `GLOBAL_API_KEY` no header e forneça `name` + `token` no body.
|
||||
|
||||
### Verificar Logs
|
||||
|
||||
**Docker:**
|
||||
```bash
|
||||
docker-compose logs -f evolution-go
|
||||
```
|
||||
|
||||
**Local:**
|
||||
```bash
|
||||
tail -f logs/evolution-go.log
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Solução de Problemas
|
||||
|
||||
### Connection Refused (PostgreSQL)
|
||||
|
||||
**Diagnóstico:**
|
||||
```bash
|
||||
docker-compose ps postgres
|
||||
# Ou local:
|
||||
sudo systemctl status postgresql
|
||||
```
|
||||
|
||||
**Verificar databases:**
|
||||
```bash
|
||||
docker-compose exec postgres psql -U postgres -c "\l"
|
||||
```
|
||||
|
||||
### Porta em Uso
|
||||
|
||||
Alterar porta no `docker-compose.yml`:
|
||||
```yaml
|
||||
ports:
|
||||
- "4001:4000"
|
||||
```
|
||||
|
||||
Acesso via: http://localhost:4001
|
||||
|
||||
### Container Reiniciando
|
||||
|
||||
**Ver logs:**
|
||||
```bash
|
||||
docker-compose logs evolution-go
|
||||
```
|
||||
|
||||
**Causas comuns:**
|
||||
- `GLOBAL_API_KEY` não definida
|
||||
- PostgreSQL não acessível
|
||||
- Credenciais incorretas
|
||||
|
||||
### Permissões de Volume
|
||||
|
||||
```bash
|
||||
mkdir -p logs dbdata
|
||||
chmod 777 logs dbdata
|
||||
```
|
||||
|
||||
Ou usar bind mounts:
|
||||
```yaml
|
||||
volumes:
|
||||
- ./logs:/app/logs
|
||||
- ./dbdata:/app/dbdata
|
||||
```
|
||||
|
||||
### MinIO Bucket Não Existe
|
||||
|
||||
1. Acessar console: http://localhost:9001
|
||||
2. Login: minioadmin / minioadmin
|
||||
3. Criar bucket: `evolution-media`
|
||||
|
||||
Ou via CLI:
|
||||
```bash
|
||||
docker-compose exec minio mc mb /data/evolution-media
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Comandos Úteis
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
# Iniciar
|
||||
docker-compose up -d
|
||||
|
||||
# Parar
|
||||
docker-compose stop
|
||||
|
||||
# Reiniciar
|
||||
docker-compose restart
|
||||
|
||||
# Status
|
||||
docker-compose ps
|
||||
|
||||
# Logs
|
||||
docker-compose logs -f
|
||||
|
||||
# Remover
|
||||
docker-compose down
|
||||
|
||||
# Atualizar
|
||||
docker-compose pull
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
### Docker Swarm
|
||||
|
||||
```bash
|
||||
# Listar serviços
|
||||
docker service ls
|
||||
|
||||
# Logs
|
||||
docker service logs evolution_evolution_go -f
|
||||
|
||||
# Escalar
|
||||
docker service scale evolution_evolution_go=3
|
||||
|
||||
# Atualizar
|
||||
docker service update --image evoapicloud/evolution-go:latest evolution_evolution_go
|
||||
|
||||
# Remover
|
||||
docker stack rm evolution
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- **[Configuração](./configuration.md)** - Variáveis de ambiente
|
||||
- **[Início Rápido](./quickstart.md)** - Primeira instância
|
||||
- **[API Overview](../guias-api/api-overview.md)** - Estrutura da API
|
||||
- **[Docker Deployment](../deploy-producao/docker-deployment.md)** - Deploy avançado
|
||||
|
||||
---
|
||||
|
||||
## Arquivos de Exemplo
|
||||
|
||||
Disponíveis em `docker/examples/`:
|
||||
|
||||
- [docker-compose.yml](../../../docker/examples/docker-compose.yml)
|
||||
- [docker-compose.swarm.yml](../../../docker/examples/docker-compose.swarm.yml)
|
||||
- [docker-compose.full.yml](../../../docker/examples/docker-compose.full.yml)
|
||||
- [init-db.sql](../../../docker/examples/init-db.sql)
|
||||
- [.env.example](../../../docker/examples/.env.example)
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,242 @@
|
||||
# Introdução ao Evolution GO
|
||||
|
||||
## Visão Geral
|
||||
|
||||
Evolution GO é um gateway de API WhatsApp construído em Go que fornece uma interface RESTful para integração com o protocolo WhatsApp Web. Funciona como camada de abstração entre aplicações e o WhatsApp, permitindo automação de mensagens, gerenciamento de múltiplas instâncias e integração através de APIs padronizadas.
|
||||
|
||||
O projeto utiliza a biblioteca [whatsmeow](https://github.com/tulir/whatsmeow), uma implementação Go do protocolo WhatsApp Web Multi-Device, e adiciona sobre ela recursos empresariais como APIs REST, sistema de eventos, persistência de dados e gerenciamento multi-instância.
|
||||
|
||||
## O que o Evolution GO oferece
|
||||
|
||||
### Comunicação via API REST
|
||||
|
||||
Envie e receba mensagens do WhatsApp através de requisições HTTP padrão:
|
||||
- Mensagens de texto com formatação
|
||||
- Mídia (imagens, vídeos, áudios, documentos)
|
||||
- Localização, contatos e stickers
|
||||
- Mensagens interativas (botões, listas, enquetes)
|
||||
- Grupos e comunidades
|
||||
|
||||
### Gerenciamento Multi-Instância
|
||||
|
||||
- Conecte múltiplas contas WhatsApp simultaneamente
|
||||
- Cada instância opera de forma independente
|
||||
- Gerenciamento de ciclo de vida completo
|
||||
- Configuração de proxy por instância
|
||||
- Logs isolados por instância
|
||||
|
||||
### Sistema de Eventos
|
||||
|
||||
Receba notificações em tempo real através de:
|
||||
- **Webhooks** - Callbacks HTTP para serviços externos
|
||||
- **RabbitMQ** - Filas de mensagens para processamento assíncrono
|
||||
- **NATS** - Mensageria leve para eventos distribuídos
|
||||
- **WebSocket** - Conexões em tempo real
|
||||
|
||||
### Armazenamento Empresarial
|
||||
|
||||
- **Dual Database** - Separação entre dados de autenticação e usuários
|
||||
- **PostgreSQL** - Banco principal para produção
|
||||
- **SQLite** - Alternativa para desenvolvimento
|
||||
- **MinIO/S3** - Armazenamento de mídia escalável
|
||||
- Pool de conexões otimizado
|
||||
|
||||
## Arquitetura
|
||||
|
||||
O Evolution GO segue arquitetura em camadas:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Camada Handler (HTTP) │
|
||||
│ Validação e Roteamento de Requests │
|
||||
├─────────────────────────────────────────┤
|
||||
│ Camada Service │
|
||||
│ Lógica de Negócio e Regras │
|
||||
├─────────────────────────────────────────┤
|
||||
│ Camada Repository │
|
||||
│ Persistência e Acesso a Dados │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Componentes Principais
|
||||
|
||||
- **Instance Manager** - Gerencia ciclo de vida das sessões WhatsApp
|
||||
- **Whatsmeow Service** - Wrapper sobre a biblioteca whatsmeow
|
||||
- **Message Service** - Processamento e entrega de mensagens
|
||||
- **Event System** - Propagação multi-canal de eventos
|
||||
- **Storage Service** - Gerenciamento de mídia
|
||||
- **User Service** - Perfis, contatos e configurações
|
||||
- **Group Service** - Administração de grupos
|
||||
- **Community Service** - Gerenciamento de comunidades
|
||||
|
||||
### Biblioteca Whatsmeow
|
||||
|
||||
A [whatsmeow](https://github.com/tulir/whatsmeow) implementa o protocolo WhatsApp Web Multi-Device:
|
||||
- Comunicação direta com servidores WhatsApp
|
||||
- Criptografia end-to-end
|
||||
- Suporte a multi-dispositivos
|
||||
- Sincronização de mensagens
|
||||
- Gerenciamento de sessões
|
||||
|
||||
O Evolution GO utiliza a whatsmeow como base e adiciona camada empresarial com APIs REST, gerenciamento de múltiplas instâncias, sistema de eventos e persistência.
|
||||
|
||||
## Casos de Uso
|
||||
|
||||
**Automação de Atendimento**
|
||||
- Chatbots com respostas automáticas
|
||||
- Integração com sistemas de tickets
|
||||
- Roteamento inteligente de conversas
|
||||
|
||||
**Notificações Transacionais**
|
||||
- Confirmações de pedidos
|
||||
- Alertas de pagamento
|
||||
- Atualizações de status
|
||||
- Lembretes automáticos
|
||||
|
||||
**Marketing e Campanhas**
|
||||
- Envio de mensagens em massa
|
||||
- Segmentação de públicos
|
||||
- Tracking de engajamento
|
||||
|
||||
**Integração com CRM**
|
||||
- Canal WhatsApp no CRM
|
||||
- Histórico unificado
|
||||
- Automação de fluxos
|
||||
|
||||
**Comunicação Corporativa**
|
||||
- Notificações internas
|
||||
- Alertas de sistemas
|
||||
- Integração com ERPs
|
||||
|
||||
## Stack Tecnológico
|
||||
|
||||
- **Linguagem**: Go 1.24+
|
||||
- **Framework Web**: Gin
|
||||
- **Protocolo WhatsApp**: whatsmeow
|
||||
- **ORM**: GORM
|
||||
- **Banco de Dados**: PostgreSQL / SQLite
|
||||
- **Filas**: RabbitMQ (AMQP), NATS
|
||||
- **Storage**: MinIO (S3-compatible)
|
||||
- **Documentação**: Swagger/OpenAPI
|
||||
- **Containers**: Docker multi-stage builds
|
||||
|
||||
## Endpoints Disponíveis
|
||||
|
||||
### Instâncias
|
||||
- Criar, conectar e gerenciar instâncias
|
||||
- QR Code para autenticação
|
||||
- Status e informações de conexão
|
||||
- Configuração de proxy
|
||||
|
||||
### Mensagens
|
||||
- Envio de texto, mídia, localização
|
||||
- Botões, listas e enquetes
|
||||
- Reações e respostas
|
||||
- Histórico de conversas
|
||||
|
||||
### Usuários
|
||||
- Gerenciamento de perfil
|
||||
- Contatos e privacidade
|
||||
- Bloqueios e configurações
|
||||
|
||||
### Grupos
|
||||
- Criação e administração
|
||||
- Gerenciamento de participantes
|
||||
- Configurações e permissões
|
||||
|
||||
### Chats
|
||||
- Pin, mute, archive
|
||||
- Marcação de leitura
|
||||
- Busca e filtros
|
||||
|
||||
### Outros
|
||||
- Labels (etiquetas)
|
||||
- Chamadas
|
||||
- Comunidades
|
||||
- Newsletters/Canais
|
||||
|
||||
## Segurança e Privacidade
|
||||
|
||||
- Criptografia end-to-end mantida (protocolo WhatsApp)
|
||||
- Autenticação via API Key
|
||||
- Suporte a HTTPS
|
||||
- Logs de auditoria
|
||||
- Secrets management
|
||||
- Isolamento de instâncias
|
||||
|
||||
## Telemetria
|
||||
|
||||
O sistema coleta métricas anônimas para melhorias:
|
||||
- Rotas mais utilizadas
|
||||
- Versão da API em uso
|
||||
- Estatísticas de performance
|
||||
|
||||
**Não são coletados**: mensagens, números de telefone, nomes ou dados pessoais.
|
||||
|
||||
## Primeiros Passos
|
||||
|
||||
### Requisitos
|
||||
|
||||
- Go 1.24+ (instalação local) ou Docker 20.10+
|
||||
- PostgreSQL 12+ ou SQLite
|
||||
- Chave de API para autenticação
|
||||
|
||||
### Instalação Rápida
|
||||
|
||||
```bash
|
||||
# Clonar repositório
|
||||
git clone https://git.evoai.app/Evolution/evolution-go.git
|
||||
cd evolution-go
|
||||
|
||||
# Configurar ambiente
|
||||
cp .env.example .env
|
||||
|
||||
# Executar com Docker
|
||||
docker-compose up -d
|
||||
|
||||
# Ou executar localmente
|
||||
make dev
|
||||
```
|
||||
|
||||
O servidor estará disponível em `http://localhost:4000` com documentação Swagger em `/swagger/index.html`.
|
||||
|
||||
## Diferencial
|
||||
|
||||
| Aspecto | Evolution GO | WhatsApp Business API |
|
||||
|---------|--------------|----------------------|
|
||||
| Licença | Apache 2.0 | Proprietária |
|
||||
| Custo | Gratuito | Pago por mensagem |
|
||||
| Aprovação | Não requer | Requer aprovação Meta |
|
||||
| Setup | Minutos | Semanas/meses |
|
||||
| Multi-instância | Ilimitado | Limitado por contrato |
|
||||
| Flexibilidade | Total | Limitada por políticas |
|
||||
| Recursos | Completo | Subconjunto aprovado |
|
||||
|
||||
## Documentação
|
||||
|
||||
- **[Instalação](./installation.md)** - Guia completo de instalação
|
||||
- **[Configuração](./configuration.md)** - Variáveis de ambiente
|
||||
- **[Início Rápido](./quickstart.md)** - Primeiro uso prático
|
||||
- **[API Overview](../guias-api/api-overview.md)** - Estrutura da API
|
||||
- **[Arquitetura](../conceitos-core/architecture.md)** - Design do sistema
|
||||
|
||||
## Suporte
|
||||
|
||||
- **Grupo WhatsApp**: [evolution-api.com/whatsapp](https://evolution-api.com/whatsapp)
|
||||
- **Discord**: [evolution-api.com/discord](https://evolution-api.com/discord)
|
||||
- **GitHub Issues**: [github.com/evolution-foundation/evolution-go](https://github.com/evolution-foundation/evolution-go/issues)
|
||||
- **Documentação**: [doc.evolution-api.com](https://doc.evolution-api.com)
|
||||
|
||||
## Licença
|
||||
|
||||
Apache License 2.0 com condições adicionais:
|
||||
|
||||
1. Logo e informações de copyright não podem ser removidas das interfaces
|
||||
2. Uso do Evolution GO deve ser notificado/creditado no sistema que o utiliza
|
||||
|
||||
Detalhes completos: [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
---
|
||||
|
||||
**Versão**: 1.0.0
|
||||
**Mantido por**: Equipe Evolution API
|
||||
@@ -0,0 +1,336 @@
|
||||
# Início Rápido
|
||||
|
||||
Tutorial prático para configurar sua primeira instância WhatsApp e enviar mensagens via Evolution GO.
|
||||
|
||||
## Pré-requisitos
|
||||
|
||||
- Evolution GO instalado e em execução
|
||||
- Chave de API configurada (GLOBAL_API_KEY)
|
||||
- Smartphone com WhatsApp ativo
|
||||
|
||||
Se ainda não instalou, consulte o [Guia de Instalação](./installation.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Verificar API
|
||||
|
||||
Confirme que o servidor está respondendo:
|
||||
|
||||
```bash
|
||||
curl http://localhost:4000/server/ok
|
||||
```
|
||||
|
||||
**Resposta esperada:**
|
||||
```json
|
||||
{
|
||||
"status": "ok"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Criar Instância
|
||||
|
||||
Uma instância representa uma conexão única do WhatsApp. Crie sua primeira:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY" \
|
||||
-d '{
|
||||
"name": "minha-instancia",
|
||||
"token": "token-secreto-da-instancia"
|
||||
}'
|
||||
```
|
||||
|
||||
> **Importante:**
|
||||
> - `apikey` header: Use a `GLOBAL_API_KEY` configurada no servidor
|
||||
> - `token`: Crie um token único para esta instância (será usado para autenticar requisições desta instância)
|
||||
> - `name`: Nome identificador da instância
|
||||
|
||||
**Resposta:**
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"instanceId": "uuid-gerado",
|
||||
"name": "minha-instancia",
|
||||
"token": "token-secreto-da-instancia",
|
||||
"status": "created"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A instância foi criada mas ainda não está autenticada no WhatsApp.
|
||||
|
||||
---
|
||||
|
||||
## 3. Autenticar via QR Code
|
||||
|
||||
### Iniciar Conexão
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/connect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-secreto-da-instancia"
|
||||
```
|
||||
|
||||
> **Nota:** Agora use o `token` da instância no header `apikey` (não mais a GLOBAL_API_KEY).
|
||||
|
||||
### Obter QR Code
|
||||
|
||||
**Via navegador:**
|
||||
```
|
||||
http://localhost:4000/instance/qr
|
||||
```
|
||||
(com o header `apikey: token-secreto-da-instancia`)
|
||||
|
||||
**Via API:**
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/qr" \
|
||||
-H "apikey: token-secreto-da-instancia"
|
||||
```
|
||||
|
||||
### Escanear no WhatsApp
|
||||
|
||||
1. Abra o WhatsApp no smartphone
|
||||
2. Acesse **Mais opções (⋮)** → **Aparelhos conectados**
|
||||
3. Toque em **Conectar um aparelho**
|
||||
4. Escaneie o QR Code exibido
|
||||
|
||||
A conexão deve ser estabelecida em aproximadamente 10 segundos.
|
||||
|
||||
---
|
||||
|
||||
## 4. Verificar Status
|
||||
|
||||
Confirme que a instância está conectada:
|
||||
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/status" \
|
||||
-H "apikey: token-secreto-da-instancia"
|
||||
```
|
||||
|
||||
**Resposta quando conectado:**
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"instanceId": "uuid-da-instancia",
|
||||
"name": "minha-instancia",
|
||||
"status": "open",
|
||||
"profilePictureUrl": "https://...",
|
||||
"profileName": "Nome do Perfil"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Status possíveis:**
|
||||
- `created` - Instância criada, aguardando autenticação
|
||||
- `connecting` - Processo de conexão em andamento
|
||||
- `open` - Conectado e operacional
|
||||
- `close` - Desconectado
|
||||
|
||||
---
|
||||
|
||||
## 5. Enviar Mensagem
|
||||
|
||||
### Mensagem de Texto
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/send/text \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-secreto-da-instancia" \
|
||||
-d '{
|
||||
"number": "5511999999999",
|
||||
"text": "Mensagem de teste via Evolution GO"
|
||||
}'
|
||||
```
|
||||
|
||||
> **Nota:** A instância é identificada pelo token no header `apikey`. Não é necessário enviar `instanceName` no body.
|
||||
|
||||
**Formato do número:**
|
||||
- DDI + DDD + Número (apenas dígitos)
|
||||
- Exemplo Brasil: `5511999999999` (55=Brasil, 11=São Paulo)
|
||||
|
||||
**Resposta:**
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"messageId": "3EB0...",
|
||||
"status": "sent"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Mensagem com Mídia
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/send/media \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-secreto-da-instancia" \
|
||||
-d '{
|
||||
"number": "5511999999999",
|
||||
"mediaUrl": "https://exemplo.com/imagem.jpg",
|
||||
"caption": "Legenda da imagem"
|
||||
}'
|
||||
```
|
||||
|
||||
### Mensagem com Documento
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/send/media \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-secreto-da-instancia" \
|
||||
-d '{
|
||||
"number": "5511999999999",
|
||||
"mediaUrl": "https://exemplo.com/documento.pdf",
|
||||
"fileName": "relatorio.pdf"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Operações de Gerenciamento
|
||||
|
||||
### Listar Instâncias
|
||||
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/all" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
> **Nota:** Use a `GLOBAL_API_KEY` para listar todas as instâncias.
|
||||
|
||||
### Detalhes da Instância
|
||||
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/info/uuid-da-instancia" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
> **Nota:** Use o `instanceId` (UUID) da instância na URL.
|
||||
|
||||
### Desconectar
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/disconnect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-secreto-da-instancia"
|
||||
```
|
||||
|
||||
### Reconectar (novo QR Code)
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/reconnect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-secreto-da-instancia"
|
||||
```
|
||||
|
||||
### Deletar
|
||||
|
||||
```bash
|
||||
curl -X DELETE "http://localhost:4000/instance/delete/uuid-da-instancia" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
> **Nota:** Use a `GLOBAL_API_KEY` e o `instanceId` (UUID) para deletar.
|
||||
|
||||
---
|
||||
|
||||
## Documentação Interativa (Swagger)
|
||||
|
||||
Acesse a interface Swagger para explorar e testar todos os endpoints:
|
||||
|
||||
```
|
||||
http://localhost:4000/swagger/index.html
|
||||
```
|
||||
|
||||
**Passos:**
|
||||
1. Clique em **Authorize** no topo da página
|
||||
2. Insira sua chave de API
|
||||
3. Confirme a autenticação
|
||||
4. Explore e teste os endpoints disponíveis
|
||||
|
||||
---
|
||||
|
||||
## Resolução de Problemas
|
||||
|
||||
### QR Code Expira
|
||||
|
||||
QR Code possui validade limitada (~60 segundos). Se expirar:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/reconnect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-secreto-da-instancia"
|
||||
```
|
||||
|
||||
### Instância Não Encontrada
|
||||
|
||||
Verifique se está usando o token correto:
|
||||
|
||||
```bash
|
||||
# Listar todas as instâncias
|
||||
curl "http://localhost:4000/instance/all" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
### Mensagem Não Entregue
|
||||
|
||||
**Verificações:**
|
||||
|
||||
1. **Status da conexão:**
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/status" \
|
||||
-H "apikey: token-secreto-da-instancia"
|
||||
```
|
||||
Status deve ser `open`.
|
||||
|
||||
2. **Formato do número:**
|
||||
- Apenas dígitos (sem espaços, hífens ou símbolos)
|
||||
- Incluir DDI e DDD
|
||||
- Validar se o número existe no WhatsApp
|
||||
|
||||
3. **Logs do servidor:**
|
||||
```bash
|
||||
docker-compose logs -f evolution-go
|
||||
```
|
||||
|
||||
### Erro de Autenticação
|
||||
|
||||
Verifique se está enviando o header correto:
|
||||
```bash
|
||||
-H "apikey: sua-chave-aqui"
|
||||
```
|
||||
|
||||
Confirme a chave configurada no `docker-compose.yml` ou `.env`.
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
### Documentação da API
|
||||
|
||||
- **[API de Mensagens](../guias-api/api-messages.md)** - Todos os tipos de mensagens
|
||||
- **[API de Grupos](../guias-api/api-groups.md)** - Gerenciamento de grupos
|
||||
- **[API de Usuários](../guias-api/api-users.md)** - Perfis e contatos
|
||||
- **[Referência Completa](../guias-api/api-overview.md)** - Todos os endpoints
|
||||
|
||||
### Recursos Avançados
|
||||
|
||||
- **[Sistema de Eventos](../recursos-avancados/events-system.md)** - Webhooks e filas
|
||||
- **[Webhooks](../recursos-avancados/webhooks.md)** - Receber notificações
|
||||
- **[RabbitMQ](../recursos-avancados/rabbitmq.md)** - Processamento assíncrono
|
||||
- **[MinIO/S3](../recursos-avancados/minio.md)** - Armazenamento de mídia
|
||||
|
||||
### Deploy e Segurança
|
||||
|
||||
- **[Configuração](./configuration.md)** - Variáveis de ambiente
|
||||
- **[Docker Deployment](../deploy-producao/docker-deployment.md)** - Deploy em produção
|
||||
- **[Segurança](../deploy-producao/security.md)** - Boas práticas de segurança
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,223 @@
|
||||
# API de Chamadas
|
||||
|
||||
Documentação do endpoint para gerenciar chamadas WhatsApp.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Rejeitar Chamada](#rejeitar-chamada)
|
||||
|
||||
---
|
||||
|
||||
## Rejeitar Chamada
|
||||
|
||||
Rejeita uma chamada recebida no WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /call/reject`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"callCreator": "[email protected]",
|
||||
"callId": "ABC123XYZ"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `callCreator` | string (JID) | ✅ Sim | JID de quem está ligando |
|
||||
| `callId` | string | ✅ Sim | ID da chamada |
|
||||
|
||||
**Nota**: Os dados da chamada (`callCreator` e `callId`) são recebidos via webhook quando uma chamada chega. Você deve capturar esses dados do evento `call` para usar este endpoint.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Resposta de Erro (400)**:
|
||||
```json
|
||||
{
|
||||
"error": "invalid request body"
|
||||
}
|
||||
```
|
||||
|
||||
**Resposta de Erro (500)**:
|
||||
```json
|
||||
{
|
||||
"error": "instance not found"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/call/reject \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"callCreator": "[email protected]",
|
||||
"callId": "ABC123XYZ"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxo Completo de Rejeição Automática
|
||||
|
||||
### 1. Receber Evento de Chamada via Webhook
|
||||
|
||||
Quando alguém liga para sua instância, você recebe um webhook:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "call",
|
||||
"instance": "minha-instancia",
|
||||
"data": {
|
||||
"id": "ABC123XYZ",
|
||||
"from": "[email protected]",
|
||||
"timestamp": "2025-11-11T10:30:00Z",
|
||||
"isVideo": false,
|
||||
"isGroup": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Rejeitar Automaticamente
|
||||
|
||||
No seu servidor que recebe webhooks, quando chegar um evento de chamada:
|
||||
1. Capture o `id` e o `from` do evento
|
||||
2. Faça uma requisição POST para `/call/reject`
|
||||
3. Use os dados capturados como `callId` e `callCreator`
|
||||
|
||||
Dessa forma, chamadas são rejeitadas automaticamente assim que chegam.
|
||||
|
||||
### 3. Rejeição Seletiva
|
||||
|
||||
Para rejeitar apenas chamadas de números não autorizados:
|
||||
1. Mantenha uma lista de números permitidos
|
||||
2. Ao receber evento de chamada, verifique se o número está na lista
|
||||
3. Se não estiver, rejeite a chamada usando o endpoint `/call/reject`
|
||||
4. Se estiver autorizado, não faça nada (deixe tocar)
|
||||
|
||||
---
|
||||
|
||||
## Casos de Uso
|
||||
|
||||
### 1. Rejeitar Todas as Chamadas
|
||||
|
||||
Útil para contas de atendimento que só respondem via mensagens:
|
||||
1. Configure seu webhook para receber eventos de chamada
|
||||
2. Quando receber evento `call`, rejeite imediatamente
|
||||
3. Envie uma mensagem de texto explicando que não atende chamadas
|
||||
|
||||
### 2. Horário Comercial
|
||||
|
||||
Rejeitar chamadas fora do horário de trabalho:
|
||||
1. Ao receber evento de chamada, verifique o horário atual
|
||||
2. Se estiver fora do horário comercial (ex: Segunda a Sexta, 9h-18h), rejeite
|
||||
3. Envie mensagem informando o horário de atendimento
|
||||
|
||||
### 3. Rejeitar Chamadas de Vídeo
|
||||
|
||||
Aceitar apenas chamadas de áudio:
|
||||
1. Verifique o campo `isVideo` no evento de chamada
|
||||
2. Se for `true`, rejeite a chamada
|
||||
3. Envie mensagem pedindo para ligar com chamada de voz
|
||||
|
||||
---
|
||||
|
||||
## Limitações e Observações
|
||||
|
||||
### Limitações do WhatsApp
|
||||
|
||||
1. **Não é possível aceitar chamadas via API**: A API do WhatsApp Multi-Device não permite aceitar chamadas programaticamente. Você só pode rejeitá-las.
|
||||
|
||||
2. **Chamadas em grupos**: Chamadas em grupos também disparam o evento, mas o campo `isGroup` será `true`.
|
||||
|
||||
3. **Timing**: A rejeição deve ser feita rapidamente. Se demorar muito, a chamada pode cair antes da rejeição.
|
||||
|
||||
### Boas Práticas
|
||||
|
||||
1. **Sempre responda ao webhook rapidamente**: Rejeite a chamada em menos de 2 segundos para evitar timeout.
|
||||
|
||||
2. **Envie mensagem explicativa**: Após rejeitar, informe o usuário o motivo via mensagem de texto.
|
||||
|
||||
3. **Log de chamadas rejeitadas**: Mantenha registro para análise, salvando data/hora, número, ID da chamada e motivo da rejeição.
|
||||
|
||||
4. **Tratamento de erros**: Sempre trate possíveis erros na rejeição para evitar que seu webhook trave ao falhar em rejeitar uma chamada.
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro Comuns
|
||||
|
||||
| Código | Erro | Solução |
|
||||
|--------|------|---------|
|
||||
| 400 | `invalid request body` | Verifique formato do JSON |
|
||||
| 500 | `instance not found` | Instância não conectada |
|
||||
| 500 | `error reject call` | Chamada não existe ou já expirou |
|
||||
|
||||
---
|
||||
|
||||
## Estrutura do Evento de Chamada
|
||||
|
||||
Quando você recebe um webhook de chamada, a estrutura é:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "call",
|
||||
"instance": "minha-instancia",
|
||||
"data": {
|
||||
"id": "ABC123XYZ",
|
||||
"from": "[email protected]",
|
||||
"timestamp": "2025-11-11T10:30:00Z",
|
||||
"isVideo": false,
|
||||
"isGroup": false,
|
||||
"status": "ringing"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos**:
|
||||
- `id`: ID único da chamada (use como `callId`)
|
||||
- `from`: JID de quem está ligando (use como `callCreator`)
|
||||
- `timestamp`: Quando a chamada foi iniciada
|
||||
- `isVideo`: Se é chamada de vídeo (true) ou áudio (false)
|
||||
- `isGroup`: Se é chamada em grupo
|
||||
- `status`: Status da chamada (ringing, timeout, reject)
|
||||
|
||||
---
|
||||
|
||||
## Configuração de Webhooks
|
||||
|
||||
Para receber eventos de chamada, configure o webhook:
|
||||
|
||||
```env
|
||||
WEBHOOK_URL=https://seu-servidor.com/webhook
|
||||
```
|
||||
|
||||
Certifique-se de que seu servidor:
|
||||
1. Aceita requisições POST
|
||||
2. Responde rapidamente (< 5 segundos)
|
||||
3. Retorna status 200 para confirmar recebimento
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [Sistema de Eventos](../recursos-avancados/events-system.md) - Configurar webhooks
|
||||
- [API de Mensagens](./api-messages.md) - Enviar mensagem após rejeitar
|
||||
- [API de Usuários](./api-user.md) - Gerenciar contatos
|
||||
- [Visão Geral da API](./api-overview.md)
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,467 @@
|
||||
# API de Chats
|
||||
|
||||
Documentação completa dos endpoints para gerenciar conversas (pin, arquivo, mute).
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Fixar Conversa](#fixar-conversa)
|
||||
- [Desfixar Conversa](#desfixar-conversa)
|
||||
- [Arquivar Conversa](#arquivar-conversa)
|
||||
- [Desarquivar Conversa](#desarquivar-conversa)
|
||||
- [Silenciar Conversa](#silenciar-conversa)
|
||||
- [Dessilenciar Conversa](#dessilenciar-conversa)
|
||||
- [Sincronizar Histórico](#sincronizar-histórico)
|
||||
|
||||
---
|
||||
|
||||
## Fixar Conversa
|
||||
|
||||
Fixa uma conversa no topo da lista de chats.
|
||||
|
||||
**Endpoint**: `POST /chat/pin`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"chat": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `chat` | string | ✅ Sim | JID do chat (individual ou grupo) |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"timestamp": "2025-11-11T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
# Fixar chat individual
|
||||
curl -X POST http://localhost:4000/chat/pin \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"chat": "[email protected]"
|
||||
}'
|
||||
|
||||
# Fixar grupo
|
||||
curl -X POST http://localhost:4000/chat/pin \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"chat": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Desfixar Conversa
|
||||
|
||||
Remove a fixação de uma conversa.
|
||||
|
||||
**Endpoint**: `POST /chat/unpin`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"chat": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `chat` | string | ✅ Sim | JID do chat |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"timestamp": "2025-11-11T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/chat/unpin \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"chat": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Arquivar Conversa
|
||||
|
||||
Move uma conversa para o arquivo.
|
||||
|
||||
**Endpoint**: `POST /chat/archive`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"chat": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `chat` | string | ✅ Sim | JID do chat |
|
||||
|
||||
**Nota**: Conversas arquivadas não aparecem na lista principal, mas ainda recebem mensagens.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"timestamp": "2025-11-11T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/chat/archive \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"chat": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Desarquivar Conversa
|
||||
|
||||
Restaura uma conversa arquivada para a lista principal.
|
||||
|
||||
**Endpoint**: `POST /chat/unarchive`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"chat": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `chat` | string | ✅ Sim | JID do chat |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"timestamp": "2025-11-11T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/chat/unarchive \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"chat": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Silenciar Conversa
|
||||
|
||||
Silencia notificações de uma conversa por 1 hora.
|
||||
|
||||
**Endpoint**: `POST /chat/mute`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"chat": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `chat` | string | ✅ Sim | JID do chat |
|
||||
|
||||
**Nota**: O silenciamento é fixo por **1 hora** (hard-coded no código: `1*time.Hour`). Para silenciar permanentemente, use o aplicativo WhatsApp.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"timestamp": "2025-11-11T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/chat/mute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"chat": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dessilenciar Conversa
|
||||
|
||||
Remove o silenciamento de uma conversa.
|
||||
|
||||
**Endpoint**: `POST /chat/unmute`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"chat": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `chat` | string | ✅ Sim | JID do chat |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"timestamp": "2025-11-11T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/chat/unmute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"chat": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sincronizar Histórico
|
||||
|
||||
Solicita sincronização de histórico de mensagens antigas (WhatsApp Multi-Device).
|
||||
|
||||
**Endpoint**: `POST /chat/history-sync`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"messageInfo": {
|
||||
"Chat": "[email protected]",
|
||||
"IsFromMe": false,
|
||||
"IsGroup": false,
|
||||
"ID": "3EB0C5A277F7F9B6C599",
|
||||
"Timestamp": "2025-11-11T10:00:00Z"
|
||||
},
|
||||
"count": 50
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `messageInfo` | object | ✅ Sim | Informações da mensagem de referência |
|
||||
| `messageInfo.Chat` | string | ✅ Sim | JID do chat |
|
||||
| `messageInfo.IsFromMe` | bool | ✅ Sim | Se a mensagem foi enviada por você |
|
||||
| `messageInfo.IsGroup` | bool | ✅ Sim | Se é um grupo |
|
||||
| `messageInfo.ID` | string | ✅ Sim | ID da mensagem de referência |
|
||||
| `messageInfo.Timestamp` | string | ✅ Sim | Timestamp da mensagem |
|
||||
| `count` | int | ✅ Sim | Número de mensagens para sincronizar |
|
||||
|
||||
**Nota**: Este endpoint é usado para sincronizar mensagens antigas do histórico do WhatsApp Multi-Device. Requer uma mensagem de referência válida.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"Timestamp": "2025-11-11T10:30:00Z",
|
||||
"ID": "abc123",
|
||||
"ServerID": 12345
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/chat/history-sync \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"messageInfo": {
|
||||
"Chat": "[email protected]",
|
||||
"IsFromMe": false,
|
||||
"IsGroup": false,
|
||||
"ID": "3EB0C5A277F7F9B6C599",
|
||||
"Timestamp": "2025-11-11T10:00:00Z"
|
||||
},
|
||||
"count": 50
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxos de Uso Comuns
|
||||
|
||||
### Organizar Conversas Prioritárias
|
||||
|
||||
```bash
|
||||
# 1. Fixar conversas importantes
|
||||
curl -X POST http://localhost:4000/chat/pin \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"chat": "[email protected]"}'
|
||||
|
||||
# 2. Arquivar conversas antigas
|
||||
curl -X POST http://localhost:4000/chat/archive \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"chat": "[email protected]"}'
|
||||
```
|
||||
|
||||
### Gerenciar Notificações
|
||||
|
||||
```bash
|
||||
# Silenciar grupo temporariamente (1 hora)
|
||||
curl -X POST http://localhost:4000/chat/mute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"chat": "[email protected]"}'
|
||||
|
||||
# Reativar notificações
|
||||
curl -X POST http://localhost:4000/chat/unmute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"chat": "[email protected]"}'
|
||||
```
|
||||
|
||||
### Limpar Lista de Chats
|
||||
|
||||
```bash
|
||||
# Arquivar múltiplas conversas
|
||||
CHATS=("[email protected]" "[email protected]" "[email protected]")
|
||||
|
||||
for chat in "\${CHATS[@]}"; do
|
||||
curl -X POST http://localhost:4000/chat/archive \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d "{"chat": "$chat"}"
|
||||
done
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro Comuns
|
||||
|
||||
| Código | Erro | Solução |
|
||||
|--------|------|---------|
|
||||
| 400 | `chat is required` | Forneça o campo `chat` |
|
||||
| 500 | `instance not found` | Instância não conectada |
|
||||
| 500 | `invalid phone number` | JID inválido (formato incorreto) |
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Validar JID
|
||||
Sempre use JIDs no formato correto:
|
||||
- Chat individual: `[email protected]`
|
||||
- Grupo: `[email protected]`
|
||||
|
||||
### 2. Gerenciar Estado
|
||||
Mantenha controle do estado dos chats na sua aplicação:
|
||||
- Registre quais chats estão fixados, arquivados e silenciados
|
||||
- Lembre-se: um chat não pode estar fixado e arquivado ao mesmo tempo
|
||||
- Ao fixar um chat, ele é automaticamente desarquivado pelo WhatsApp
|
||||
|
||||
### 3. Silenciamento Temporário
|
||||
Lembre-se que o mute dura apenas 1 hora. Para silenciamento permanente:
|
||||
- Use o aplicativo WhatsApp nativo
|
||||
- Ou implemente lógica para re-silenciar periodicamente
|
||||
|
||||
### 4. Limite de Chats Fixados
|
||||
O WhatsApp permite fixar até **3 chats** no topo. Não há validação na API, mas isso é uma limitação do WhatsApp.
|
||||
|
||||
### 5. Sincronização de Histórico
|
||||
Use com cuidado - sincronizar histórico consome recursos. Recomendações:
|
||||
- Sincronize no máximo **100 mensagens** por vez
|
||||
- Aguarde resposta antes de nova sincronização
|
||||
- Use apenas quando necessário (nova instalação, restauração)
|
||||
|
||||
---
|
||||
|
||||
## Diferenças de Comportamento
|
||||
|
||||
### Fixar vs Arquivar
|
||||
- **Fixar**: Mantém conversa no topo (máx 3)
|
||||
- **Arquivar**: Remove da lista principal, mas mantém notificações
|
||||
|
||||
### Mute vs Archive
|
||||
- **Mute**: Silencia notificações, mas chat permanece visível
|
||||
- **Archive**: Oculta chat, mas notificações continuam (a menos que também esteja mutado)
|
||||
|
||||
### Para Combinar
|
||||
```bash
|
||||
# Arquivar E silenciar (para "esconder" completamente)
|
||||
curl -X POST http://localhost:4000/chat/archive ...
|
||||
curl -X POST http://localhost:4000/chat/mute ...
|
||||
|
||||
# Fixar (automaticamente desarquiva)
|
||||
curl -X POST http://localhost:4000/chat/pin ...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Labels](./api-labels.md) - Organizar chats com etiquetas
|
||||
- [API de Mensagens](./api-messages.md) - Gerenciar mensagens
|
||||
- [API de Grupos](./api-groups.md) - Gerenciar grupos
|
||||
- [Visão Geral da API](./api-overview.md)
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,376 @@
|
||||
# API de Comunidades
|
||||
|
||||
Documentação dos endpoints para gerenciar Comunidades WhatsApp.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Criar Comunidade](#criar-comunidade)
|
||||
- [Adicionar Grupos](#adicionar-grupos)
|
||||
- [Remover Grupos](#remover-grupos)
|
||||
|
||||
---
|
||||
|
||||
## O que são Comunidades?
|
||||
|
||||
**Comunidades** são um recurso do WhatsApp que permite agrupar vários grupos relacionados sob uma única estrutura. É como um "grupo de grupos".
|
||||
|
||||
**Características**:
|
||||
- Uma comunidade pode conter **até 50 grupos**
|
||||
- Cada comunidade tem um **canal de anúncios** (grupo pai)
|
||||
- Membros da comunidade veem todos os grupos vinculados
|
||||
- Facilita organização de organizações, escolas, condomínios, etc.
|
||||
|
||||
---
|
||||
|
||||
## Criar Comunidade
|
||||
|
||||
Cria uma nova comunidade WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /community/create`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"communityName": "Escola ABC"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `communityName` | string | ✅ Sim | Nome da comunidade |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"JID": "[email protected]",
|
||||
"OwnerJID": "[email protected]",
|
||||
"GroupName": {
|
||||
"Name": "Escola ABC",
|
||||
"NameSetAt": "2025-11-11T10:30:00Z",
|
||||
"NameSetBy": "[email protected]"
|
||||
},
|
||||
"GroupCreated": "2025-11-11T10:30:00Z",
|
||||
"GroupParent": {
|
||||
"IsParent": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `JID`: ID único da comunidade (formato de grupo @g.us)
|
||||
- `OwnerJID`: Criador da comunidade
|
||||
- `GroupName`: Nome e metadados
|
||||
- `GroupParent.IsParent`: true (indica que é uma comunidade)
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/community/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"communityName": "Condomínio Residencial"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Adicionar Grupos
|
||||
|
||||
Adiciona (vincula) grupos existentes a uma comunidade.
|
||||
|
||||
**Endpoint**: `POST /community/add`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"communityJid": "[email protected]",
|
||||
"groupJid": [
|
||||
"[email protected]",
|
||||
"[email protected]"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `communityJid` | string | ✅ Sim | JID da comunidade |
|
||||
| `groupJid` | array | ✅ Sim | Array de JIDs de grupos para adicionar |
|
||||
|
||||
**Nota**: Os grupos devem **já existir** e você deve ser **admin** de ambos (comunidade e grupos).
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"success": [
|
||||
"[email protected]",
|
||||
"[email protected]"
|
||||
],
|
||||
"failed": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `success`: Array de grupos adicionados com sucesso
|
||||
- `failed`: Array de grupos que falharam (não existe, sem permissão, etc)
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/community/add \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"communityJid": "[email protected]",
|
||||
"groupJid": [
|
||||
"[email protected]"
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Remover Grupos
|
||||
|
||||
Remove (desvincula) grupos de uma comunidade.
|
||||
|
||||
**Endpoint**: `POST /community/remove`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"communityJid": "[email protected]",
|
||||
"groupJid": [
|
||||
"[email protected]"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `communityJid` | string | ✅ Sim | JID da comunidade |
|
||||
| `groupJid` | array | ✅ Sim | Array de JIDs de grupos para remover |
|
||||
|
||||
**Nota**: Remover um grupo da comunidade **não deleta o grupo**, apenas o desvincula.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"success": [
|
||||
"[email protected]"
|
||||
],
|
||||
"failed": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/community/remove \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"communityJid": "[email protected]",
|
||||
"groupJid": [
|
||||
"[email protected]"
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxo Completo de Gerenciamento
|
||||
|
||||
### 1. Criar Comunidade e Organizar Grupos
|
||||
|
||||
**Fluxo completo**:
|
||||
|
||||
1. **Criar a comunidade** usando `POST /community/create`
|
||||
2. **Criar os grupos** que farão parte da comunidade usando `POST /group/create`
|
||||
3. **Adicionar os grupos à comunidade** usando `POST /community/add` com os JIDs obtidos nos passos anteriores
|
||||
|
||||
Exemplo:
|
||||
- Primeiro, crie uma comunidade "Escola Municipal" e guarde o `JID` retornado
|
||||
- Depois, crie dois grupos "1º Ano A" e "2º Ano B" e guarde os JIDs
|
||||
- Por fim, adicione os grupos à comunidade usando os JIDs
|
||||
|
||||
### 2. Reorganizar Comunidade
|
||||
|
||||
Para reorganizar uma comunidade (remover grupos antigos e adicionar novos):
|
||||
|
||||
1. Use `POST /community/remove` para remover grupos que não fazem mais parte
|
||||
2. Use `POST /community/add` para adicionar novos grupos
|
||||
|
||||
Exemplo: Se você precisa substituir o grupo "120363OLD1@g.us" por dois novos grupos, primeiro remova o antigo e depois adicione os novos usando os respectivos endpoints.
|
||||
|
||||
---
|
||||
|
||||
## Casos de Uso
|
||||
|
||||
### 1. Escola / Universidade
|
||||
|
||||
```
|
||||
Comunidade: "Universidade XYZ"
|
||||
├── Grupo: Administração
|
||||
├── Grupo: Engenharia - 1º Ano
|
||||
├── Grupo: Engenharia - 2º Ano
|
||||
├── Grupo: Medicina - 1º Ano
|
||||
└── Grupo: Eventos
|
||||
```
|
||||
|
||||
### 2. Condomínio
|
||||
|
||||
```
|
||||
Comunidade: "Condomínio Residencial"
|
||||
├── Grupo: Síndico e Zeladores
|
||||
├── Grupo: Bloco A
|
||||
├── Grupo: Bloco B
|
||||
├── Grupo: Churrasqueira (Reservas)
|
||||
└── Grupo: Comunicados Gerais
|
||||
```
|
||||
|
||||
### 3. Empresa
|
||||
|
||||
```
|
||||
Comunidade: "Empresa LTDA"
|
||||
├── Grupo: Diretoria
|
||||
├── Grupo: TI
|
||||
├── Grupo: Vendas
|
||||
├── Grupo: Marketing
|
||||
└── Grupo: RH
|
||||
```
|
||||
|
||||
### 4. Igreja / Instituição Religiosa
|
||||
|
||||
```
|
||||
Comunidade: "Igreja Central"
|
||||
├── Grupo: Liderança
|
||||
├── Grupo: Jovens
|
||||
├── Grupo: Mulheres
|
||||
├── Grupo: Eventos
|
||||
└── Grupo: Voluntários
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Permissões e Limitações
|
||||
|
||||
### Permissões Necessárias
|
||||
|
||||
Para gerenciar comunidades, você precisa ser:
|
||||
1. **Criador** da comunidade (para adicionar/remover grupos)
|
||||
2. **Admin** dos grupos que deseja vincular
|
||||
|
||||
### Limitações do WhatsApp
|
||||
|
||||
| Limitação | Valor |
|
||||
|-----------|-------|
|
||||
| Máximo de grupos por comunidade | 50 |
|
||||
| Máximo de participantes por grupo | 1024 |
|
||||
| Máximo de admins por grupo | Ilimitado |
|
||||
|
||||
### Comportamento
|
||||
|
||||
- **Desvincular grupo**: Não deleta o grupo, apenas remove da comunidade
|
||||
- **Deletar comunidade**: Não deleta os grupos vinculados
|
||||
- **Sair da comunidade**: Você sai de todos os grupos vinculados
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro Comuns
|
||||
|
||||
| Código | Erro | Solução |
|
||||
|--------|------|---------|
|
||||
| 400 | `community name is required` | Forneça o nome da comunidade |
|
||||
| 400 | `community jid is required` | Forneça o JID da comunidade |
|
||||
| 400 | `group jid is required` | Forneça array de JIDs de grupos |
|
||||
| 500 | `instance not found` | Instância não conectada |
|
||||
| 500 | `error parse community jid` | JID inválido |
|
||||
| 500 | `error link group` | Sem permissão ou grupo não existe |
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Planeje a Estrutura
|
||||
|
||||
Antes de criar, defina a organização:
|
||||
```
|
||||
Comunidade (Tema geral)
|
||||
├── Grupo 1 (Categoria específica)
|
||||
├── Grupo 2 (Categoria específica)
|
||||
└── Grupo 3 (Categoria específica)
|
||||
```
|
||||
|
||||
### 2. Nomeação Clara
|
||||
|
||||
Use nomes descritivos:
|
||||
- ✅ "Escola ABC - 1º Ano A"
|
||||
- ✅ "Condomínio XYZ - Bloco A"
|
||||
- ❌ "Grupo 1"
|
||||
- ❌ "ABC"
|
||||
|
||||
### 3. Canal de Anúncios
|
||||
|
||||
A comunidade em si funciona como canal de anúncios para todos os grupos. Use-a para:
|
||||
- Comunicados gerais
|
||||
- Eventos importantes
|
||||
- Informações que afetam todos
|
||||
|
||||
### 4. Organize por Hierarquia
|
||||
|
||||
```
|
||||
Comunidade (Nível mais alto)
|
||||
└── Grupos (Nível específico)
|
||||
└── Participantes (Nível individual)
|
||||
```
|
||||
|
||||
### 5. Limite de Grupos
|
||||
|
||||
Não exceda 50 grupos por comunidade. Se precisar de mais:
|
||||
- Crie múltiplas comunidades
|
||||
- Reorganize grupos por temas
|
||||
- Arquive grupos inativos
|
||||
|
||||
---
|
||||
|
||||
## Diferenças: Comunidade vs Grupo
|
||||
|
||||
| Aspecto | Comunidade | Grupo |
|
||||
|---------|------------|-------|
|
||||
| Função | Agrupar grupos relacionados | Conversação direta |
|
||||
| Limite de membros | 50 grupos × 1024 = 51.200 | 1024 |
|
||||
| Estrutura | Hierárquica (pais) | Plana (participantes) |
|
||||
| Mensagens | Canal de anúncios | Conversa completa |
|
||||
| Admin | Admin da comunidade | Admin do grupo |
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Grupos](./api-groups.md) - Criar e gerenciar grupos
|
||||
- [API de Mensagens](./api-messages.md) - Enviar anúncios
|
||||
- [API de Usuários](./api-user.md) - Gerenciar contatos
|
||||
- [Visão Geral da API](./api-overview.md)
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,808 @@
|
||||
# API de Grupos
|
||||
|
||||
Documentação completa dos endpoints para gerenciar grupos WhatsApp.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Listar Grupos](#listar-grupos)
|
||||
- [Informações do Grupo](#informações-do-grupo)
|
||||
- [Link de Convite](#link-de-convite)
|
||||
- [Criar Grupo](#criar-grupo)
|
||||
- [Gerenciar Participantes](#gerenciar-participantes)
|
||||
- [Configurações do Grupo](#configurações-do-grupo)
|
||||
- [Alterar Foto](#alterar-foto)
|
||||
- [Alterar Nome](#alterar-nome)
|
||||
- [Alterar Descrição](#alterar-descrição)
|
||||
- [Meus Grupos (Admin)](#meus-grupos-admin)
|
||||
- [Entrar via Link](#entrar-via-link)
|
||||
- [Sair do Grupo](#sair-do-grupo)
|
||||
|
||||
---
|
||||
|
||||
## Listar Grupos
|
||||
|
||||
Lista todos os grupos que você participa.
|
||||
|
||||
**Endpoint**: `GET /group/list`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"OwnerJID": "[email protected]",
|
||||
"GroupName": {
|
||||
"Name": "Equipe de Vendas",
|
||||
"NameSetAt": "2025-01-15T10:30:00Z",
|
||||
"NameSetBy": "[email protected]"
|
||||
},
|
||||
"GroupTopic": {
|
||||
"Topic": "Discussões sobre vendas e metas",
|
||||
"TopicID": "abc123",
|
||||
"TopicSetAt": "2025-01-15T10:35:00Z",
|
||||
"TopicSetBy": "[email protected]"
|
||||
},
|
||||
"GroupCreated": "2025-01-15T10:00:00Z",
|
||||
"Participants": [
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"IsAdmin": true,
|
||||
"IsSuperAdmin": true
|
||||
},
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"IsAdmin": false,
|
||||
"IsSuperAdmin": false
|
||||
}
|
||||
],
|
||||
"ParticipantVersionID": "abc123"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `JID`: ID único do grupo (sempre termina com @g.us)
|
||||
- `OwnerJID`: Criador do grupo
|
||||
- `GroupName`: Nome e metadados
|
||||
- `GroupTopic`: Descrição do grupo
|
||||
- `Participants`: Lista de participantes com permissões
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X GET http://localhost:4000/group/list \
|
||||
-H "apikey: SUA-CHAVE-API"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Informações do Grupo
|
||||
|
||||
Obtém informações detalhadas de um grupo específico.
|
||||
|
||||
**Endpoint**: `POST /group/info`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupJid` | string | ✅ Sim | JID do grupo |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"JID": "[email protected]",
|
||||
"OwnerJID": "[email protected]",
|
||||
"GroupName": {
|
||||
"Name": "Equipe de Vendas",
|
||||
"NameSetAt": "2025-01-15T10:30:00Z",
|
||||
"NameSetBy": "[email protected]"
|
||||
},
|
||||
"GroupTopic": {
|
||||
"Topic": "Discussões sobre vendas",
|
||||
"TopicID": "abc123",
|
||||
"TopicSetAt": "2025-01-15T10:35:00Z",
|
||||
"TopicSetBy": "[email protected]"
|
||||
},
|
||||
"GroupCreated": "2025-01-15T10:00:00Z",
|
||||
"Participants": [
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"IsAdmin": true,
|
||||
"IsSuperAdmin": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/group/info \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Link de Convite
|
||||
|
||||
Obtém ou regenera o link de convite do grupo.
|
||||
|
||||
**Endpoint**: `POST /group/invitelink`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]",
|
||||
"reset": false
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupJid` | string | ✅ Sim | JID do grupo |
|
||||
| `reset` | bool | ❌ Não | Se true, gera um novo link (invalida o anterior) |
|
||||
|
||||
**Nota**: Apenas admins podem obter/resetar links de convite.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
# Obter link existente
|
||||
curl -X POST http://localhost:4000/group/invitelink \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"reset": false
|
||||
}'
|
||||
|
||||
# Gerar novo link
|
||||
curl -X POST http://localhost:4000/group/invitelink \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"reset": true
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Criar Grupo
|
||||
|
||||
Cria um novo grupo WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /group/create`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupName": "Equipe de Vendas",
|
||||
"participants": [
|
||||
"5511999999999",
|
||||
"5511888888888",
|
||||
"5511777777777"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupName` | string | ✅ Sim | Nome do grupo |
|
||||
| `participants` | array | ✅ Sim | Array de números dos participantes (mínimo 1) |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"jid": "[email protected]",
|
||||
"name": "Equipe de Vendas",
|
||||
"owner": "[email protected]",
|
||||
"added": [
|
||||
"[email protected]",
|
||||
"[email protected]"
|
||||
],
|
||||
"failed": [
|
||||
"[email protected]"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `jid`: ID do grupo criado
|
||||
- `name`: Nome do grupo
|
||||
- `owner`: Criador (você)
|
||||
- `added`: Participantes adicionados com sucesso
|
||||
- `failed`: Participantes que falharam (número inválido, bloqueado, etc)
|
||||
|
||||
**Nota**: É normal que alguns participantes falhem (números inexistentes, bloqueados, etc).
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/group/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupName": "Meu Grupo",
|
||||
"participants": ["5511999999999", "5511888888888"]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Gerenciar Participantes
|
||||
|
||||
Adiciona, remove ou promove participantes do grupo.
|
||||
|
||||
**Endpoint**: `POST /group/participant`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "add",
|
||||
"participants": ["5511999999999", "5511888888888"]
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupJid` | string | ✅ Sim | JID do grupo |
|
||||
| `action` | string | ✅ Sim | Ação a executar |
|
||||
| `participants` | array | ✅ Sim | Array de números |
|
||||
|
||||
**Ações Disponíveis**:
|
||||
|
||||
| Action | Descrição | Requer Admin |
|
||||
|--------|-----------|--------------|
|
||||
| `add` | Adicionar participantes | ✅ Sim |
|
||||
| `remove` | Remover participantes | ✅ Sim |
|
||||
| `promote` | Promover a admin | ✅ Sim |
|
||||
| `demote` | Remover admin | ✅ Sim |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Resposta de Erro (500)**:
|
||||
```json
|
||||
{
|
||||
"error": "error create group: 403 forbidden"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplos cURL**:
|
||||
|
||||
```bash
|
||||
# Adicionar participantes
|
||||
curl -X POST http://localhost:4000/group/participant \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "add",
|
||||
"participants": ["5511999999999"]
|
||||
}'
|
||||
|
||||
# Remover participantes
|
||||
curl -X POST http://localhost:4000/group/participant \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "remove",
|
||||
"participants": ["5511888888888"]
|
||||
}'
|
||||
|
||||
# Promover a admin
|
||||
curl -X POST http://localhost:4000/group/participant \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "promote",
|
||||
"participants": ["5511999999999"]
|
||||
}'
|
||||
|
||||
# Remover admin (rebaixar)
|
||||
curl -X POST http://localhost:4000/group/participant \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "demote",
|
||||
"participants": ["5511999999999"]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configurações do Grupo
|
||||
|
||||
### Alterar Foto
|
||||
|
||||
Define a foto do grupo.
|
||||
|
||||
**Endpoint**: `POST /group/photo`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]",
|
||||
"image": "https://exemplo.com/logo.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
Ou com base64:
|
||||
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]",
|
||||
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupJid` | string | ✅ Sim | JID do grupo |
|
||||
| `image` | string | ✅ Sim | URL ou base64 da imagem |
|
||||
|
||||
**Formatos Aceitos**:
|
||||
- URL (http:// ou https://)
|
||||
- Base64 (data:image/jpeg;base64,... ou data:image/png;base64,...)
|
||||
|
||||
**Nota**: Apenas admins podem alterar a foto.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": "abc123"
|
||||
}
|
||||
```
|
||||
|
||||
O campo `data` contém o ID da nova foto.
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
# Com URL
|
||||
curl -X POST http://localhost:4000/group/photo \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"image": "https://exemplo.com/logo.jpg"
|
||||
}'
|
||||
|
||||
# Com base64
|
||||
curl -X POST http://localhost:4000/group/photo \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Alterar Nome
|
||||
|
||||
Altera o nome do grupo.
|
||||
|
||||
**Endpoint**: `POST /group/name`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]",
|
||||
"name": "Novo Nome do Grupo"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupJid` | string | ✅ Sim | JID do grupo |
|
||||
| `name` | string | ✅ Sim | Novo nome (máx 25 caracteres) |
|
||||
|
||||
**Nota**: Apenas admins podem alterar o nome.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/group/name \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"name": "Equipe Marketing 2025"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Alterar Descrição
|
||||
|
||||
Altera a descrição do grupo.
|
||||
|
||||
**Endpoint**: `POST /group/description`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]",
|
||||
"description": "Grupo para discussões sobre marketing e estratégias de vendas."
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupJid` | string | ✅ Sim | JID do grupo |
|
||||
| `description` | string | ✅ Sim | Nova descrição (máx 512 caracteres) |
|
||||
|
||||
**Nota**: Apenas admins podem alterar a descrição.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/group/description \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"description": "Grupo oficial da empresa - Apenas assuntos profissionais"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Meus Grupos (Admin)
|
||||
|
||||
Lista apenas os grupos onde você é o **proprietário/criador**.
|
||||
|
||||
**Endpoint**: `GET /group/myall`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"OwnerJID": "[email protected]",
|
||||
"GroupName": {
|
||||
"Name": "Meu Grupo",
|
||||
"NameSetAt": "2025-01-15T10:30:00Z",
|
||||
"NameSetBy": "[email protected]"
|
||||
},
|
||||
"Participants": [...]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Diferença**:
|
||||
- `/group/list` - Todos os grupos que você participa
|
||||
- `/group/myall` - Apenas grupos que você criou (owner)
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X GET http://localhost:4000/group/myall \
|
||||
-H "apikey: SUA-CHAVE-API"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Entrar via Link
|
||||
|
||||
Entra em um grupo através de um link de convite.
|
||||
|
||||
**Endpoint**: `POST /group/join`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"code": "ABCDEFGHIJKLMNOP"
|
||||
}
|
||||
```
|
||||
|
||||
Ou com URL completa:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `code` | string | ✅ Sim | Código do link ou URL completa |
|
||||
|
||||
**Nota**: O código é a parte após `https://chat.whatsapp.com/`.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Resposta de Erro (500)**:
|
||||
```json
|
||||
{
|
||||
"error": "error create group: 404 not found"
|
||||
}
|
||||
```
|
||||
|
||||
Erros comuns:
|
||||
- `404 not found` - Link inválido ou expirado
|
||||
- `403 forbidden` - Você foi banido ou removido
|
||||
- `406 not acceptable` - Grupo cheio (256 participantes)
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
# Com código
|
||||
curl -X POST http://localhost:4000/group/join \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"code": "ABCDEFGHIJKLMNOP"
|
||||
}'
|
||||
|
||||
# Com URL completa
|
||||
curl -X POST http://localhost:4000/group/join \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"code": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sair do Grupo
|
||||
|
||||
Sai de um grupo WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /group/leave`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupJid": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupJid` | string | ✅ Sim | JID do grupo |
|
||||
|
||||
**Nota**: Se você for o único admin, o grupo ficará sem admins até que outro seja promovido ou o grupo seja excluído.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/group/leave \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxo Completo de Gerenciamento
|
||||
|
||||
### 1. Criar e Configurar Grupo
|
||||
|
||||
```bash
|
||||
# 1. Criar grupo
|
||||
GROUP_JID=$(curl -X POST http://localhost:4000/group/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupName": "Meu Grupo",
|
||||
"participants": ["5511999999999"]
|
||||
}' | jq -r '.data.jid')
|
||||
|
||||
# 2. Adicionar foto
|
||||
curl -X POST http://localhost:4000/group/photo \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d "{
|
||||
"groupJid": "$GROUP_JID",
|
||||
"image": "https://exemplo.com/logo.jpg"
|
||||
}"
|
||||
|
||||
# 3. Adicionar descrição
|
||||
curl -X POST http://localhost:4000/group/description \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d "{
|
||||
"groupJid": "$GROUP_JID",
|
||||
"description": "Grupo oficial da empresa"
|
||||
}"
|
||||
|
||||
# 4. Obter link de convite
|
||||
curl -X POST http://localhost:4000/group/invitelink \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d "{
|
||||
"groupJid": "$GROUP_JID",
|
||||
"reset": false
|
||||
}"
|
||||
```
|
||||
|
||||
### 2. Gerenciar Participantes
|
||||
|
||||
```bash
|
||||
# Adicionar novos membros
|
||||
curl -X POST http://localhost:4000/group/participant \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "add",
|
||||
"participants": ["5511888888888", "5511777777777"]
|
||||
}'
|
||||
|
||||
# Promover a admin
|
||||
curl -X POST http://localhost:4000/group/participant \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "promote",
|
||||
"participants": ["5511888888888"]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro Comuns
|
||||
|
||||
| Código | Erro | Solução |
|
||||
|--------|------|---------|
|
||||
| 400 | `groupJid is required` | Forneça o JID do grupo |
|
||||
| 400 | `groupName is required` | Forneça o nome do grupo |
|
||||
| 400 | `participants are required` | Forneça array de participantes |
|
||||
| 400 | `action is required` | Especifique a ação (add/remove/promote/demote) |
|
||||
| 500 | `invalid group jid` | JID de grupo inválido (deve terminar com @g.us) |
|
||||
| 500 | `403 forbidden` | Sem permissão (não é admin) |
|
||||
| 500 | `404 not found` | Grupo não existe ou link inválido |
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Verificar Permissões
|
||||
Sempre verifique se você é admin antes de tentar alterar configurações:
|
||||
```bash
|
||||
# 1. Obter info do grupo
|
||||
INFO=$(curl -s -X POST http://localhost:4000/group/info \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"groupJid": "[email protected]"}')
|
||||
|
||||
# 2. Verificar se você é admin
|
||||
echo $INFO | jq '.data.Participants[] | select(.IsAdmin == true)'
|
||||
```
|
||||
|
||||
### 2. Validar Números
|
||||
Valide números antes de adicionar ao grupo:
|
||||
```bash
|
||||
# 1. Verificar se número existe
|
||||
curl -X POST http://localhost:4000/user/check \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"number": ["5511999999999"]}'
|
||||
|
||||
# 2. Se IsInWhatsapp=true, adicionar ao grupo
|
||||
curl -X POST http://localhost:4000/group/participant \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupJid": "[email protected]",
|
||||
"action": "add",
|
||||
"participants": ["5511999999999"]
|
||||
}'
|
||||
```
|
||||
|
||||
### 3. Limites do WhatsApp
|
||||
Respeite os limites do WhatsApp:
|
||||
- **256 participantes** por grupo
|
||||
- **25 caracteres** para nome do grupo
|
||||
- **512 caracteres** para descrição
|
||||
- Não adicione mais de **20 participantes de uma vez**
|
||||
|
||||
### 4. Tratamento de Falhas
|
||||
Ao criar grupo, sempre verifique o campo `failed` na resposta:
|
||||
- O campo `added` contém os participantes adicionados com sucesso
|
||||
- O campo `failed` contém os que falharam (número inválido, não tem WhatsApp, etc)
|
||||
- Se houver falhas, você pode tentar adicionar novamente após verificação
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Mensagens](./api-messages.md) - Enviar mensagens em grupos
|
||||
- [API de Usuários](./api-user.md) - Gerenciar contatos
|
||||
- [API de Chats](./api-chats.md) - Gerenciar conversas
|
||||
- [Visão Geral da API](./api-overview.md)
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,853 @@
|
||||
# API de Instâncias
|
||||
|
||||
Documentação completa dos endpoints para gerenciar instâncias WhatsApp.
|
||||
|
||||
## Visão Geral
|
||||
|
||||
Uma **instância** representa uma conexão individual com o WhatsApp. Cada instância mantém sua própria sessão, autenticação e configurações independentes.
|
||||
|
||||
**Importante**: A maioria das rotas identifica a instância automaticamente através do header `apikey` (token da instância). Apenas rotas administrativas usam `:instanceId` na URL e exigem a `GLOBAL_API_KEY` configurada no ambiente.
|
||||
|
||||
## Endpoints Disponíveis
|
||||
|
||||
### Gerenciamento Básico (Administrativo - usa GLOBAL_API_KEY)
|
||||
- `POST /instance/create` - Criar nova instância
|
||||
- `GET /instance/all` - Listar todas as instâncias
|
||||
- `GET /instance/info/:instanceId` - Informações da instância
|
||||
- `DELETE /instance/delete/:instanceId` - Deletar instância
|
||||
|
||||
### Conexão (usa token da instância)
|
||||
- `POST /instance/connect` - Conectar via QR Code
|
||||
- `GET /instance/qr` - Obter QR Code
|
||||
- `POST /instance/pair` - Conectar via código de pareamento
|
||||
- `GET /instance/status` - Status da conexão
|
||||
- `POST /instance/disconnect` - Desconectar
|
||||
- `POST /instance/reconnect` - Reconectar
|
||||
- `DELETE /instance/logout` - Fazer logout
|
||||
|
||||
### Gerenciamento Avançado (Administrativo - usa GLOBAL_API_KEY)
|
||||
- `POST /instance/proxy/:instanceId` - Configurar proxy
|
||||
- `DELETE /instance/proxy/:instanceId` - Remover proxy
|
||||
- `POST /instance/forcereconnect/:instanceId` - Forçar reconexão
|
||||
- `GET /instance/logs/:instanceId` - Obter logs
|
||||
- `GET /instance/:instanceId/advanced-settings` - Configurações avançadas
|
||||
- `PUT /instance/:instanceId/advanced-settings` - Atualizar configurações
|
||||
|
||||
---
|
||||
|
||||
## Criar Instância
|
||||
|
||||
Cria uma nova instância WhatsApp.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
POST /instance/create
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (variável de ambiente), não o token da instância.
|
||||
|
||||
### Body
|
||||
```json
|
||||
{
|
||||
"name": "vendas",
|
||||
"token": "token-seguro-unico",
|
||||
"webhook": "https://seu-servidor.com/webhook",
|
||||
"webhookEvents": ["messages.upsert", "connection.update"],
|
||||
"proxy": {
|
||||
"host": "proxy.exemplo.com",
|
||||
"port": "8080",
|
||||
"username": "usuario",
|
||||
"password": "senha"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Parâmetros
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| name | string | ✅ Sim | Nome único da instância |
|
||||
| token | string | ✅ Sim | Token de autenticação da instância |
|
||||
| webhook | string | ❌ Não | URL para receber webhooks |
|
||||
| webhookEvents | array | ❌ Não | Eventos específicos para webhook |
|
||||
| proxy | object | ❌ Não | Configuração de proxy |
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"name": "vendas",
|
||||
"token": "token-seguro-unico",
|
||||
"webhook": "https://seu-servidor.com/webhook",
|
||||
"status": "created",
|
||||
"createdAt": "2025-01-15T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Resposta Erro (400)
|
||||
```json
|
||||
{
|
||||
"error": "name is required"
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/create -H "Content-Type: application/json" -H "apikey: SUA-CHAVE-API" -d '{
|
||||
"name": "vendas",
|
||||
"token": "meu-token-seguro"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Conectar Instância
|
||||
|
||||
Inicia o processo de conexão via QR Code.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
POST /instance/connect
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: TOKEN-DA-INSTANCIA
|
||||
```
|
||||
|
||||
**⚠️ Atenção**: Use o `token` que você definiu ao criar a instância, NÃO a `GLOBAL_API_KEY`.
|
||||
|
||||
### Body
|
||||
```json
|
||||
{
|
||||
"webhookUrl": "https://seu-servidor.com/webhook",
|
||||
"subscribe": ["messages.upsert", "connection.update"]
|
||||
}
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"jid": "[email protected]",
|
||||
"webhookUrl": "https://seu-servidor.com/webhook",
|
||||
"eventString": "messages.upsert,connection.update"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/connect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-da-instancia-vendas" \
|
||||
-d '{
|
||||
"webhookUrl": "https://seu-servidor.com/webhook",
|
||||
"subscribe": ["messages.upsert"]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Obter QR Code
|
||||
|
||||
Retorna o QR Code para escanear com WhatsApp.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
GET /instance/qr
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: TOKEN-DA-INSTANCIA
|
||||
```
|
||||
|
||||
**Importante**: A instância é identificada automaticamente pelo token no header.
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"qrcode": "2@abcd1234...",
|
||||
"code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/qr" \
|
||||
-H "apikey: token-da-instancia-vendas"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Conectar via Código de Pareamento
|
||||
|
||||
Conecta usando código de 8 dígitos em vez de QR Code.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
POST /instance/pair
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: TOKEN-DA-INSTANCIA
|
||||
```
|
||||
|
||||
### Body
|
||||
```json
|
||||
{
|
||||
"phone": "5511999999999"
|
||||
}
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"code": "12345678"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Como Usar
|
||||
1. Faça a requisição com seu número
|
||||
2. Receba o código de 8 dígitos
|
||||
3. No WhatsApp: Aparelhos conectados > Conectar dispositivo > Conectar com número de telefone
|
||||
4. Digite o código recebido
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/pair \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-da-instancia-vendas" \
|
||||
-d '{"phone": "5511999999999"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Status da Conexão
|
||||
|
||||
Verifica o status atual da instância.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
GET /instance/status
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: TOKEN-DA-INSTANCIA
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"connected": true,
|
||||
"loggedIn": true,
|
||||
"name": "Minha Empresa",
|
||||
"myJid": "[email protected]"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Status Possíveis
|
||||
- `connected: false, loggedIn: false` - Instância criada mas não conectada
|
||||
- `connected: true, loggedIn: false` - Conectando (aguardando QR Code)
|
||||
- `connected: true, loggedIn: true` - Conectado e ativo
|
||||
- `connected: false, loggedIn: true` - Sessão válida mas desconectado temporariamente
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/status" \
|
||||
-H "apikey: token-da-instancia-vendas"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Listar Todas as Instâncias
|
||||
|
||||
Retorna todas as instâncias cadastradas.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
GET /instance/all
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa).
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"id": "abc123",
|
||||
"name": "vendas",
|
||||
"connected": true,
|
||||
"jid": "[email protected]"
|
||||
},
|
||||
{
|
||||
"id": "def456",
|
||||
"name": "suporte",
|
||||
"connected": false,
|
||||
"jid": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/all" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Informações da Instância
|
||||
|
||||
Obtém informações detalhadas de uma instância específica.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
GET /instance/info/:instanceId
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa) e o ID da instância no path.
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"id": "abc123",
|
||||
"name": "vendas",
|
||||
"token": "token-seguro",
|
||||
"webhook": "https://seu-servidor.com/webhook",
|
||||
"events": "messages.upsert,connection.update",
|
||||
"connected": true,
|
||||
"jid": "[email protected]",
|
||||
"createdAt": "2025-01-15T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/info/vendas" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Desconectar Instância
|
||||
|
||||
Desconecta a instância mas mantém os dados.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
POST /instance/disconnect
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: TOKEN-DA-INSTANCIA
|
||||
```
|
||||
|
||||
### Body
|
||||
```json
|
||||
{}
|
||||
```
|
||||
|
||||
**Nota**: O body pode ser vazio. A instância é identificada pelo header apikey.
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/disconnect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-da-instancia-vendas" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reconectar Instância
|
||||
|
||||
Reconecta uma instância desconectada.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
POST /instance/reconnect
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: TOKEN-DA-INSTANCIA
|
||||
```
|
||||
|
||||
### Body
|
||||
```json
|
||||
{}
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/reconnect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-da-instancia-vendas" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Logout
|
||||
|
||||
Faz logout completo, removendo a sessão WhatsApp.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
DELETE /instance/logout
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: TOKEN-DA-INSTANCIA
|
||||
```
|
||||
|
||||
### Body
|
||||
```json
|
||||
{}
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**⚠️ Atenção**: Após logout, será necessário escanear QR Code novamente.
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X DELETE http://localhost:4000/instance/logout \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-da-instancia-vendas" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Deletar Instância
|
||||
|
||||
Remove completamente a instância e todos os seus dados.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
DELETE /instance/delete/:instanceId
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa). Esta ação é irreversível!
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X DELETE "http://localhost:4000/instance/delete/vendas" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configurar Proxy
|
||||
|
||||
Configura proxy HTTP para a instância.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
POST /instance/proxy/:instanceId
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
### Body
|
||||
```json
|
||||
{
|
||||
"host": "proxy.exemplo.com",
|
||||
"port": "8080",
|
||||
"username": "usuario",
|
||||
"password": "senha"
|
||||
}
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"host": "proxy.exemplo.com",
|
||||
"port": "8080",
|
||||
"hasAuth": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X POST "http://localhost:4000/instance/proxy/vendas" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY" \
|
||||
-d '{
|
||||
"host": "proxy.exemplo.com",
|
||||
"port": "8080",
|
||||
"username": "usuario",
|
||||
"password": "senha"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Remover Proxy
|
||||
|
||||
Remove configuração de proxy da instância.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
DELETE /instance/proxy/:instanceId
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X DELETE "http://localhost:4000/instance/proxy/vendas" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Forçar Reconexão
|
||||
|
||||
Força reconexão com número específico (útil para resolver problemas).
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
POST /instance/forcereconnect/:instanceId
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
### Body
|
||||
```json
|
||||
{
|
||||
"number": "5511999999999"
|
||||
}
|
||||
```
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X POST "http://localhost:4000/instance/forcereconnect/vendas" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY" \
|
||||
-d '{"number": "5511999999999"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Obter Logs
|
||||
|
||||
Obtém logs da instância.
|
||||
|
||||
### Endpoint
|
||||
```
|
||||
GET /instance/logs/:instanceId?start_date=DATA&end_date=DATA&level=NIVEL&limit=N
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
### Query Parameters
|
||||
| Parâmetro | Tipo | Obrigatório | Descrição |
|
||||
|-----------|------|-------------|-----------|
|
||||
| start_date | string | ❌ Não | Data inicial (YYYY-MM-DD) |
|
||||
| end_date | string | ❌ Não | Data final (YYYY-MM-DD) |
|
||||
| level | string | ❌ Não | Nível do log (INFO, DEBUG, ERROR) |
|
||||
| limit | integer | ❌ Não | Número de registros (padrão: 100) |
|
||||
|
||||
### Resposta Sucesso (200)
|
||||
```json
|
||||
[
|
||||
{
|
||||
"timestamp": "2025-01-15T10:30:00Z",
|
||||
"level": "INFO",
|
||||
"message": "Instance connected successfully",
|
||||
"instanceId": "vendas"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/logs/vendas?start_date=2025-01-01&limit=50" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configurações Avançadas
|
||||
|
||||
### Obter Configurações
|
||||
|
||||
```
|
||||
GET /instance/:instanceId/advanced-settings
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
### Resposta (200)
|
||||
```json
|
||||
{
|
||||
"rejectCall": false,
|
||||
"msgCall": "Não estou disponível para chamadas",
|
||||
"groupsIgnore": true,
|
||||
"alwaysOnline": false,
|
||||
"readMessages": false,
|
||||
"readStatus": false,
|
||||
"syncFullHistory": false
|
||||
}
|
||||
```
|
||||
|
||||
### Atualizar Configurações
|
||||
|
||||
```
|
||||
PUT /instance/:instanceId/advanced-settings
|
||||
```
|
||||
|
||||
### Headers
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-GLOBAL-API-KEY
|
||||
```
|
||||
|
||||
### Body
|
||||
```json
|
||||
{
|
||||
"rejectCall": true,
|
||||
"msgCall": "Por favor, envie mensagem",
|
||||
"groupsIgnore": false,
|
||||
"alwaysOnline": true,
|
||||
"readMessages": true,
|
||||
"readStatus": true,
|
||||
"syncFullHistory": false
|
||||
}
|
||||
```
|
||||
|
||||
### Exemplo cURL
|
||||
```bash
|
||||
curl -X PUT "http://localhost:4000/instance/vendas/advanced-settings" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY" \
|
||||
-d '{
|
||||
"rejectCall": true,
|
||||
"alwaysOnline": true
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxo Completo de Uso
|
||||
|
||||
### 1. Criar Instância (Administrativo)
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-GLOBAL-API-KEY" \
|
||||
-d '{
|
||||
"name": "vendas",
|
||||
"token": "token-vendas-123"
|
||||
}'
|
||||
```
|
||||
|
||||
### 2. Conectar (Usando Token da Instância)
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/connect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-vendas-123" \
|
||||
-d '{
|
||||
"webhookUrl": "https://meu-servidor.com/webhook",
|
||||
"subscribe": ["messages.upsert"]
|
||||
}'
|
||||
```
|
||||
|
||||
### 3. Obter QR Code
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/qr" \
|
||||
-H "apikey: token-vendas-123"
|
||||
```
|
||||
|
||||
### 4. Escanear QR Code com WhatsApp
|
||||
|
||||
Abra o WhatsApp → Aparelhos conectados → Conectar um aparelho → Escanear QR Code
|
||||
|
||||
### 5. Verificar Status
|
||||
```bash
|
||||
curl "http://localhost:4000/instance/status" \
|
||||
-H "apikey: token-vendas-123"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Gestão de Tokens
|
||||
|
||||
**GLOBAL_API_KEY**:
|
||||
- Use para rotas administrativas (criar, deletar, listar instâncias)
|
||||
- Mantenha em segredo (variável de ambiente)
|
||||
- Nunca exponha em código frontend
|
||||
- Rotacione periodicamente
|
||||
|
||||
**Token da Instância**:
|
||||
- Defina ao criar a instância (`token` no body)
|
||||
- Use para operações da instância específica (enviar mensagens, obter status)
|
||||
- Um token único por instância
|
||||
- Use UUIDs: `uuidgen` ou `python3 -c "import uuid; print(uuid.uuid4())"`
|
||||
|
||||
### 2. Nome de Instância
|
||||
- Use nomes descritivos e únicos
|
||||
- Apenas letras, números e hífen
|
||||
- Exemplo: `vendas-empresa`, `suporte-01`
|
||||
|
||||
### 3. Webhooks
|
||||
- Configure webhook para receber eventos em tempo real
|
||||
- Use HTTPS em produção
|
||||
- Valide os eventos recebidos
|
||||
- Retorne status 200 rapidamente
|
||||
|
||||
### 4. Gerenciamento
|
||||
- Monitore o status das instâncias regularmente
|
||||
- Configure reconexão automática se necessário
|
||||
- Mantenha logs para debug
|
||||
- Use configurações avançadas conforme necessário
|
||||
|
||||
---
|
||||
|
||||
## Erros Comuns
|
||||
|
||||
### "not authorized"
|
||||
**Causa**: API key incorreta ou ausente
|
||||
**Solução**:
|
||||
- Rotas administrativas: Use `GLOBAL_API_KEY`
|
||||
- Rotas de operação: Use token da instância
|
||||
|
||||
### "instance not found"
|
||||
**Causa**: Instância não existe ou token incorreto
|
||||
**Solução**: Verifique se a instância foi criada e se está usando o token correto
|
||||
|
||||
### "name is required"
|
||||
**Causa**: Campo obrigatório não enviado
|
||||
**Solução**: Inclua todos os campos obrigatórios no body
|
||||
|
||||
### QR Code Expira
|
||||
**Causa**: QR Code tem validade de ~40 segundos
|
||||
**Solução**: Use `/instance/reconnect` para gerar novo QR
|
||||
|
||||
### "session already logged in"
|
||||
**Causa**: Tentou obter QR Code de instância já conectada
|
||||
**Solução**: Instância já está conectada, não precisa de QR Code
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Mensagens](./api-messages.md) - Enviar diferentes tipos de mensagens
|
||||
- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos
|
||||
- [Sistema de Eventos](../recursos-avancados/events-system.md) - Webhooks e eventos
|
||||
- [Configuração](../fundamentos/configuration.md) - Variáveis de ambiente
|
||||
|
||||
---
|
||||
|
||||
**Dica**: Use o Swagger em `http://localhost:4000/swagger/index.html` para testar os endpoints interativamente!
|
||||
@@ -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": "[email protected]",
|
||||
"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": "[email protected]"}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
### 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": "[email protected]",
|
||||
"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": "[email protected]",
|
||||
"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": "[email protected]",
|
||||
"pushName": "João Silva",
|
||||
"messageId": "3EB034D434158AD2CC0B9A",
|
||||
"chat": "[email protected]",
|
||||
"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": "[email protected]",
|
||||
"pushName": "Maria Santos",
|
||||
"messageId": "3EB0XXXXXXXXXXXXXX",
|
||||
"chat": "[email protected]",
|
||||
"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": "[email protected]",
|
||||
"pushName": "Pedro Oliveira",
|
||||
"messageId": "3EB0XXXXXXXXXXXXXX",
|
||||
"chat": "[email protected]",
|
||||
"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": "[email protected]",
|
||||
"pushName": "Ana Costa",
|
||||
"messageId": "3EB0XXXXXXXXXXXXXX",
|
||||
"chat": "[email protected]",
|
||||
"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: `[email protected]`) |
|
||||
| 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 | ✅ | ✅ | ✅ |
|
||||
@@ -0,0 +1,540 @@
|
||||
# API de Labels
|
||||
|
||||
Documentação completa dos endpoints para organizar chats e mensagens com etiquetas (labels).
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Adicionar Label em Chat](#adicionar-label-em-chat)
|
||||
- [Adicionar Label em Mensagem](#adicionar-label-em-mensagem)
|
||||
- [Editar Label](#editar-label)
|
||||
- [Remover Label de Chat](#remover-label-de-chat)
|
||||
- [Remover Label de Mensagem](#remover-label-de-mensagem)
|
||||
- [Listar Todas as Labels](#listar-todas-as-labels)
|
||||
|
||||
---
|
||||
|
||||
## Adicionar Label em Chat
|
||||
|
||||
Adiciona uma etiqueta (label) a um chat.
|
||||
|
||||
**Endpoint**: `POST /label/chat`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "1"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `jid` | string | ✅ Sim | JID do chat (individual ou grupo) |
|
||||
| `labelId` | string | ✅ Sim | ID da label |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/label/chat \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "1"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Adicionar Label em Mensagem
|
||||
|
||||
Adiciona uma etiqueta a uma mensagem específica.
|
||||
|
||||
**Endpoint**: `POST /label/message`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "2",
|
||||
"messageId": "3EB0C5A277F7F9B6C599"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `jid` | string | ✅ Sim | JID do chat |
|
||||
| `labelId` | string | ✅ Sim | ID da label |
|
||||
| `messageId` | string | ✅ Sim | ID da mensagem |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/label/message \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "2",
|
||||
"messageId": "3EB0C5A277F7F9B6C599"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Editar Label
|
||||
|
||||
Edita nome, cor ou deleta uma label existente.
|
||||
|
||||
**Endpoint**: `POST /label/edit`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"labelId": "1",
|
||||
"name": "Clientes VIP",
|
||||
"color": 0,
|
||||
"deleted": false
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `labelId` | string | ✅ Sim | ID da label a editar |
|
||||
| `name` | string | ✅ Sim | Novo nome da label |
|
||||
| `color` | int | ❌ Não | Código de cor (0-19) |
|
||||
| `deleted` | bool | ❌ Não | Se true, marca label como deletada |
|
||||
|
||||
**Cores Disponíveis** (0-19):
|
||||
|
||||
| Código | Cor |
|
||||
|--------|-----|
|
||||
| 0 | Azul |
|
||||
| 1 | Rosa |
|
||||
| 2 | Roxo |
|
||||
| 3 | Verde |
|
||||
| 4 | Laranja |
|
||||
| 5 | Cinza |
|
||||
| 6 | Vermelho |
|
||||
| 7 | Marrom |
|
||||
| 8 | Verde água |
|
||||
| 9 | Amarelo |
|
||||
| 10-19 | Variações |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
# Renomear label
|
||||
curl -X POST http://localhost:4000/label/edit \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"labelId": "1",
|
||||
"name": "Clientes VIP",
|
||||
"color": 3
|
||||
}'
|
||||
|
||||
# Deletar label
|
||||
curl -X POST http://localhost:4000/label/edit \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"labelId": "1",
|
||||
"name": "Label antiga",
|
||||
"deleted": true
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Remover Label de Chat
|
||||
|
||||
Remove uma etiqueta de um chat.
|
||||
|
||||
**Endpoint**: `POST /unlabel/chat`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "1"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `jid` | string | ✅ Sim | JID do chat |
|
||||
| `labelId` | string | ✅ Sim | ID da label a remover |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/unlabel/chat \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "1"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Remover Label de Mensagem
|
||||
|
||||
Remove uma etiqueta de uma mensagem específica.
|
||||
|
||||
**Endpoint**: `POST /unlabel/message`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "2",
|
||||
"messageId": "3EB0C5A277F7F9B6C599"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `jid` | string | ✅ Sim | JID do chat |
|
||||
| `labelId` | string | ✅ Sim | ID da label |
|
||||
| `messageId` | string | ✅ Sim | ID da mensagem |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/unlabel/message \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "2",
|
||||
"messageId": "3EB0C5A277F7F9B6C599"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Listar Todas as Labels
|
||||
|
||||
Obtém todas as labels da instância.
|
||||
|
||||
**Endpoint**: `GET /label`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"ID": 1,
|
||||
"LabelID": "1",
|
||||
"Name": "Clientes VIP",
|
||||
"Color": 3,
|
||||
"Deleted": false,
|
||||
"PredefinedID": 0,
|
||||
"InstanceID": "minha-instancia"
|
||||
},
|
||||
{
|
||||
"ID": 2,
|
||||
"LabelID": "2",
|
||||
"Name": "Suporte",
|
||||
"Color": 6,
|
||||
"Deleted": false,
|
||||
"PredefinedID": 0,
|
||||
"InstanceID": "minha-instancia"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `ID`: ID interno do banco de dados
|
||||
- `LabelID`: ID da label no WhatsApp
|
||||
- `Name`: Nome da label
|
||||
- `Color`: Código da cor (0-19)
|
||||
- `Deleted`: Se foi deletada
|
||||
- `PredefinedID`: ID de label pré-definida (0 se customizada)
|
||||
- `InstanceID`: ID da instância
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X GET http://localhost:4000/label \
|
||||
-H "apikey: SUA-CHAVE-API"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxos Completos de Uso
|
||||
|
||||
### 1. Sistema de Categorização de Clientes
|
||||
|
||||
```bash
|
||||
# 1. Listar labels existentes
|
||||
LABELS=$(curl -s -X GET http://localhost:4000/label \
|
||||
-H "apikey: SUA-CHAVE-API")
|
||||
|
||||
echo $LABELS | jq '.'
|
||||
|
||||
# 2. Criar nova label (via edição)
|
||||
curl -X POST http://localhost:4000/label/edit \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"labelId": "10",
|
||||
"name": "Lead Qualificado",
|
||||
"color": 3,
|
||||
"deleted": false
|
||||
}'
|
||||
|
||||
# 3. Etiquetar chats de clientes
|
||||
CLIENTES=("[email protected]" "[email protected]")
|
||||
|
||||
for cliente in "\${CLIENTES[@]}"; do
|
||||
curl -X POST http://localhost:4000/label/chat \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d "{
|
||||
"jid": "$cliente",
|
||||
"labelId": "10"
|
||||
}"
|
||||
done
|
||||
```
|
||||
|
||||
### 2. Marcar Mensagens Importantes
|
||||
|
||||
```bash
|
||||
# Etiquetar mensagem específica como "Urgente"
|
||||
curl -X POST http://localhost:4000/label/message \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "[email protected]",
|
||||
"labelId": "5",
|
||||
"messageId": "3EB0C5A277F7F9B6C599"
|
||||
}'
|
||||
```
|
||||
|
||||
### 3. Gerenciar Labels de Suporte
|
||||
|
||||
```bash
|
||||
# Criar labels de status de atendimento
|
||||
LABELS=(
|
||||
"1:Aguardando:0"
|
||||
"2:Em Atendimento:3"
|
||||
"3:Resolvido:4"
|
||||
"4:Cancelado:6"
|
||||
)
|
||||
|
||||
for label_data in "\${LABELS[@]}"; do
|
||||
IFS=':' read -r id name color <<< "$label_data"
|
||||
|
||||
curl -X POST http://localhost:4000/label/edit \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d "{
|
||||
"labelId": "$id",
|
||||
"name": "$name",
|
||||
"color": $color,
|
||||
"deleted": false
|
||||
}"
|
||||
done
|
||||
```
|
||||
|
||||
### 4. Reorganizar Labels
|
||||
|
||||
```bash
|
||||
# Renomear label existente
|
||||
curl -X POST http://localhost:4000/label/edit \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"labelId": "1",
|
||||
"name": "Clientes Premium",
|
||||
"color": 1
|
||||
}'
|
||||
|
||||
# Deletar label obsoleta
|
||||
curl -X POST http://localhost:4000/label/edit \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"labelId": "99",
|
||||
"name": "Label Antiga",
|
||||
"deleted": true
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Casos de Uso Práticos
|
||||
|
||||
### CRM Simples
|
||||
Use labels para categorizar clientes:
|
||||
- **Label 1**: Leads
|
||||
- **Label 2**: Clientes Ativos
|
||||
- **Label 3**: Clientes Inativos
|
||||
- **Label 4**: VIP
|
||||
|
||||
### Suporte ao Cliente
|
||||
Organize tickets por status:
|
||||
- **Label 1**: Aberto
|
||||
- **Label 2**: Em Progresso
|
||||
- **Label 3**: Aguardando Cliente
|
||||
- **Label 4**: Resolvido
|
||||
|
||||
### E-commerce
|
||||
Categorize conversas por estágio:
|
||||
- **Label 1**: Interessado
|
||||
- **Label 2**: Pedido Realizado
|
||||
- **Label 3**: Enviado
|
||||
- **Label 4**: Entregue
|
||||
|
||||
### Equipes
|
||||
Atribua conversas para departamentos:
|
||||
- **Label 1**: Vendas
|
||||
- **Label 2**: Suporte
|
||||
- **Label 3**: Financeiro
|
||||
- **Label 4**: Diretoria
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro Comuns
|
||||
|
||||
| Código | Erro | Solução |
|
||||
|--------|------|---------|
|
||||
| 400 | `jid is required` | Forneça o JID do chat |
|
||||
| 400 | `label id is required` | Forneça o ID da label |
|
||||
| 400 | `message id is required` | Forneça o ID da mensagem |
|
||||
| 400 | `name is required` | Forneça o nome da label (ao editar) |
|
||||
| 500 | `instance not found` | Instância não conectada |
|
||||
| 500 | `error parse community jid` | JID inválido |
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Planeje suas Labels
|
||||
Defina um sistema de categorização antes de começar. Exemplo:
|
||||
- **Label 1**: "Novo Lead" (cor: azul/0)
|
||||
- **Label 2**: "Qualificado" (cor: verde/3)
|
||||
- **Label 3**: "Cliente" (cor: rosa/1)
|
||||
- **Label 4**: "Inativo" (cor: marrom/5)
|
||||
|
||||
### 2. Use Cores Consistentes
|
||||
Mantenha um padrão de cores:
|
||||
- **Verde (3)**: Status positivo
|
||||
- **Vermelho (6)**: Urgente/Problema
|
||||
- **Azul (0)**: Novo/Neutro
|
||||
- **Laranja (4)**: Em progresso
|
||||
|
||||
### 3. Documente IDs
|
||||
Mantenha uma tabela de referência:
|
||||
```
|
||||
ID | Nome | Cor | Descrição
|
||||
---|------|-----|----------
|
||||
1 | VIP | 1 | Clientes premium
|
||||
2 | Lead | 0 | Novos contatos
|
||||
3 | Urg | 6 | Requer atenção
|
||||
```
|
||||
|
||||
### 4. Não Abuse de Labels
|
||||
Limite-se a **10-15 labels** no máximo. Muitas labels dificultam a organização.
|
||||
|
||||
### 5. Limpe Labels Antigas
|
||||
Periodicamente, revise e delete labels não utilizadas:
|
||||
```bash
|
||||
# Listar todas
|
||||
curl -s http://localhost:4000/label -H "apikey: KEY" | jq '.'
|
||||
|
||||
# Deletar obsoletas
|
||||
curl -X POST http://localhost:4000/label/edit \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: KEY" \
|
||||
-d '{"labelId": "99", "name": "Old", "deleted": true}'
|
||||
```
|
||||
|
||||
### 6. Labels em Mensagens
|
||||
Use labels em mensagens apenas para casos especiais:
|
||||
- Mensagens com pedidos
|
||||
- Informações importantes para referência
|
||||
- Reclamações/Problemas
|
||||
|
||||
**Evite**: Etiquetar todas as mensagens (cria poluição visual).
|
||||
|
||||
---
|
||||
|
||||
## Limitações do WhatsApp
|
||||
|
||||
### Limites Conhecidos
|
||||
- **Máximo de labels**: Não documentado oficialmente, mas recomenda-se não ultrapassar 100
|
||||
- **Labels por chat**: Sem limite conhecido
|
||||
- **Labels por mensagem**: 1 label por mensagem
|
||||
|
||||
### Sincronização
|
||||
Labels são sincronizadas entre dispositivos via WhatsApp Multi-Device. Mudanças podem levar alguns segundos para aparecer em outros dispositivos.
|
||||
|
||||
### Visibilidade
|
||||
Labels são **privadas** - apenas você vê suas labels. O destinatário não vê que você etiquetou o chat ou mensagem.
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Chats](./api-chats.md) - Gerenciar conversas (pin, archive, mute)
|
||||
- [API de Mensagens](./api-messages.md) - Enviar e gerenciar mensagens
|
||||
- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos
|
||||
- [Visão Geral da API](./api-overview.md)
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,593 @@
|
||||
# API de Newsletters
|
||||
|
||||
Documentação dos endpoints para gerenciar Newsletters (Canais) do WhatsApp.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Criar Newsletter](#criar-newsletter)
|
||||
- [Listar Newsletters Inscritas](#listar-newsletters-inscritas)
|
||||
- [Informações da Newsletter](#informações-da-newsletter)
|
||||
- [Obter Newsletter por Link](#obter-newsletter-por-link)
|
||||
- [Inscrever em Newsletter](#inscrever-em-newsletter)
|
||||
- [Listar Mensagens](#listar-mensagens)
|
||||
|
||||
---
|
||||
|
||||
## O que são Newsletters?
|
||||
|
||||
**Newsletters** (também chamadas de **Canais**) são um recurso do WhatsApp para transmissão unidirecional de mensagens. Similar a um canal de broadcast.
|
||||
|
||||
**Características**:
|
||||
- **Transmissão unidirecional**: Apenas admins postam, seguidores apenas leem
|
||||
- **Sem limite de seguidores**: Diferente de grupos (1024) ou listas de transmissão (256)
|
||||
- **Privacidade**: Seguidores não veem quem mais segue o canal
|
||||
- **Reações**: Seguidores podem reagir às mensagens
|
||||
- **Conteúdo público ou privado**: Configurável
|
||||
|
||||
---
|
||||
|
||||
## Criar Newsletter
|
||||
|
||||
Cria um novo canal (newsletter) no WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /newsletter/create`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"name": "Notícias da Empresa",
|
||||
"description": "Canal oficial de comunicados e novidades"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `name` | string | ✅ Sim | Nome do canal |
|
||||
| `description` | string | ❌ Não | Descrição do canal |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"ID": "120363XXXXXXXXXX@newsletter",
|
||||
"Name": "Notícias da Empresa",
|
||||
"Description": "Canal oficial de comunicados e novidades",
|
||||
"SubscriberCount": 0,
|
||||
"CreationTime": 1699000000,
|
||||
"Settings": {
|
||||
"ReactionCodes": ["👍", "❤️", "😂", "😮", "😢", "🙏"]
|
||||
},
|
||||
"ThreadMetadata": {
|
||||
"CreationTime": 1699000000
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `ID`: JID único do canal (formato @newsletter)
|
||||
- `Name`: Nome do canal
|
||||
- `Description`: Descrição
|
||||
- `SubscriberCount`: Número de seguidores
|
||||
- `Settings.ReactionCodes`: Reações permitidas
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/newsletter/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"name": "Canal de Ofertas",
|
||||
"description": "Promoções e ofertas exclusivas"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Listar Newsletters Inscritas
|
||||
|
||||
Lista todos os canais que você está seguindo.
|
||||
|
||||
**Endpoint**: `GET /newsletter/list`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"ID": "120363XXXXXXXXXX@newsletter",
|
||||
"Name": "Canal de Ofertas",
|
||||
"Description": "Promoções exclusivas",
|
||||
"SubscriberCount": 1523,
|
||||
"Role": "SUBSCRIBER",
|
||||
"Settings": {
|
||||
"ReactionCodes": ["👍", "❤️", "😂"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"ID": "120363YYYYYYYYYY@newsletter",
|
||||
"Name": "Notícias Tech",
|
||||
"Description": "Últimas novidades em tecnologia",
|
||||
"SubscriberCount": 5420,
|
||||
"Role": "OWNER",
|
||||
"Settings": {
|
||||
"ReactionCodes": ["👍", "❤️"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Roles Possíveis**:
|
||||
- `OWNER`: Você é o criador/dono do canal
|
||||
- `ADMIN`: Você é administrador
|
||||
- `SUBSCRIBER`: Você é apenas seguidor
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X GET http://localhost:4000/newsletter/list \
|
||||
-H "apikey: SUA-CHAVE-API"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Informações da Newsletter
|
||||
|
||||
Obtém informações detalhadas de um canal específico.
|
||||
|
||||
**Endpoint**: `POST /newsletter/info`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"jid": "120363XXXXXXXXXX@newsletter"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `jid` | string (JID) | ✅ Sim | JID do canal |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"ID": "120363XXXXXXXXXX@newsletter",
|
||||
"State": "ACTIVE",
|
||||
"Name": "Canal de Ofertas",
|
||||
"Description": "Promoções exclusivas",
|
||||
"SubscriberCount": 1523,
|
||||
"VerificationState": "VERIFIED",
|
||||
"Role": "SUBSCRIBER",
|
||||
"Settings": {
|
||||
"ReactionCodes": ["👍", "❤️", "😂", "😮", "😢", "🙏"]
|
||||
},
|
||||
"ThreadMetadata": {
|
||||
"CreationTime": 1699000000
|
||||
},
|
||||
"ViewerMetadata": {
|
||||
"MuteState": "UNMUTED",
|
||||
"ViewerRole": "SUBSCRIBER"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos Adicionais**:
|
||||
- `State`: ACTIVE, SUSPENDED, GEOSUSPENDED
|
||||
- `VerificationState`: VERIFIED (canal verificado) ou não
|
||||
- `ViewerMetadata.MuteState`: MUTED ou UNMUTED
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/newsletter/info \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "120363XXXXXXXXXX@newsletter"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Obter Newsletter por Link
|
||||
|
||||
Obtém informações de um canal através do link de convite.
|
||||
|
||||
**Endpoint**: `POST /newsletter/link`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"key": "ABC123XYZ"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `key` | string | ✅ Sim | Código do link de convite |
|
||||
|
||||
**Nota**: O `key` é a parte após `https://whatsapp.com/channel/` no link do canal.
|
||||
|
||||
**Exemplo de Link**:
|
||||
```
|
||||
https://whatsapp.com/channel/ABC123XYZ
|
||||
↑
|
||||
Este é o key
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"ID": "120363XXXXXXXXXX@newsletter",
|
||||
"Name": "Canal Público",
|
||||
"Description": "Nosso canal oficial",
|
||||
"SubscriberCount": 2547,
|
||||
"VerificationState": "VERIFIED",
|
||||
"Settings": {
|
||||
"ReactionCodes": ["👍", "❤️"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/newsletter/link \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"key": "ABC123XYZ"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Inscrever em Newsletter
|
||||
|
||||
Inscreve-se (segue) um canal do WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /newsletter/subscribe`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"jid": "120363XXXXXXXXXX@newsletter"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `jid` | string (JID) | ✅ Sim | JID do canal |
|
||||
|
||||
**Nota**: Para obter o JID, primeiro use `/newsletter/link` com o código do convite.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/newsletter/subscribe \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "120363XXXXXXXXXX@newsletter"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Listar Mensagens
|
||||
|
||||
Obtém mensagens de um canal.
|
||||
|
||||
**Endpoint**: `POST /newsletter/messages`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"jid": "120363XXXXXXXXXX@newsletter",
|
||||
"count": 20,
|
||||
"before_id": 0
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `jid` | string (JID) | ✅ Sim | JID do canal |
|
||||
| `count` | int | ❌ Não | Número de mensagens (padrão: 20, máx: 100) |
|
||||
| `before_id` | int | ❌ Não | ID da mensagem para paginação (0 = mais recentes) |
|
||||
|
||||
**Paginação**: Use o `ServerID` da última mensagem como `before_id` para buscar mensagens mais antigas.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"MessageServerID": 12345,
|
||||
"ViewsCount": 1234,
|
||||
"Message": {
|
||||
"conversation": "Bem-vindos ao nosso canal!"
|
||||
},
|
||||
"ReactionCounts": {
|
||||
"👍": 45,
|
||||
"❤️": 89
|
||||
}
|
||||
},
|
||||
{
|
||||
"MessageServerID": 12344,
|
||||
"ViewsCount": 2156,
|
||||
"Message": {
|
||||
"imageMessage": {
|
||||
"url": "https://...",
|
||||
"caption": "Promoção imperdível!"
|
||||
}
|
||||
},
|
||||
"ReactionCounts": {
|
||||
"👍": 124,
|
||||
"😮": 23
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `MessageServerID`: ID único da mensagem
|
||||
- `ViewsCount`: Número de visualizações
|
||||
- `Message`: Conteúdo da mensagem (texto, imagem, etc)
|
||||
- `ReactionCounts`: Contagem de cada reação
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
# Buscar últimas 20 mensagens
|
||||
curl -X POST http://localhost:4000/newsletter/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "120363XXXXXXXXXX@newsletter",
|
||||
"count": 20
|
||||
}'
|
||||
|
||||
# Buscar 20 mensagens anteriores (paginação)
|
||||
curl -X POST http://localhost:4000/newsletter/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"jid": "120363XXXXXXXXXX@newsletter",
|
||||
"count": 20,
|
||||
"before_id": 12340
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fluxos Completos
|
||||
|
||||
### 1. Criar e Configurar Canal
|
||||
|
||||
```bash
|
||||
# 1. Criar canal
|
||||
NEWSLETTER_JID=$(curl -s -X POST http://localhost:4000/newsletter/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"name": "Ofertas Especiais",
|
||||
"description": "Promoções exclusivas para você"
|
||||
}' | jq -r '.data.ID')
|
||||
|
||||
echo "Canal criado: $NEWSLETTER_JID"
|
||||
|
||||
# 2. Obter informações
|
||||
curl -X POST http://localhost:4000/newsletter/info \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d "{"jid": "$NEWSLETTER_JID"}"
|
||||
```
|
||||
|
||||
### 2. Inscrever-se via Link
|
||||
|
||||
Para se inscrever em um canal usando um link de convite:
|
||||
|
||||
1. **Obter informações do canal**:
|
||||
- Use `POST /newsletter/link` com a `key` do convite
|
||||
- A resposta inclui nome, descrição, contador de seguidores e o JID do canal
|
||||
|
||||
2. **Inscrever-se**:
|
||||
- Use `POST /newsletter/subscribe` com o JID obtido
|
||||
- Se retornar status 200, a inscrição foi bem-sucedida
|
||||
|
||||
### 3. Ler Mensagens Recentes
|
||||
|
||||
Para buscar mensagens publicadas em um canal:
|
||||
|
||||
1. Use `POST /newsletter/messages` com:
|
||||
- `jid`: JID do canal
|
||||
- `count`: Quantas mensagens buscar (ex: 20)
|
||||
- `before_id`: ID da mensagem anterior (use 0 para as mais recentes)
|
||||
|
||||
2. A resposta inclui para cada mensagem:
|
||||
- `MessageServerID`: ID da mensagem
|
||||
- `ViewsCount`: Número de visualizações
|
||||
- `Message`: Conteúdo da mensagem
|
||||
- `ReactionCounts`: Contadores de reações por emoji
|
||||
|
||||
---
|
||||
|
||||
## Casos de Uso
|
||||
|
||||
### 1. Empresa / Marca
|
||||
|
||||
- **Lançamentos**: Anunciar novos produtos
|
||||
- **Promoções**: Divulgar ofertas exclusivas
|
||||
- **Novidades**: Comunicados corporativos
|
||||
- **Blog**: Compartilhar artigos
|
||||
|
||||
### 2. Influencer / Criador de Conteúdo
|
||||
|
||||
- **Conteúdo exclusivo**: Posts para seguidores
|
||||
- **Bastidores**: Fotos e vídeos dos bastidores
|
||||
- **Anúncios**: Novos vídeos, lives, eventos
|
||||
|
||||
### 3. Mídia / Jornalismo
|
||||
|
||||
- **Notícias**: Breaking news
|
||||
- **Análises**: Artigos de opinião
|
||||
- **Entretenimento**: Conteúdo exclusivo
|
||||
|
||||
### 4. Educação
|
||||
|
||||
- **Dicas**: Conteúdo educativo
|
||||
- **Aulas**: Links para aulas ao vivo
|
||||
- **Materiais**: Compartilhar PDFs, links
|
||||
|
||||
---
|
||||
|
||||
## Enviar Mensagens no Canal
|
||||
|
||||
Para enviar mensagens no seu canal, use a **API de Mensagens** normal, passando o JID do canal:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/send/text \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": "120363XXXXXXXXXX@newsletter",
|
||||
"text": "🔥 Promoção Relâmpago! 50% OFF em todos os produtos!"
|
||||
}'
|
||||
```
|
||||
|
||||
Funciona com todos os tipos de mensagem:
|
||||
- Texto
|
||||
- Imagem
|
||||
- Vídeo
|
||||
- Documento
|
||||
- Localização
|
||||
- Poll (enquete)
|
||||
|
||||
---
|
||||
|
||||
## Limitações e Observações
|
||||
|
||||
### Permissões
|
||||
|
||||
- **Criar canal**: Qualquer usuário
|
||||
- **Postar**: Apenas OWNER e ADMIN
|
||||
- **Ver mensagens**: Todos os seguidores
|
||||
- **Reagir**: Todos os seguidores (se permitido)
|
||||
|
||||
### Limitações do WhatsApp
|
||||
|
||||
| Aspecto | Limitação |
|
||||
|---------|-----------|
|
||||
| Número de seguidores | Ilimitado |
|
||||
| Mensagens por dia | Não documentado |
|
||||
| Tamanho da descrição | ~255 caracteres |
|
||||
| Reações | Até 7 emojis configuráveis |
|
||||
|
||||
### Diferenças: Newsletter vs Grupo vs Lista
|
||||
|
||||
| Aspecto | Newsletter | Grupo | Lista de Transmissão |
|
||||
|---------|-----------|-------|---------------------|
|
||||
| Seguidores | Ilimitado | 1024 | 256 |
|
||||
| Comunicação | Unidirecional | Bidirecional | Unidirecional |
|
||||
| Privacidade | Anônimo | Todos veem todos | Anônimo |
|
||||
| Reações | Sim | Sim | Não |
|
||||
| Respostas | Não | Sim | Sim (privado) |
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro Comuns
|
||||
|
||||
| Código | Erro | Solução |
|
||||
|--------|------|---------|
|
||||
| 400 | `name is required` | Forneça o nome do canal |
|
||||
| 400 | `jid is required` | Forneça o JID do canal |
|
||||
| 400 | `key is required` | Forneça o código do link |
|
||||
| 500 | `instance not found` | Instância não conectada |
|
||||
| 500 | `error create newsletter` | Falha ao criar (tente nome diferente) |
|
||||
| 500 | `error list newsletter` | Falha ao buscar canais |
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Nome e Descrição Claros
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Tech News Daily",
|
||||
"description": "Últimas notícias de tecnologia todos os dias às 9h"
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Consistência de Postagens
|
||||
|
||||
- Defina frequência (diária, semanal)
|
||||
- Mantenha horários regulares
|
||||
- Avise se houver pausas
|
||||
|
||||
### 3. Conteúdo de Qualidade
|
||||
|
||||
- Textos concisos
|
||||
- Imagens de alta qualidade
|
||||
- Informações relevantes
|
||||
- Evite spam
|
||||
|
||||
### 4. Engajamento
|
||||
|
||||
- Use enquetes
|
||||
- Permita reações relevantes
|
||||
- Responda dúvidas (em outros canais)
|
||||
|
||||
### 5. Divulgação
|
||||
|
||||
Compartilhe o link do canal:
|
||||
```
|
||||
https://whatsapp.com/channel/ABC123XYZ
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Mensagens](./api-messages.md) - Enviar conteúdo no canal
|
||||
- [API de Grupos](./api-groups.md) - Comparar com grupos
|
||||
- [API de Comunidades](./api-community.md) - Organizar múltiplos canais
|
||||
- [Visão Geral da API](./api-overview.md)
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,342 @@
|
||||
# Visão Geral da API
|
||||
|
||||
Guia completo para usar a API REST do Evolution GO.
|
||||
|
||||
## Base URL
|
||||
|
||||
```
|
||||
http://localhost:4000
|
||||
```
|
||||
|
||||
## Autenticação
|
||||
|
||||
Todas as requisições precisam do header `apikey`:
|
||||
|
||||
```bash
|
||||
curl -H "apikey: SUA-CHAVE-API" http://localhost:4000/endpoint
|
||||
```
|
||||
|
||||
**Tipos de API Key**:
|
||||
- **GLOBAL_API_KEY**: Configurada na variável de ambiente, usada para operações administrativas (criar/deletar instâncias)
|
||||
- **Token da Instância**: Definido ao criar a instância, usado para operações da instância (enviar mensagens, conectar, etc)
|
||||
|
||||
## Formato das Requisições
|
||||
|
||||
### Content-Type
|
||||
|
||||
```
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
### Exemplo de Requisição
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: GLOBAL_API_KEY" \
|
||||
-d '{
|
||||
"name": "teste",
|
||||
"token": "token-teste-123"
|
||||
}'
|
||||
```
|
||||
|
||||
## Formato das Respostas
|
||||
|
||||
### Sucesso (HTTP 200/201)
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"id": "uuid-abc-123",
|
||||
"name": "teste",
|
||||
"token": "token-teste-123",
|
||||
"connected": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Erro (HTTP 4xx/5xx)
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Instance not found",
|
||||
"message": "A instância especificada não existe"
|
||||
}
|
||||
```
|
||||
|
||||
## Códigos de Status HTTP
|
||||
|
||||
| Código | Significado |
|
||||
|--------|-------------|
|
||||
| 200 | OK - Requisição bem-sucedida |
|
||||
| 201 | Created - Recurso criado com sucesso |
|
||||
| 400 | Bad Request - Dados inválidos |
|
||||
| 401 | Unauthorized - API key inválida |
|
||||
| 404 | Not Found - Recurso não encontrado |
|
||||
| 500 | Internal Server Error - Erro no servidor |
|
||||
|
||||
## Estrutura da API
|
||||
|
||||
A API está organizada em módulos:
|
||||
|
||||
### Instâncias
|
||||
Gerenciar conexões WhatsApp
|
||||
- `POST /instance/create` - Criar instância
|
||||
- `POST /instance/connect` - Conectar via QR Code
|
||||
- `GET /instance/status` - Ver status
|
||||
- `DELETE /instance/delete/:id` - Deletar
|
||||
|
||||
### Mensagens
|
||||
Enviar e gerenciar mensagens
|
||||
- `POST /send/text` - Texto simples
|
||||
- `POST /send/link` - Link com preview
|
||||
- `POST /send/media` - Mídia (imagem, vídeo, áudio, documento)
|
||||
- `POST /send/sticker` - Sticker/figurinha
|
||||
- `POST /send/location` - Localização
|
||||
- `POST /send/contact` - Contato
|
||||
- `POST /send/poll` - Enquete
|
||||
- `POST /send/button` - Botões interativos
|
||||
- `POST /send/list` - Lista de opções
|
||||
|
||||
### Gerenciar Mensagens
|
||||
Interagir com mensagens enviadas/recebidas
|
||||
- `POST /message/react` - Reagir a mensagem
|
||||
- `POST /message/markread` - Marcar como lida
|
||||
- `POST /message/delete` - Deletar para todos
|
||||
- `POST /message/edit` - Editar mensagem
|
||||
- `POST /message/presence` - Definir presença (digitando, gravando)
|
||||
- `POST /message/downloadmedia` - Baixar mídia
|
||||
- `POST /message/status` - Ver status de entrega
|
||||
|
||||
### Usuários
|
||||
Gerenciar perfil e contatos
|
||||
- `POST /user/info` - Informações do usuário
|
||||
- `POST /user/check` - Verificar se número existe
|
||||
- `POST /user/avatar` - Obter avatar
|
||||
- `GET /user/contacts` - Listar contatos
|
||||
- `GET /user/privacy` - Ver configurações de privacidade
|
||||
- `POST /user/privacy` - Configurar privacidade
|
||||
- `POST /user/block` - Bloquear contato
|
||||
- `POST /user/unblock` - Desbloquear contato
|
||||
- `GET /user/blocklist` - Ver lista de bloqueados
|
||||
- `POST /user/profilePicture` - Alterar foto de perfil
|
||||
- `POST /user/profileName` - Alterar nome
|
||||
- `POST /user/profileStatus` - Alterar status/recado
|
||||
|
||||
### Grupos
|
||||
Gerenciar grupos WhatsApp
|
||||
- `GET /group/list` - Listar todos os grupos
|
||||
- `POST /group/create` - Criar grupo
|
||||
- `POST /group/info` - Informações do grupo
|
||||
- `POST /group/invitelink` - Obter link de convite
|
||||
- `POST /group/photo` - Alterar foto do grupo
|
||||
- `POST /group/name` - Alterar nome
|
||||
- `POST /group/description` - Alterar descrição
|
||||
- `POST /group/participant` - Gerenciar participantes (adicionar/remover/promover)
|
||||
- `POST /group/join` - Entrar via link
|
||||
- `POST /group/leave` - Sair do grupo
|
||||
|
||||
### Chats
|
||||
Gerenciar conversas
|
||||
- `POST /chat/pin` - Fixar conversa
|
||||
- `POST /chat/unpin` - Desfixar conversa
|
||||
- `POST /chat/archive` - Arquivar conversa
|
||||
- `POST /chat/unarchive` - Desarquivar
|
||||
- `POST /chat/mute` - Silenciar notificações
|
||||
- `POST /chat/unmute` - Reativar notificações
|
||||
- `POST /chat/history-sync` - Solicitar sincronização de histórico
|
||||
|
||||
### Labels (Etiquetas)
|
||||
Organizar conversas com etiquetas
|
||||
- `POST /label/chat` - Adicionar etiqueta a chat
|
||||
- `POST /label/message` - Adicionar etiqueta a mensagem
|
||||
- `POST /label/edit` - Criar/editar etiqueta
|
||||
- `GET /label/list` - Listar todas as etiquetas
|
||||
- `POST /unlabel/chat` - Remover etiqueta de chat
|
||||
- `POST /unlabel/message` - Remover etiqueta de mensagem
|
||||
|
||||
### Chamadas
|
||||
Gerenciar chamadas
|
||||
- `POST /call/reject` - Rejeitar chamada
|
||||
|
||||
### Newsletter (Canais)
|
||||
Gerenciar newsletters/canais
|
||||
- `POST /newsletter/create` - Criar newsletter
|
||||
- `GET /newsletter/list` - Listar newsletters
|
||||
- `POST /newsletter/info` - Informações da newsletter
|
||||
- `POST /newsletter/link` - Obter link de convite
|
||||
- `POST /newsletter/subscribe` - Inscrever-se
|
||||
- `POST /newsletter/messages` - Ver mensagens
|
||||
|
||||
### Community (Comunidades)
|
||||
Gerenciar comunidades
|
||||
- `POST /community/create` - Criar comunidade
|
||||
- `POST /community/add` - Adicionar grupo à comunidade
|
||||
- `POST /community/remove` - Remover grupo da comunidade
|
||||
|
||||
## Parâmetros Comuns
|
||||
|
||||
### number
|
||||
Número do WhatsApp (DDI + DDD + Número)
|
||||
- Formato: Apenas dígitos
|
||||
- Exemplo: `"5511999999999"` (Brasil)
|
||||
- Exemplo: `"1234567890"` (EUA)
|
||||
|
||||
## Formato de Números
|
||||
|
||||
### Número Individual
|
||||
```json
|
||||
{
|
||||
"number": "5511999999999"
|
||||
}
|
||||
```
|
||||
|
||||
### Grupo
|
||||
```json
|
||||
{
|
||||
"number": "120363XXXXXXXXXX@g.us"
|
||||
}
|
||||
```
|
||||
|
||||
O Evolution GO formata automaticamente números quando necessário.
|
||||
|
||||
## Paginação
|
||||
|
||||
Endpoints que retornam listas suportam paginação:
|
||||
|
||||
```bash
|
||||
GET /endpoint?page=1&limit=50
|
||||
```
|
||||
|
||||
## WebSocket
|
||||
|
||||
Para receber eventos em tempo real via WebSocket:
|
||||
|
||||
```
|
||||
ws://localhost:4000/ws?token=SUA-CHAVE-API&instanceId=minha-instancia
|
||||
```
|
||||
|
||||
## Webhooks
|
||||
|
||||
Configure webhooks via variável de ambiente:
|
||||
|
||||
```env
|
||||
WEBHOOK_URL=https://seu-servidor.com/webhook
|
||||
```
|
||||
|
||||
Eventos serão enviados via POST para a URL configurada.
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
Atualmente não há rate limiting configurado, mas é recomendado:
|
||||
- Máximo 50 requisições por segundo por instância
|
||||
- Aguarde resposta antes de enviar próxima mensagem
|
||||
|
||||
## Swagger/OpenAPI
|
||||
|
||||
Documentação interativa disponível em:
|
||||
|
||||
```
|
||||
http://localhost:4000/swagger/index.html
|
||||
```
|
||||
|
||||
Recursos do Swagger:
|
||||
- Testar endpoints diretamente
|
||||
- Ver todos os parâmetros
|
||||
- Exemplos de request/response
|
||||
- Autenticação integrada
|
||||
|
||||
## Exemplos Práticos
|
||||
|
||||
### Criar e Conectar Instância
|
||||
|
||||
```bash
|
||||
# 1. Criar instância (usa GLOBAL_API_KEY)
|
||||
curl -X POST http://localhost:4000/instance/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: GLOBAL_API_KEY" \
|
||||
-d '{
|
||||
"name": "vendas",
|
||||
"token": "token-vendas-123"
|
||||
}'
|
||||
|
||||
# 2. Conectar (usa token da instância)
|
||||
curl -X POST http://localhost:4000/instance/connect \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-vendas-123" \
|
||||
-d '{
|
||||
"webhookUrl": "https://meu-servidor.com/webhook"
|
||||
}'
|
||||
|
||||
# 3. Ver QR Code (usa token da instância)
|
||||
curl -X GET http://localhost:4000/instance/qr \
|
||||
-H "apikey: token-vendas-123"
|
||||
```
|
||||
|
||||
### Enviar Mensagem com Mídia
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/send/media \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-vendas-123" \
|
||||
-d '{
|
||||
"number": "5511999999999",
|
||||
"url": "https://exemplo.com/produto.jpg",
|
||||
"type": "image",
|
||||
"caption": "Confira nosso produto!"
|
||||
}'
|
||||
```
|
||||
|
||||
### Criar Grupo
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/group/create \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: token-vendas-123" \
|
||||
-d '{
|
||||
"name": "Equipe de Vendas",
|
||||
"participants": ["5511999999999", "5511888888888"]
|
||||
}'
|
||||
```
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Validar Números
|
||||
Use `/user/check` para verificar se número existe no WhatsApp
|
||||
|
||||
### 2. Gerenciar Erros
|
||||
Sempre trate erros HTTP 4xx e 5xx
|
||||
|
||||
### 3. Usar Webhooks
|
||||
Para receber mensagens, configure webhooks em vez de polling
|
||||
|
||||
### 4. Múltiplas Instâncias
|
||||
Use uma instância por número WhatsApp
|
||||
|
||||
### 5. Logs
|
||||
Configure logs adequadamente para debug
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Erro 401 Unauthorized
|
||||
Verifique se a `apikey` está correta
|
||||
|
||||
### Erro 404 Instance not found
|
||||
Certifique-se de que criou a instância primeiro
|
||||
|
||||
### Mensagem não enviada
|
||||
1. Verifique status da conexão
|
||||
2. Confirme formato do número
|
||||
3. Verifique se número existe no WhatsApp
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Instâncias](./api-instances.md) - Gerenciar instâncias
|
||||
- [API de Mensagens](./api-messages.md) - Enviar mensagens
|
||||
- [API de Grupos](./api-groups.md) - Gerenciar grupos
|
||||
- [Sistema de Eventos](../recursos-avancados/events-system.md) - Webhooks e eventos
|
||||
|
||||
---
|
||||
|
||||
**Dica**: Use o Swagger para explorar todos os endpoints disponíveis!
|
||||
@@ -0,0 +1,760 @@
|
||||
# API de Usuários
|
||||
|
||||
Documentação completa dos endpoints para gerenciar perfil, contatos e privacidade.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Informações do Usuário](#informações-do-usuário)
|
||||
- [Verificar Usuário no WhatsApp](#verificar-usuário-no-whatsapp)
|
||||
- [Avatar do Usuário](#avatar-do-usuário)
|
||||
- [Listar Contatos](#listar-contatos)
|
||||
- [Privacidade](#privacidade)
|
||||
- [Consultar Privacidade](#consultar-privacidade)
|
||||
- [Configurar Privacidade](#configurar-privacidade)
|
||||
- [Bloqueio de Contatos](#bloqueio-de-contatos)
|
||||
- [Bloquear Contato](#bloquear-contato)
|
||||
- [Desbloquear Contato](#desbloquear-contato)
|
||||
- [Listar Bloqueados](#listar-bloqueados)
|
||||
- [Perfil](#perfil)
|
||||
- [Alterar Foto de Perfil](#alterar-foto-de-perfil)
|
||||
- [Alterar Nome](#alterar-nome)
|
||||
- [Alterar Status/Recado](#alterar-statusrecado)
|
||||
|
||||
---
|
||||
|
||||
## Informações do Usuário
|
||||
|
||||
Obtém informações detalhadas de um ou mais usuários WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /user/info`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
Content-Type: application/json
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"number": ["5511999999999", "5511888888888"]
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `number` | array | ✅ Sim | Array de números a consultar |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"Users": {
|
||||
"5511999999999@s.whatsapp.net": {
|
||||
"VerifiedName": {
|
||||
"Certificate": {...},
|
||||
"Details": {
|
||||
"Serial": 123,
|
||||
"Issuer": "WhatsApp",
|
||||
"VerifiedName": "Empresa Verificada LTDA"
|
||||
}
|
||||
},
|
||||
"Status": "Olá! Estou usando WhatsApp.",
|
||||
"PictureID": "abc123",
|
||||
"Devices": ["5511999999999.0:1@s.whatsapp.net"],
|
||||
"LID": "lid_string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `VerifiedName`: Nome verificado (empresas) ou null
|
||||
- `Status`: Recado/status do usuário
|
||||
- `PictureID`: ID da foto de perfil
|
||||
- `Devices`: Lista de dispositivos conectados
|
||||
- `LID`: Local ID (se disponível)
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/info \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": ["5511999999999"]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verificar Usuário no WhatsApp
|
||||
|
||||
Verifica se um número existe no WhatsApp e retorna o JID correto para mensagens.
|
||||
|
||||
**Endpoint**: `POST /user/check`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"number": ["5511999999999", "11999999999", "+55 11 99999-9999"],
|
||||
"formatJid": false
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `number` | array | ✅ Sim | Array de números em qualquer formato |
|
||||
| `formatJid` | bool | ❌ Não | Formatar número (padrão: false) |
|
||||
|
||||
**Nota Importante**: Por padrão, `formatJid=false` para verificação. O sistema tenta automaticamente ambos os formatos se o primeiro falhar.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"Users": [
|
||||
{
|
||||
"Query": "5511999999999",
|
||||
"IsInWhatsapp": true,
|
||||
"JID": "5511999999999@s.whatsapp.net",
|
||||
"RemoteJID": "5511999999999@s.whatsapp.net",
|
||||
"LID": "lid_string",
|
||||
"VerifiedName": "Empresa LTDA"
|
||||
},
|
||||
{
|
||||
"Query": "5511888888888",
|
||||
"IsInWhatsapp": false,
|
||||
"JID": "",
|
||||
"RemoteJID": "5511888888888",
|
||||
"LID": null,
|
||||
"VerifiedName": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `Query`: Número original consultado
|
||||
- `IsInWhatsapp`: Se existe no WhatsApp
|
||||
- `JID`: JID do usuário (vazio se não existe)
|
||||
- `RemoteJID`: JID recomendado para envio de mensagens
|
||||
- `LID`: Local ID
|
||||
- `VerifiedName`: Nome verificado (empresas)
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/check \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": ["5511999999999", "11888888888"]
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Avatar do Usuário
|
||||
|
||||
Obtém a URL da foto de perfil de um usuário.
|
||||
|
||||
**Endpoint**: `POST /user/avatar`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"number": "5511999999999",
|
||||
"preview": false
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `number` | string | ✅ Sim | Número do usuário |
|
||||
| `preview` | bool | ❌ Não | Se true, retorna preview (menor resolução) |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"URL": "https://pps.whatsapp.net/v/...",
|
||||
"ID": "abc123",
|
||||
"Type": "image",
|
||||
"DirectPath": "/v/..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Resposta de Erro (500)**:
|
||||
```json
|
||||
{
|
||||
"error": "no profile picture found"
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/avatar \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": "5511999999999",
|
||||
"preview": true
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Listar Contatos
|
||||
|
||||
Obtém todos os contatos salvos na conta WhatsApp.
|
||||
|
||||
**Endpoint**: `GET /user/contacts`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"Jid": "5511999999999@s.whatsapp.net",
|
||||
"Found": true,
|
||||
"FirstName": "João",
|
||||
"FullName": "João Silva",
|
||||
"PushName": "João",
|
||||
"BusinessName": ""
|
||||
},
|
||||
{
|
||||
"Jid": "5511888888888@s.whatsapp.net",
|
||||
"Found": true,
|
||||
"FirstName": "Maria",
|
||||
"FullName": "Maria Santos",
|
||||
"PushName": "Maria",
|
||||
"BusinessName": "Loja da Maria"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Campos da Resposta**:
|
||||
- `Jid`: JID do contato
|
||||
- `Found`: Se foi encontrado no WhatsApp
|
||||
- `FirstName`: Primeiro nome
|
||||
- `FullName`: Nome completo
|
||||
- `PushName`: Nome exibido no WhatsApp
|
||||
- `BusinessName`: Nome da empresa (se for conta comercial)
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X GET http://localhost:4000/user/contacts \
|
||||
-H "apikey: SUA-CHAVE-API"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Privacidade
|
||||
|
||||
### Consultar Privacidade
|
||||
|
||||
Obtém as configurações atuais de privacidade da conta.
|
||||
|
||||
**Endpoint**: `GET /user/privacy`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"GroupAdd": "all",
|
||||
"LastSeen": "contacts",
|
||||
"Status": "contacts",
|
||||
"Profile": "all",
|
||||
"ReadReceipts": "all",
|
||||
"CallAdd": "all",
|
||||
"Online": "all"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Valores Possíveis**:
|
||||
- `all` - Todos
|
||||
- `contacts` - Apenas contatos
|
||||
- `contact_blacklist` - Meus contatos exceto...
|
||||
- `none` - Ninguém
|
||||
- `match_last_seen` - Mesmo de "Visto por último"
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X GET http://localhost:4000/user/privacy \
|
||||
-H "apikey: SUA-CHAVE-API"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Configurar Privacidade
|
||||
|
||||
Define as configurações de privacidade da conta.
|
||||
|
||||
**Endpoint**: `POST /user/privacy`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"groupAdd": "contacts",
|
||||
"lastSeen": "contacts",
|
||||
"status": "contacts",
|
||||
"profile": "all",
|
||||
"readReceipts": "all",
|
||||
"callAdd": "all",
|
||||
"online": "all"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `groupAdd` | string | ✅ Sim | Quem pode me adicionar em grupos |
|
||||
| `lastSeen` | string | ✅ Sim | Quem vê meu "visto por último" |
|
||||
| `status` | string | ✅ Sim | Quem vê meu recado/status |
|
||||
| `profile` | string | ✅ Sim | Quem vê minha foto de perfil |
|
||||
| `readReceipts` | string | ✅ Sim | Confirmações de leitura |
|
||||
| `callAdd` | string | ✅ Sim | Quem pode me ligar |
|
||||
| `online` | string | ✅ Sim | Quem vê quando estou online |
|
||||
|
||||
**Valores Permitidos**: `all`, `contacts`, `contact_blacklist`, `none`, `match_last_seen`
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"GroupAdd": "contacts",
|
||||
"LastSeen": "contacts",
|
||||
"Status": "contacts",
|
||||
"Profile": "all",
|
||||
"ReadReceipts": "all",
|
||||
"CallAdd": "all",
|
||||
"Online": "all"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/privacy \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupAdd": "contacts",
|
||||
"lastSeen": "contacts",
|
||||
"status": "contacts",
|
||||
"profile": "all",
|
||||
"readReceipts": "all",
|
||||
"callAdd": "all",
|
||||
"online": "all"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Bloqueio de Contatos
|
||||
|
||||
### Bloquear Contato
|
||||
|
||||
Bloqueia um contato no WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /user/block`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"number": "5511999999999"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `number` | string | ✅ Sim | Número do contato a bloquear |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"AddressingMode": "lid",
|
||||
"DHash": "abc123",
|
||||
"Items": [
|
||||
{
|
||||
"LID": "123456789012345@lid",
|
||||
"PN": "5511999999999@s.whatsapp.net",
|
||||
"Active": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/block \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": "5511999999999"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Desbloquear Contato
|
||||
|
||||
Desbloqueia um contato previamente bloqueado.
|
||||
|
||||
**Endpoint**: `POST /user/unblock`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"number": "5511999999999"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `number` | string | ✅ Sim | Número do contato a desbloquear |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"AddressingMode": "lid",
|
||||
"DHash": "abc123",
|
||||
"Items": [
|
||||
{
|
||||
"LID": "123456789012345@lid",
|
||||
"PN": "5511999999999@s.whatsapp.net",
|
||||
"Active": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/unblock \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": "5511999999999"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Listar Bloqueados
|
||||
|
||||
Obtém a lista de todos os contatos bloqueados.
|
||||
|
||||
**Endpoint**: `GET /user/blocklist`
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"AddressingMode": "lid",
|
||||
"DHash": "abc123",
|
||||
"Items": [
|
||||
{
|
||||
"LID": "123456789012345@lid",
|
||||
"PN": "5511999999999@s.whatsapp.net",
|
||||
"Active": true
|
||||
},
|
||||
{
|
||||
"LID": "987654321098765@lid",
|
||||
"PN": "5511888888888@s.whatsapp.net",
|
||||
"Active": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X GET http://localhost:4000/user/blocklist \
|
||||
-H "apikey: SUA-CHAVE-API"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Perfil
|
||||
|
||||
### Alterar Foto de Perfil
|
||||
|
||||
Define a foto de perfil da conta WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /user/profilePicture`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"image": "https://exemplo.com/foto.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `image` | string | ✅ Sim | URL da imagem |
|
||||
|
||||
**Nota**: A imagem deve ser acessível via HTTP/HTTPS. Formatos aceitos: JPG, PNG.
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"image": "https://exemplo.com/foto.jpg"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/profilePicture \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"image": "https://exemplo.com/minha-foto.jpg"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Alterar Nome
|
||||
|
||||
Define o nome de exibição da conta WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /user/profileName`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"name": "João Silva"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `name` | string | ✅ Sim | Novo nome de exibição |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"name": "João Silva"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/profileName \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"name": "Meu Novo Nome"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Alterar Status/Recado
|
||||
|
||||
Define o recado (status) da conta WhatsApp.
|
||||
|
||||
**Endpoint**: `POST /user/profileStatus`
|
||||
|
||||
**Body**:
|
||||
```json
|
||||
{
|
||||
"status": "Disponível para atendimento 24h!"
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|-------|------|-------------|-----------|
|
||||
| `status` | string | ✅ Sim | Novo recado/status |
|
||||
|
||||
**Resposta de Sucesso (200)**:
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"status": "Disponível para atendimento 24h!"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Exemplo cURL**:
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/profileStatus \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"status": "Olá! Como posso ajudar?"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Casos de Uso Comuns
|
||||
|
||||
### Validar Números Antes de Enviar
|
||||
|
||||
Sempre verifique se o número existe antes de tentar enviar mensagem:
|
||||
|
||||
```bash
|
||||
# 1. Verificar número
|
||||
curl -X POST http://localhost:4000/user/check \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": ["5511999999999"]
|
||||
}'
|
||||
|
||||
# 2. Se IsInWhatsapp=true, use RemoteJID para enviar
|
||||
curl -X POST http://localhost:4000/send/text \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"number": "5511999999999@s.whatsapp.net",
|
||||
"text": "Olá!",
|
||||
"formatJid": false
|
||||
}'
|
||||
```
|
||||
|
||||
### Configurar Privacidade Máxima
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/user/privacy \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{
|
||||
"groupAdd": "contacts",
|
||||
"lastSeen": "none",
|
||||
"status": "contacts",
|
||||
"profile": "contacts",
|
||||
"readReceipts": "all",
|
||||
"callAdd": "contacts",
|
||||
"online": "none"
|
||||
}'
|
||||
```
|
||||
|
||||
### Personalizar Perfil Completo
|
||||
|
||||
```bash
|
||||
# 1. Foto de perfil
|
||||
curl -X POST http://localhost:4000/user/profilePicture \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"image": "https://exemplo.com/logo.jpg"}'
|
||||
|
||||
# 2. Nome
|
||||
curl -X POST http://localhost:4000/user/profileName \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"name": "Empresa LTDA"}'
|
||||
|
||||
# 3. Status
|
||||
curl -X POST http://localhost:4000/user/profileStatus \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "apikey: SUA-CHAVE-API" \
|
||||
-d '{"status": "Atendimento 24h - (11) 99999-9999"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro Comuns
|
||||
|
||||
| Código | Erro | Solução |
|
||||
|--------|------|---------|
|
||||
| 400 | `phone number is required` | Forneça o campo `number` |
|
||||
| 400 | `image is required` | Forneça uma URL de imagem válida |
|
||||
| 500 | `instance not found` | Instância não conectada |
|
||||
| 500 | `no profile picture found` | Usuário não tem foto de perfil |
|
||||
| 500 | `invalid phone number` | Formato de número inválido |
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Cache de Verificações
|
||||
Evite verificar o mesmo número múltiplas vezes. Implemente um sistema de cache na sua aplicação:
|
||||
- Armazene o resultado da verificação por algumas horas
|
||||
- Antes de chamar a API, verifique se já tem o resultado em cache
|
||||
- Isso reduz requisições desnecessárias e melhora a performance
|
||||
|
||||
### 2. Privacidade Responsável
|
||||
Configure privacidade adequada para contas comerciais:
|
||||
- `readReceipts: all` - Envie confirmações de leitura
|
||||
- `online: contacts` - Evite mostrar online para todos
|
||||
- `groupAdd: contacts` - Evite spam de grupos
|
||||
|
||||
### 3. Validação de Imagens
|
||||
Ao alterar foto de perfil, certifique-se que a imagem:
|
||||
- Está acessível publicamente (HTTP/HTTPS)
|
||||
- É JPG ou PNG
|
||||
- Tem tamanho adequado (recomendado: 640x640px)
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [API de Mensagens](./api-messages.md) - Enviar e gerenciar mensagens
|
||||
- [API de Grupos](./api-groups.md) - Gerenciar grupos WhatsApp
|
||||
- [API de Chats](./api-chats.md) - Gerenciar conversas
|
||||
- [Visão Geral da API](./api-overview.md)
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,412 @@
|
||||
# Pareamento por Chave de Acesso (Passkey / WebAuthn)
|
||||
|
||||
Guia completo de como conectar uma instância WhatsApp no Evolution GO quando a
|
||||
conta exige uma **chave de acesso (passkey)** — a nova etapa de segurança que a
|
||||
Meta passou a exigir em algumas contas ao vincular um novo dispositivo.
|
||||
|
||||
---
|
||||
|
||||
## 1. Por que o passkey existe
|
||||
|
||||
O fluxo clássico multi-dispositivo era: mostra o QR rotativo → o celular escaneia
|
||||
→ pareado. A Meta está lançando o **linking travado por passkey** (o protocolo
|
||||
que os clients oficiais chamam de **Shortcake** no lado web / **CRSC** no lado
|
||||
telefone): para **algumas contas**, o servidor exige uma **assertion de passkey
|
||||
WebAuthn** antes de vincular um novo dispositivo.
|
||||
|
||||
**Quem é afetado:** é uma decisão **100% server-side, por conta** (um bucket A/B
|
||||
do servidor + a conta ter um passkey + sinal de risco). O usuário não escolhe, e
|
||||
o cliente não consegue disparar nem desviar. Você não controla se sua conta cai
|
||||
nesse fluxo.
|
||||
|
||||
**Importante — nem sempre há QR.** Numa conta travada, o servidor responde ao
|
||||
pareamento com `retry-with-method: shortcake-with-passkeys` e frequentemente
|
||||
**omite o `qr-code`** — ou seja, **pode não existir QR para escanear**. O prólogo
|
||||
de passkey também pode vir logo após um **código de pareamento**. Por isso o
|
||||
Evolution GO trata o pedido de passkey de forma independente do QR.
|
||||
|
||||
O ponto difícil: a chamada `navigator.credentials.get()` (que dispara a
|
||||
biometria/PIN) **só funciona numa página cujo domínio bata com o `rpId` da
|
||||
credencial** (`whatsapp.com`) — ou seja, precisa rodar dentro de uma aba real
|
||||
`web.whatsapp.com`. **Não existe bypass headless** (confirmado empiricamente por
|
||||
pesquisa de engenharia reversa independente — ver §10): o servidor valida a
|
||||
assinatura contra a chave pública **registrada** da conta, com challenge fresco;
|
||||
uma assertion forjada é rejeitada. A cerimônia exige o autenticador real do dono
|
||||
da conta (Touch ID / Windows Hello / passkey sincronizada).
|
||||
|
||||
> **É web-only.** Um companion android (`platform_type = 10`) é rejeitado pelo
|
||||
> servidor com `463 account_reachout_restricted`. A cerimônia Shortcake só roda
|
||||
> num companion web.
|
||||
|
||||
**Solução do Evolution GO:** uma pequena extensão de navegador
|
||||
(`tools/passkey-helper`) roda **apenas** em `web.whatsapp.com`, executa a
|
||||
cerimônia WebAuthn ali (onde o `rpId` é aceito), e devolve a assinatura para a
|
||||
API do Evolution GO, que a repassa ao WhatsApp via whatsmeow.
|
||||
|
||||
> A extensão é o único componente que roda no domínio `web.whatsapp.com`. Ela
|
||||
> não interage com o login do WhatsApp Web e não coleta dados — serve só como
|
||||
> "palco" com o origin correto para a biometria.
|
||||
|
||||
---
|
||||
|
||||
## 2. Arquitetura
|
||||
|
||||
```
|
||||
┌──────────────────────────── Evolution GO (backend) ────────────────────────────┐
|
||||
│ │
|
||||
│ whatsmeow client ──emite──> events.PairPasskeyRequest / Confirmation / Error │
|
||||
│ │ │ │
|
||||
│ │ ▼ │
|
||||
│ │ ceremony.Store (token efêmero + estágio, mutex) │
|
||||
│ │ ▲ │
|
||||
│ ▼ │ │
|
||||
│ SendPasskeyResponse ◄──── API pública /passkey-ceremony/{token} │
|
||||
│ SendPasskeyConfirmation (CORS libera https://web.whatsapp.com) │
|
||||
└─────────────────────────────────────────────────────────────────────────────────┘
|
||||
▲ │
|
||||
│ POST assertion / confirm │ GET desafio
|
||||
│ ▼
|
||||
┌──────────────────────── Extensão (content script) ─────────────────────────┐
|
||||
│ roda SÓ em https://web.whatsapp.com/* │
|
||||
│ lê o token+baseUrl do hash da URL → GET desafio → navigator.credentials.get │
|
||||
│ → POST da assinatura de volta │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
▲
|
||||
│ abre https://web.whatsapp.com/#wapk=<payload>
|
||||
┌──────────────────────────────── Manager ───────────────────────────────────┐
|
||||
│ QRCodeModal detecta passkeyStage no poll do QR → botão "Abrir WhatsApp Web" │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Papéis:**
|
||||
|
||||
1. **whatsmeow** — emite os eventos de passkey e expõe `SendPasskeyResponse` /
|
||||
`SendPasskeyConfirmation`.
|
||||
2. **Backend Evolution GO** — guarda o estado da cerimônia (por token efêmero) e
|
||||
expõe a API pública com CORS que o `web.whatsapp.com` chama.
|
||||
3. **Extensão** — a única peça no origin `web.whatsapp.com`; executa a cerimônia
|
||||
WebAuthn.
|
||||
4. **Manager** — abre a URL da cerimônia e faz polling até conectar.
|
||||
|
||||
---
|
||||
|
||||
## 3. Sequência ponta a ponta
|
||||
|
||||
1. Você cria a instância e clica em conectar.
|
||||
- **Conta normal:** o QR aparece, você escaneia, conecta — e o passkey **nunca
|
||||
é acionado**. Este guia não se aplica.
|
||||
- **Conta travada por passkey:** pode aparecer um QR primeiro (e o passkey vir
|
||||
depois do escaneio) **ou não haver QR algum** — o servidor decide. De
|
||||
qualquer forma, o próximo passo é o passkey.
|
||||
2. Quando o servidor pede o passkey, o whatsmeow emite `PairPasskeyRequest`
|
||||
(independente de ter havido QR). O backend:
|
||||
- gera um **token de cerimônia** efêmero (32 bytes, TTL 5 min);
|
||||
- guarda o desafio WebAuthn (`publicKey`) associado a esse token;
|
||||
- loga a URL `#wapk` pronta e a expõe no poll do QR.
|
||||
3. O manager detecta `passkeyStage` e mostra o painel de passkey, com o botão
|
||||
**"Abrir WhatsApp Web"** (aponta para
|
||||
`https://web.whatsapp.com/#wapk=<payload>`).
|
||||
4. A extensão (na aba `web.whatsapp.com`) lê o payload, busca o desafio na API,
|
||||
executa `navigator.credentials.get()` (biometria/PIN) e **POSTa a
|
||||
assinatura** para `/passkey-ceremony/{token}/response`.
|
||||
5. O backend chama `SendPasskeyResponse`. O servidor valida a assertion contra a
|
||||
chave pública registrada e responde com um **código de confirmação** →
|
||||
`PairPasskeyConfirmation` → o backend guarda o código no estado da cerimônia.
|
||||
6. A extensão mostra o código; o usuário confere e clica em confirmar → a
|
||||
extensão chama `/passkey-ceremony/{token}/confirm` → o backend chama
|
||||
`SendPasskeyConfirmation`.
|
||||
7. O pareamento se completa: `PairSuccess` / `Connected`. O backend limpa a
|
||||
cerimônia. O manager, ainda em polling, detecta `connected: true`.
|
||||
|
||||
> **Nota sobre o código de confirmação (handoff).** Em alguns casos o telefone
|
||||
> pula a tela de conferência de código (quando um "handoff proof" válido é
|
||||
> enviado). O Evolution GO **sempre** exige a confirmação manual
|
||||
> (`skipHandoffUX=false`) — confirmar automaticamente pode dessincronizar o
|
||||
> pareamento e disparar o anti-abuso do WhatsApp ("Não foi possível conectar o
|
||||
> dispositivo").
|
||||
|
||||
---
|
||||
|
||||
## 4. Configuração obrigatória
|
||||
|
||||
### `PASSKEY_PUBLIC_URL`
|
||||
|
||||
A extensão roda no navegador e precisa chamar a **API do Evolution GO**. A URL
|
||||
base dessa API precisa ser **acessível pelo navegador** onde o WhatsApp Web
|
||||
abre. Defina no `.env`:
|
||||
|
||||
```env
|
||||
# URL pública da API que o navegador (aba web.whatsapp.com) consegue alcançar.
|
||||
# Em produção: o domínio público da API.
|
||||
# Em desenvolvimento: um túnel (ngrok/cloudflared) OU o IP de LAN da máquina.
|
||||
# NÃO use localhost se o navegador estiver em outra máquina.
|
||||
PASSKEY_PUBLIC_URL=https://sua-api.exemplo.com
|
||||
```
|
||||
|
||||
> Se `PASSKEY_PUBLIC_URL` não estiver setado, a URL `#wapk` sai com o
|
||||
> placeholder `<SET_PASSKEY_PUBLIC_URL>` e o manager exibe um aviso, com o botão
|
||||
> "Abrir WhatsApp Web" desabilitado.
|
||||
|
||||
### Instalar a extensão (uma vez por navegador)
|
||||
|
||||
A extensão fica na pasta **`passkey-helper/`** do repositório público (Manifest
|
||||
V3, Chromium — Chrome/Edge). No repositório de desenvolvimento ela está em
|
||||
`tools/passkey-helper/`.
|
||||
|
||||
**Chrome:** `chrome://extensions` → ativar **Modo do desenvolvedor** → **Carregar
|
||||
sem compactação** → selecionar a pasta `passkey-helper`.
|
||||
|
||||
**Edge:** `edge://extensions` → **Modo de desenvolvedor** → **Carregar sem
|
||||
pacote** → selecionar a pasta `passkey-helper`.
|
||||
|
||||
> Use o navegador logado na mesma conta (Google/iCloud) onde a passkey do
|
||||
> WhatsApp está salva, ou tenha o celular por perto para a biometria.
|
||||
|
||||
### CORS
|
||||
|
||||
O backend já libera a origem `https://web.whatsapp.com` (o CORS atual usa `*`,
|
||||
que cobre chamadas não-credenciadas da extensão). As rotas `/passkey-ceremony/*`
|
||||
também estão isentas do gate de licença.
|
||||
|
||||
---
|
||||
|
||||
## 5. Guia rápido para testar (comunidade)
|
||||
|
||||
Recurso **novo (0.7.2)** e ainda **não validado ponta a ponta** — poucas contas
|
||||
foram travadas por passkey até agora. Se a sua conta pede passkey, siga o
|
||||
passo-a-passo abaixo e reporte o resultado (funcionou / em qual etapa parou +
|
||||
logs) numa issue do repositório. Isso ajuda muito.
|
||||
|
||||
**Como saber se preciso disso:** você tenta conectar a instância e (a) o QR não
|
||||
completa o pareamento mesmo escaneado, ou (b) nem aparece QR, ou (c) o app do
|
||||
WhatsApp reclama de "chave de acesso" / "não foi possível conectar o
|
||||
dispositivo". Nesses casos a conta provavelmente está travada por passkey.
|
||||
|
||||
**Pré-requisitos:**
|
||||
|
||||
1. Evolution GO **0.7.2+** rodando.
|
||||
2. `PASSKEY_PUBLIC_URL` no `.env` apontando para uma URL **pública** da API,
|
||||
alcançável pelo navegador (ver §4). Em teste local use um túnel (ngrok /
|
||||
cloudflared) — **não** `localhost` se o navegador estiver em outra máquina.
|
||||
3. A **extensão** `tools/passkey-helper` instalada no Chrome/Edge (ver §4).
|
||||
4. O navegador logado na mesma conta (Google/iCloud) onde a passkey do WhatsApp
|
||||
está salva, **ou** o celular por perto para a biometria.
|
||||
|
||||
**Passo a passo:**
|
||||
|
||||
1. No manager, crie a instância e clique em conectar.
|
||||
2. Se aparecer QR, escaneie. Se a conta for travada, o painel muda para
|
||||
**"Chave de acesso (passkey)"** (ou não haverá QR, indo direto para esse
|
||||
painel).
|
||||
3. Clique em **"Abrir WhatsApp Web"**. Abre uma aba `web.whatsapp.com` com o
|
||||
painel da extensão no canto.
|
||||
4. Na aba, clique em **"Autenticar com chave de acesso"** e confirme com
|
||||
biometria/PIN.
|
||||
5. Se aparecer um **código de confirmação**, confira que ele bate com o do
|
||||
celular e confirme.
|
||||
6. Volte ao manager e aguarde a instância ficar **conectada**.
|
||||
|
||||
**Sem o manager (teste manual via API):** o backend loga a URL `#wapk` pronta
|
||||
quando o passkey é pedido (procure por `Passkey required. Open this URL...` nos
|
||||
logs). Copie essa URL, abra no navegador com a extensão, e complete a cerimônia.
|
||||
Os endpoints estão na §6.
|
||||
|
||||
---
|
||||
|
||||
## 6. Referência das requisições
|
||||
|
||||
Todas as rotas de cerimônia são **públicas** (sem `apikey`): a segurança está no
|
||||
token de cerimônia — opaco, imprevisível, de uso único e com expiração. Sem um
|
||||
token válido não há nada a fazer, e concluir a cerimônia ainda exige o
|
||||
autenticador real do usuário.
|
||||
|
||||
`{base}` = `PASSKEY_PUBLIC_URL`. `{token}` = token de cerimônia.
|
||||
|
||||
### 5.1 Consultar o estado da cerimônia
|
||||
|
||||
```
|
||||
GET {base}/passkey-ceremony/{token}
|
||||
```
|
||||
|
||||
Resposta (200):
|
||||
|
||||
```json
|
||||
{
|
||||
"stage": "challenge",
|
||||
"publicKey": {
|
||||
"challenge": "<base64url>",
|
||||
"timeout": 60000,
|
||||
"rpId": "whatsapp.com",
|
||||
"allowCredentials": [
|
||||
{ "type": "public-key", "id": "<base64url>", "transports": ["internal"] }
|
||||
],
|
||||
"userVerification": "required"
|
||||
},
|
||||
"skipHandoffUX": false,
|
||||
"code": "",
|
||||
"error": ""
|
||||
}
|
||||
```
|
||||
|
||||
- `404` se o token for desconhecido ou expirado.
|
||||
|
||||
**Estágios (`stage`):**
|
||||
|
||||
| stage | significado |
|
||||
| ----------------------- | ------------------------------------------------------------------ |
|
||||
| `challenge` | desafio disponível; a extensão executa `navigator.credentials.get` |
|
||||
| `awaiting_confirmation` | assinatura enviada; aguardando o código do servidor |
|
||||
| `confirmation` | código disponível (`code`); usuário deve conferir e confirmar |
|
||||
| `confirmed` | confirmação enviada; pareamento concluindo |
|
||||
| `error` | falhou (ver `error`) |
|
||||
|
||||
### 5.2 Enviar a assinatura WebAuthn
|
||||
|
||||
```
|
||||
POST {base}/passkey-ceremony/{token}/response
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
Corpo (produzido por `navigator.credentials.get()`, tudo em base64url **sem
|
||||
padding**):
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "<credential id>",
|
||||
"rawId": "<base64url>",
|
||||
"type": "public-key",
|
||||
"response": {
|
||||
"clientDataJSON": "<base64url>",
|
||||
"authenticatorData": "<base64url>",
|
||||
"signature": "<base64url>",
|
||||
"userHandle": "<base64url|opcional>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Resposta: `200 {"ok": true}`. Em erro: `4xx/5xx {"error": "..."}`.
|
||||
|
||||
Internamente chama `client.SendPasskeyResponse(ctx, *types.WebAuthnResponse)`. O
|
||||
servidor então emite, de forma assíncrona, `PairPasskeyConfirmation` (código) ou
|
||||
`PairPasskeyError`.
|
||||
|
||||
### 5.3 Confirmar o código
|
||||
|
||||
```
|
||||
POST {base}/passkey-ceremony/{token}/confirm
|
||||
```
|
||||
|
||||
Resposta: `200 {"ok": true}`. Chama `client.SendPasskeyConfirmation(ctx)`; o
|
||||
pareamento então completa com `PairSuccess` / `Connected`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Como o manager expõe isso
|
||||
|
||||
O manager **não** tem um endpoint dedicado — ele reaproveita o poll do QR que já
|
||||
existe. O endpoint autenticado do QR (`GET /instance/qr`, header `apikey`)
|
||||
retorna, quando há uma cerimônia ativa:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "success",
|
||||
"data": {
|
||||
"qrcode": "",
|
||||
"code": "",
|
||||
"passkeyStage": "challenge",
|
||||
"passkeyOpenUrl": "https://web.whatsapp.com/#wapk=...",
|
||||
"passkeyCode": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
O `QRCodeModal` detecta `passkeyStage` e mostra o painel de passkey (botão
|
||||
"Abrir WhatsApp Web" → `passkeyOpenUrl`, e o `passkeyCode` quando disponível).
|
||||
|
||||
> **Importante:** a **extensão** conduz a cerimônia inteira (desafio +
|
||||
> confirmação). O manager só abre a URL e faz polling. O código de confirmação é
|
||||
> exibido tanto na extensão quanto (opcionalmente) no manager para conferência.
|
||||
|
||||
---
|
||||
|
||||
## 8. Notas de implementação (para quem for mexer no backend)
|
||||
|
||||
Regras que **não** podem ser violadas (extraídas do comportamento do whatsmeow):
|
||||
|
||||
- **Não use `GetQRChannel` durante o passkey.** No whatsmeow instalado, o handler
|
||||
do `qrChannel` (a) auto-confirma a `PairPasskeyConfirmation` quando
|
||||
`SkipHandoffUX` está setado — correndo com o fluxo manual — e (b) desconecta o
|
||||
socket quando os códigos de QR acabam. Por isso o Evolution GO conecta com
|
||||
`client.Connect()` direto e consome `events.QR` no event handler
|
||||
(`handleQRCodes`), que o `pair.go` despacha para todos os handlers de qualquer
|
||||
forma.
|
||||
- **Nunca auto-confirme com base em `SkipHandoffUX`.** O backend força
|
||||
`skipHandoffUX=false`, então a confirmação é sempre manual (o usuário confere o
|
||||
código). Auto-confirmar dessincroniza o pareamento e dispara o anti-abuso do
|
||||
WhatsApp.
|
||||
- **`EnableAutoReconnect = false`** já está setado; a reconexão é centralizada
|
||||
pela aplicação.
|
||||
- **A rotação de QR pausa durante uma cerimônia de passkey.** O `handleQRCodes`
|
||||
consulta `ceremony.Store.HasActiveByInstance()` antes de qualquer teardown, para
|
||||
não derrubar o socket enquanto o usuário completa a cerimônia (que é conduzida
|
||||
por um humano no navegador e pode demorar mais que a janela de rotação do QR).
|
||||
- **`PairPasskeyRequest` NÃO chama `SendPasskeyResponse`.** No momento do request
|
||||
só existe o desafio; a assinatura só existe depois que a extensão roda
|
||||
`navigator.credentials.get()`. O `SendPasskeyResponse` é chamado apenas no
|
||||
handler HTTP `/response`.
|
||||
|
||||
Arquivos principais:
|
||||
|
||||
| Arquivo | Responsabilidade |
|
||||
| ---------------------------------------------- | -------------------------------------------------- |
|
||||
| `pkg/passkey/ceremony/store.go` | estado da cerimônia (token → estágio), mutex, TTL |
|
||||
| `pkg/passkey/handler/passkey_handler.go` | os 3 endpoints públicos |
|
||||
| `pkg/whatsmeow/service/whatsmeow.go` | eventos `PairPasskey*`, `handleQRCodes`, bridges |
|
||||
| `pkg/instance/service/instance_service.go` | `GetQr` expõe o estado da cerimônia ao manager |
|
||||
| `tools/passkey-helper/` | extensão de navegador (content script + manifest) |
|
||||
|
||||
---
|
||||
|
||||
## 9. Solução de problemas
|
||||
|
||||
| Sintoma | Causa provável / correção |
|
||||
| --------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| Botão "Abrir WhatsApp Web" desabilitado | `PASSKEY_PUBLIC_URL` não configurado. Defina no `.env` e reinicie. |
|
||||
| A aba `web.whatsapp.com` não mostra o painel | Extensão não instalada / não é a aba de `web.whatsapp.com`. Instale e recarregue a aba. |
|
||||
| `ceremony not found or expired` (404) | Token expirou (TTL 5 min). Gere um novo QR no manager para reiniciar a cerimônia. |
|
||||
| A extensão falha ao buscar o desafio (CORS/rede) | `PASSKEY_PUBLIC_URL` não é alcançável pelo navegador. Use um túnel ou o IP de LAN correto. |
|
||||
| "Não foi possível conectar o dispositivo" | Confirmação automática indevida. O backend força `skipHandoffUX=false` — confirme manual. |
|
||||
| A assinatura é rejeitada pelo WhatsApp | Formato base64url com padding. A extensão emite base64url **sem** padding (correto). |
|
||||
|
||||
---
|
||||
|
||||
## 10. Segurança
|
||||
|
||||
- O token de cerimônia é opaco, de uso único e expira em ~5 minutos.
|
||||
- As rotas de cerimônia são públicas por design: sem um token válido não há nada
|
||||
a fazer, e concluir a cerimônia exige o autenticador real do usuário.
|
||||
- A extensão não coleta nem envia dados a terceiros; apenas executa a cerimônia
|
||||
WebAuthn no origin correto.
|
||||
- O whatsmeow é licenciado sob MIT; os eventos e métodos de passkey fazem parte
|
||||
da biblioteca oficial (`go.mau.fi/whatsmeow`).
|
||||
|
||||
---
|
||||
|
||||
## 11. Referências e limites conhecidos
|
||||
|
||||
- **Não existe bypass headless.** Numa conta travada, vincular exige uma assertion
|
||||
do **próprio authenticator do dono** — obtida no navegador/dispositivo dele e
|
||||
repassada ao fluxo. Isso é *usar* o passkey real, não burlá-lo. O servidor
|
||||
valida a assinatura contra a chave pública registrada da conta (challenge
|
||||
fresco, sem replay); assertions forjadas são rejeitadas silenciosamente.
|
||||
- **Web-only.** A cerimônia Shortcake só roda num companion web. Companion android
|
||||
é rejeitado (`463 account_reachout_restricted`).
|
||||
- **A decisão é do servidor.** Nenhuma versão de client, flag ou capability
|
||||
desvia do passkey — é um bucket A/B por conta, server-side.
|
||||
- **Engenharia reversa do protocolo:** o fluxo Shortcake/CRSC (as stanzas,
|
||||
a criptografia ECDH commit-reveal, a captura de wire correlacionada) foi
|
||||
documentado de forma independente pelo projeto **zapo** em
|
||||
<https://zapo.to/pt-br/reverse-engineering/passkey-linking> — leitura
|
||||
recomendada para quem quiser entender o protocolo por baixo. O `zapo` é um
|
||||
projeto independente, não afiliado ao WhatsApp/Meta; o Evolution GO apenas
|
||||
consome o suporte a passkey já implementado no whatsmeow oficial.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,474 @@
|
||||
# Armazenamento de Mídia
|
||||
|
||||
Sistema de armazenamento de arquivos de mídia do Evolution GO. Suporta MinIO, Amazon S3 e outros serviços compatíveis com S3.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Configuração](#configuração)
|
||||
- [Estrutura de Arquivos](#estrutura-de-arquivos)
|
||||
- [URLs Presignadas](#urls-presignadas)
|
||||
- [Provedores Compatíveis](#provedores-compatíveis)
|
||||
- [Exemplos Práticos](#exemplos-práticos)
|
||||
- [Boas Práticas](#boas-práticas)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
O Evolution GO armazena arquivos de mídia (imagens, vídeos, áudios, documentos) em **object storage** compatível com S3. Isso inclui serviços como MinIO, Amazon S3, Backblaze B2, DigitalOcean Spaces e outros.
|
||||
|
||||
### Por que Object Storage?
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Escalável: suporta terabytes ou petabytes de dados
|
||||
- ✅ Distribuído: alta disponibilidade e redundância
|
||||
- ✅ Custo-efetivo: preços competitivos comparados a armazenamento tradicional
|
||||
- ✅ Integração com CDN: acesso rápido globalmente
|
||||
- ✅ Políticas de ciclo de vida: limpeza automática de arquivos antigos
|
||||
|
||||
**Comparado com armazenamento local (disco)**:
|
||||
- ❌ Armazenamento local não escala horizontalmente
|
||||
- ❌ Risco de perda de dados se o servidor falhar
|
||||
- ❌ Complica deploys em clusters
|
||||
- ❌ Sem redundância geográfica
|
||||
|
||||
### Arquitetura
|
||||
|
||||
```
|
||||
┌─────────────┐
|
||||
│ WhatsApp │ Envia mídia
|
||||
└──────┬──────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ Evolution GO │ Recebe arquivo
|
||||
└──────┬───────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────────┐
|
||||
│ MediaStorage Interface │
|
||||
└───────────────┬──────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────┐
|
||||
│ MinIO Storage Impl │
|
||||
│ (S3-Compatible Object Storage) │
|
||||
└───────────────┬─────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────┐
|
||||
│ MinIO Server │
|
||||
│ (ou S3, B2, etc) │
|
||||
└───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ Bucket │
|
||||
│ evolution- │
|
||||
│ go-medias/ │
|
||||
└──────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuração
|
||||
|
||||
### Variáveis de Ambiente
|
||||
|
||||
```env
|
||||
# MinIO/S3 Endpoint
|
||||
MINIO_ENDPOINT=s3.amazonaws.com
|
||||
|
||||
# Credenciais
|
||||
MINIO_ACCESS_KEY=sua-access-key
|
||||
MINIO_SECRET_KEY=sua-secret-key
|
||||
|
||||
# Bucket
|
||||
MINIO_BUCKET=evolution-go-media
|
||||
|
||||
# Região (para AWS S3)
|
||||
MINIO_REGION=us-east-1
|
||||
|
||||
# Usar SSL (true/false)
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
### Exemplo: MinIO Local (Docker)
|
||||
|
||||
```bash
|
||||
# Rodar MinIO server
|
||||
docker run -d --name minio -p 9000:9000 -p 9001:9001 -e MINIO_ROOT_USER=admin -e MINIO_ROOT_PASSWORD=password -v minio_data:/data minio/minio server /data --console-address ":9001"
|
||||
|
||||
# Criar bucket via mc (MinIO Client)
|
||||
docker run --rm --network host minio/mc alias set local http://localhost:9000 admin password
|
||||
|
||||
docker run --rm --network host minio/mc mb local/evolution-go-media
|
||||
|
||||
# .env
|
||||
MINIO_ENDPOINT=localhost:9000
|
||||
MINIO_ACCESS_KEY=admin
|
||||
MINIO_SECRET_KEY=password
|
||||
MINIO_BUCKET=evolution-go-media
|
||||
MINIO_REGION=us-east-1
|
||||
MINIO_USE_SSL=false
|
||||
```
|
||||
|
||||
**Acesso Web Console**: http://localhost:9001
|
||||
|
||||
### Exemplo: AWS S3
|
||||
|
||||
```env
|
||||
MINIO_ENDPOINT=s3.amazonaws.com
|
||||
MINIO_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE
|
||||
MINIO_SECRET_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
|
||||
MINIO_BUCKET=meu-bucket-evolution
|
||||
MINIO_REGION=us-east-1
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
### Exemplo: Backblaze B2
|
||||
|
||||
```env
|
||||
MINIO_ENDPOINT=s3.us-west-004.backblazeb2.com
|
||||
MINIO_ACCESS_KEY=sua-key-id
|
||||
MINIO_SECRET_KEY=sua-application-key
|
||||
MINIO_BUCKET=meu-bucket
|
||||
MINIO_REGION=us-west-004
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
### Exemplo: DigitalOcean Spaces
|
||||
|
||||
```env
|
||||
MINIO_ENDPOINT=nyc3.digitaloceanspaces.com
|
||||
MINIO_ACCESS_KEY=sua-spaces-key
|
||||
MINIO_SECRET_KEY=sua-spaces-secret
|
||||
MINIO_BUCKET=meu-space
|
||||
MINIO_REGION=nyc3
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Estrutura de Arquivos
|
||||
|
||||
### Organização
|
||||
|
||||
Arquivos são armazenados com estrutura organizada:
|
||||
|
||||
```
|
||||
bucket-name/
|
||||
└── evolution-go-medias/
|
||||
├── image-abc123.jpg
|
||||
├── video-def456.mp4
|
||||
├── audio-ghi789.ogg
|
||||
└── document-jkl012.pdf
|
||||
```
|
||||
|
||||
### Caminho dos Arquivos
|
||||
|
||||
Todos os arquivos são armazenados automaticamente no diretório `evolution-go-medias/`:
|
||||
|
||||
**Exemplos**:
|
||||
- Arquivo: `photo-123.jpg` → Caminho: `evolution-go-medias/photo-123.jpg`
|
||||
- Arquivo: `video-456.mp4` → Caminho: `evolution-go-medias/video-456.mp4`
|
||||
- Arquivo: `document-789.pdf` → Caminho: `evolution-go-medias/document-789.pdf`
|
||||
|
||||
---
|
||||
|
||||
## URLs Presignadas
|
||||
|
||||
### O que são?
|
||||
|
||||
**URLs presignadas** são URLs temporárias que permitem acesso a arquivos privados sem expor suas credenciais de acesso.
|
||||
|
||||
**Características**:
|
||||
- ✅ Válidas por tempo limitado (padrão: 7 dias)
|
||||
- ✅ Não requerem autenticação adicional
|
||||
- ✅ Assinadas criptograficamente para segurança
|
||||
- ✅ Podem ser compartilhadas publicamente durante o período de validade
|
||||
|
||||
### Como Funcionam
|
||||
|
||||
Quando você armazena ou solicita acesso a um arquivo, o Evolution GO gera automaticamente uma URL presignada com validade de 7 dias.
|
||||
|
||||
**Exemplo de URL presignada**:
|
||||
```
|
||||
https://s3.amazonaws.com/evolution-go-media/evolution-go-medias/photo-123.jpg?
|
||||
X-Amz-Algorithm=AWS4-HMAC-SHA256&
|
||||
X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20250111%2Fus-east-1%2Fs3%2Faws4_request&
|
||||
X-Amz-Date=20250111T100000Z&
|
||||
X-Amz-Expires=604800&
|
||||
X-Amz-SignedHeaders=host&
|
||||
X-Amz-Signature=abc123def456...
|
||||
```
|
||||
|
||||
### Validade
|
||||
|
||||
**Tempo de expiração**: 7 dias (168 horas)
|
||||
|
||||
**Após expiração**:
|
||||
- A URL retorna erro `403 Forbidden`
|
||||
- É necessário gerar uma nova URL através da API
|
||||
|
||||
---
|
||||
|
||||
## Provedores Compatíveis
|
||||
|
||||
### Amazon S3
|
||||
|
||||
**Configuração**:
|
||||
```env
|
||||
MINIO_ENDPOINT=s3.amazonaws.com
|
||||
MINIO_REGION=us-east-1
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Mais confiável e testado
|
||||
- ✅ Integração com CloudFront (CDN)
|
||||
- ✅ Lifecycle policies avançadas
|
||||
- ✅ Versionamento de objetos
|
||||
|
||||
**Desvantagens**:
|
||||
- ❌ Mais caro que alternativas
|
||||
- ❌ Vendor lock-in
|
||||
|
||||
### MinIO (Self-hosted)
|
||||
|
||||
**Configuração**:
|
||||
```env
|
||||
MINIO_ENDPOINT=minio.meu-dominio.com:9000
|
||||
MINIO_REGION=us-east-1
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Gratuito (self-hosted)
|
||||
- ✅ Controle total
|
||||
- ✅ Compatível com S3 API
|
||||
- ✅ Bom para desenvolvimento
|
||||
|
||||
**Desvantagens**:
|
||||
- ❌ Você gerencia infraestrutura
|
||||
- ❌ Requer configuração de HA
|
||||
|
||||
### Backblaze B2
|
||||
|
||||
**Configuração**:
|
||||
```env
|
||||
MINIO_ENDPOINT=s3.us-west-004.backblazeb2.com
|
||||
MINIO_REGION=us-west-004
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Muito mais barato que S3 (1/4 do preço)
|
||||
- ✅ Egress gratuito (até 3x storage)
|
||||
- ✅ S3-compatible
|
||||
|
||||
**Desvantagens**:
|
||||
- ❌ Não suporta bucket policies (usa presigned URLs)
|
||||
- ❌ Menos integrações que AWS
|
||||
|
||||
### DigitalOcean Spaces
|
||||
|
||||
**Configuração**:
|
||||
```env
|
||||
MINIO_ENDPOINT=nyc3.digitaloceanspaces.com
|
||||
MINIO_REGION=nyc3
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Preço fixo ($5/mês por 250GB)
|
||||
- ✅ CDN incluso
|
||||
- ✅ Fácil configuração
|
||||
|
||||
**Desvantagens**:
|
||||
- ❌ Limite de 250GB no plano básico
|
||||
- ❌ Menos recursos que S3
|
||||
|
||||
### Wasabi
|
||||
|
||||
**Configuração**:
|
||||
```env
|
||||
MINIO_ENDPOINT=s3.wasabisys.com
|
||||
MINIO_REGION=us-east-1
|
||||
MINIO_USE_SSL=true
|
||||
```
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Sem custo de egress
|
||||
- ✅ Preço competitivo
|
||||
- ✅ S3-compatible
|
||||
|
||||
---
|
||||
|
||||
## Exemplos Práticos
|
||||
|
||||
### 1. Upload de Mídia
|
||||
|
||||
Quando o WhatsApp recebe uma imagem, vídeo ou documento:
|
||||
1. O Evolution GO baixa o arquivo
|
||||
2. Armazena automaticamente no object storage configurado
|
||||
3. Gera uma URL presignada de acesso
|
||||
4. A URL é incluída na resposta da API ou evento
|
||||
|
||||
### 2. Acesso a Mídia Armazenada
|
||||
|
||||
Para acessar um arquivo já armazenado:
|
||||
- Use a URL presignada retornada durante o upload
|
||||
- Se a URL expirou (>7 dias), solicite uma nova através da API
|
||||
|
||||
### 3. Limpeza de Arquivos Antigos
|
||||
|
||||
Configure lifecycle policies no seu provedor para deletar automaticamente arquivos antigos:
|
||||
- **AWS S3**: Configure regras de ciclo de vida no console
|
||||
- **MinIO**: Use o comando `mc ilm` para configurar políticas
|
||||
- **Outros**: Consulte a documentação do provedor
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Use Nomes de Arquivo Únicos
|
||||
|
||||
Gere nomes únicos para cada arquivo para evitar sobrescrever arquivos existentes:
|
||||
|
||||
**❌ Evite**: Usar nomes genéricos como `photo.jpg`, `video.mp4`
|
||||
|
||||
**✅ Recomendado**: Usar identificadores únicos como UUID ou timestamp:
|
||||
- `photo-abc123-def456-ghi789.jpg`
|
||||
- `video-20250111-103045.mp4`
|
||||
- `document-550e8400-e29b-41d4.pdf`
|
||||
|
||||
### 2. Configure Content-Type Correto
|
||||
|
||||
O Evolution GO configura automaticamente o Content-Type baseado na extensão do arquivo:
|
||||
- `.jpg`, `.jpeg` → `image/jpeg`
|
||||
- `.png` → `image/png`
|
||||
- `.mp4` → `video/mp4`
|
||||
- `.pdf` → `application/pdf`
|
||||
- `.ogg` → `audio/ogg`
|
||||
|
||||
### 3. Implemente Lifecycle Policies
|
||||
|
||||
**AWS S3**:
|
||||
```json
|
||||
{
|
||||
"Rules": [
|
||||
{
|
||||
"Id": "delete-old-media",
|
||||
"Status": "Enabled",
|
||||
"Prefix": "evolution-go-medias/",
|
||||
"Expiration": {
|
||||
"Days": 30
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**MinIO**:
|
||||
```bash
|
||||
mc ilm add local/evolution-go-media --prefix "evolution-go-medias/" --expiry-days 30
|
||||
```
|
||||
|
||||
### 4. Use CDN para Distribuição
|
||||
|
||||
**CloudFront (AWS)**:
|
||||
1. Crie distribuição CloudFront
|
||||
2. Aponte origin para bucket S3
|
||||
3. URLs ficam: `https://d123456.cloudfront.net/evolution-go-medias/photo.jpg`
|
||||
|
||||
**DigitalOcean Spaces CDN** (automático):
|
||||
```
|
||||
https://bucket-name.nyc3.cdn.digitaloceanspaces.com/file.jpg
|
||||
```
|
||||
|
||||
### 5. Monitore Uso e Custos
|
||||
|
||||
```bash
|
||||
# AWS S3 - Tamanho total do bucket
|
||||
aws s3 ls s3://bucket-name --recursive --summarize | grep "Total Size"
|
||||
|
||||
# MinIO
|
||||
mc du local/evolution-go-media
|
||||
```
|
||||
|
||||
### 6. Comprima Imagens Quando Possível
|
||||
|
||||
Para reduzir custos de armazenamento e transferência:
|
||||
- Comprima imagens antes de armazenar
|
||||
- Use formatos modernos como WebP quando possível
|
||||
- Ajuste a qualidade JPEG para 80-90% (reduz tamanho sem perda significativa de qualidade)
|
||||
|
||||
### 7. Monitore Uso e Custos
|
||||
|
||||
Acompanhe regularmente:
|
||||
- Tamanho total do bucket
|
||||
- Número de arquivos armazenados
|
||||
- Custos mensais de armazenamento e transferência
|
||||
- URLs presignadas que expiraram
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Erro: "failed to create MinIO client"
|
||||
|
||||
**Causa**: Credenciais ou endpoint incorretos.
|
||||
|
||||
**Solução**:
|
||||
```bash
|
||||
# Testar conexão com mc
|
||||
mc alias set test https://endpoint access-key secret-key
|
||||
mc ls test
|
||||
```
|
||||
|
||||
### Erro: "bucket does not exist"
|
||||
|
||||
**Causa**: Bucket não foi criado.
|
||||
|
||||
**Solução**:
|
||||
```bash
|
||||
# Criar bucket
|
||||
mc mb test/evolution-go-media
|
||||
|
||||
# Ou via AWS CLI
|
||||
aws s3 mb s3://evolution-go-media
|
||||
```
|
||||
|
||||
### URLs retornam 403 Forbidden
|
||||
|
||||
**Causa 1**: URL presignada expirou (>7 dias).
|
||||
|
||||
**Solução**: Gere nova URL com `GetURL()`.
|
||||
|
||||
**Causa 2**: Bucket policy incorreta.
|
||||
|
||||
**Solução**: Use presigned URLs (funcionam independente de bucket policy).
|
||||
|
||||
### Upload muito lento
|
||||
|
||||
**Causa**: Latência de rede para região distante.
|
||||
|
||||
**Solução**:
|
||||
1. Use região mais próxima do servidor
|
||||
2. Use multipart upload para arquivos grandes (>5MB)
|
||||
3. Configure timeout adequado
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [Sistema de Eventos](./events-system.md) - Receber notificações de uploads
|
||||
- [Conexão QR Code](./qrcode-connection.md) - Autenticação WhatsApp
|
||||
- [Multi-Dispositivo](./multi-device.md) - Suporte Multi-Device
|
||||
- [API de Mensagens](../guias-api/api-messages.md) - Enviar mídias via API
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,395 @@
|
||||
# WhatsApp Multi-Device
|
||||
|
||||
Entenda como funciona o protocolo Multi-Device do WhatsApp e como o Evolution GO o utiliza.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Arquitetura](#arquitetura)
|
||||
- [Protocolo Signal](#protocolo-signal)
|
||||
- [Sincronização de Dados](#sincronização-de-dados)
|
||||
- [Criptografia](#criptografia)
|
||||
- [Limitações](#limitações)
|
||||
- [Vantagens](#vantagens)
|
||||
- [Comparação com Versão Antiga](#comparação-com-versão-antiga)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
WhatsApp **Multi-Device** é o protocolo que permite conectar até 4 dispositivos simultaneamente, sem necessidade do celular estar online após o pareamento inicial.
|
||||
|
||||
### Antes vs Depois
|
||||
|
||||
**Legacy (Antigo - Web WhatsApp)**:
|
||||
```
|
||||
┌─────────────┐
|
||||
│ Celular │ ◄── SEMPRE precisa estar online
|
||||
│ (Primary) │
|
||||
└──────┬──────┘
|
||||
│
|
||||
│ Relay
|
||||
│
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ WhatsApp Web │ ◄── Depende 100% do celular
|
||||
└──────────────┘
|
||||
```
|
||||
|
||||
**Multi-Device (Atual)**:
|
||||
```
|
||||
┌─────────────┐
|
||||
│ Celular │ ◄── Dispositivo principal
|
||||
│ (Primary) │
|
||||
└──────┬──────┘
|
||||
│
|
||||
│ Peer-to-Peer Sync
|
||||
│
|
||||
├────────────┬────────────┬────────────┐
|
||||
▼ ▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
|
||||
│WhatsApp │ │Evolution │ │WhatsApp │ │WhatsApp │
|
||||
│Desktop │ │ GO │ │Web │ │Business │
|
||||
└──────────┘ └──────────┘ └──────────┘ └──────────┘
|
||||
|
||||
Todos funcionam INDEPENDENTEMENTE!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Arquitetura
|
||||
|
||||
### Componentes
|
||||
|
||||
1. **Dispositivo Principal (Primary Device)**
|
||||
- Celular com WhatsApp instalado
|
||||
- Única fonte de verdade para contatos e configurações
|
||||
- Pode funcionar offline após sincronização inicial
|
||||
|
||||
2. **Dispositivos Companion (Companion Devices)**
|
||||
- WhatsApp Web, Desktop, Business API, Evolution GO
|
||||
- Até 4 dispositivos simultâneos
|
||||
- Funcionam independentemente após pareamento
|
||||
|
||||
3. **Servidores WhatsApp**
|
||||
- Facilitam comunicação entre devices
|
||||
- Armazenam mensagens criptografadas temporariamente
|
||||
- Sincronizam estado entre dispositivos
|
||||
|
||||
### Diagrama de Comunicação
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ WhatsApp Servers │
|
||||
│ - Message Routing │
|
||||
│ - State Synchronization │
|
||||
│ - End-to-End Encryption Relay │
|
||||
└───────────────────┬──────────────────────────────────────┘
|
||||
│
|
||||
┌──────────┼──────────┬──────────┬──────────┐
|
||||
│ │ │ │ │
|
||||
▼ ▼ ▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Primary │ │Device 1│ │Device 2│ │Device 3│ │Device 4│
|
||||
│(Phone) │ │Desktop │ │Evolution│ │ Web │ │Business│
|
||||
└────────┘ └────────┘ └────────┘ └────────┘ └────────┘
|
||||
│ │ │ │ │
|
||||
└──────────┴──────────┴──────────┴──────────┘
|
||||
│
|
||||
Direct Peer Sync
|
||||
(quando ambos online)
|
||||
```
|
||||
|
||||
### Funcionamento
|
||||
|
||||
**Enviar Mensagem**:
|
||||
1. Device 1 (Evolution GO) envia mensagem criptografada para WhatsApp servers
|
||||
2. Servers encaminham para destinatário
|
||||
3. Servers **também** sincronizam com outros devices do remetente
|
||||
4. Primary device e outros companion devices recebem cópia
|
||||
|
||||
**Receber Mensagem**:
|
||||
1. WhatsApp servers recebem mensagem destinada ao seu número
|
||||
2. Servers replicam para **todos os devices conectados** simultaneamente
|
||||
3. Cada device descriptografa independentemente
|
||||
|
||||
---
|
||||
|
||||
## Protocolo Signal
|
||||
|
||||
### O que é Signal Protocol?
|
||||
|
||||
**Signal Protocol** é o protocolo de criptografia ponta-a-ponta (E2EE) usado pelo WhatsApp Multi-Device.
|
||||
|
||||
**Criado por**: Open Whisper Systems (agora Signal Foundation)
|
||||
|
||||
**Usado em**:
|
||||
- WhatsApp
|
||||
- Signal Messenger
|
||||
- Facebook Messenger (Secret Conversations)
|
||||
- Google Messages (RCS)
|
||||
|
||||
### Componentes do Signal Protocol
|
||||
|
||||
#### 1. Identity Keys (Chaves de Identidade)
|
||||
|
||||
Cada dispositivo tem um par de chaves únicas:
|
||||
- **Chave Pública**: Compartilhada com outros dispositivos
|
||||
- **Chave Privada**: Nunca sai do dispositivo, usada para descriptografia
|
||||
|
||||
#### 2. Pre-Keys (Chaves Pré-geradas)
|
||||
|
||||
Um conjunto de 100 chaves geradas automaticamente quando você conecta um dispositivo pela primeira vez. Essas chaves permitem que outros dispositivos iniciem conversas criptografadas com você, mesmo quando você está offline.
|
||||
|
||||
**Renovação**: Novas pre-keys são geradas automaticamente conforme necessário.
|
||||
|
||||
#### 3. Signed Pre-Keys (Chaves Assinadas)
|
||||
|
||||
Uma pre-key especial assinada pela sua chave de identidade, provando autenticidade.
|
||||
|
||||
**Renovação**: A cada 7 dias.
|
||||
|
||||
#### 4. Session Keys (Chaves de Sessão)
|
||||
|
||||
Chaves únicas para cada conversa que mudam automaticamente a cada mensagem enviada (conceito chamado "ratcheting").
|
||||
|
||||
**Segurança**: Se uma chave for comprometida, apenas aquela mensagem específica é afetada - mensagens anteriores e futuras permanecem seguras (Forward Secrecy).
|
||||
|
||||
---
|
||||
|
||||
## Sincronização de Dados
|
||||
|
||||
### Tipos de Sincronização
|
||||
|
||||
#### 1. Mensagens
|
||||
|
||||
**Histórico Inicial**:
|
||||
- Últimos **3 meses** de conversas
|
||||
- Mídia: Apenas thumbnails (mídia completa baixada on-demand)
|
||||
|
||||
**Novas Mensagens**:
|
||||
- Sincronizadas em tempo real
|
||||
- Todos os dispositivos recebem simultaneamente
|
||||
|
||||
#### 2. Contatos
|
||||
|
||||
**Sincronização**:
|
||||
- Lista completa de contatos do celular
|
||||
- Atualizada automaticamente quando um contato muda nome ou número
|
||||
|
||||
#### 3. Grupos
|
||||
|
||||
**Informações sincronizadas**:
|
||||
- Lista de todos os grupos que você participa
|
||||
- Metadados (nome, descrição, foto, lista de participantes)
|
||||
- Configurações (silenciado, fixado)
|
||||
|
||||
#### 4. Chats
|
||||
|
||||
**Estados sincronizados**:
|
||||
- Chats fixados (pinned)
|
||||
- Chats arquivados (archived)
|
||||
- Chats silenciados (muted)
|
||||
- Mensagens lidas/não lidas
|
||||
|
||||
#### 5. Configurações
|
||||
|
||||
**Sincronizadas**:
|
||||
- Foto de perfil
|
||||
- Nome de exibição
|
||||
- Recado (status text)
|
||||
- Configurações de privacidade
|
||||
|
||||
**NÃO sincronizadas**:
|
||||
- Notificações (específico por device)
|
||||
- Tema/aparência (específico por device)
|
||||
|
||||
### History Sync Request
|
||||
|
||||
**Solicitação de histórico** (implementado via API):
|
||||
|
||||
```bash
|
||||
POST /chat/history-sync-request
|
||||
{
|
||||
"messageInfo": {
|
||||
"Chat": "5511999999999@s.whatsapp.net",
|
||||
"IsFromMe": false,
|
||||
"IsGroup": false,
|
||||
"ID": "3EB0C5A277F7F9B6C599",
|
||||
"Timestamp": "2025-11-11T10:00:00Z"
|
||||
},
|
||||
"count": 50
|
||||
}
|
||||
```
|
||||
|
||||
**Parâmetros**:
|
||||
- `messageInfo`: Mensagem de referência (ponto de partida)
|
||||
- `count`: Número de mensagens para buscar (máx 100)
|
||||
|
||||
**Uso**: Carregar mensagens antigas de uma conversa.
|
||||
|
||||
---
|
||||
|
||||
## Criptografia
|
||||
|
||||
### End-to-End Encryption (Criptografia Ponta-a-Ponta)
|
||||
|
||||
Todas as mensagens são criptografadas no dispositivo do remetente e só podem ser descriptografadas no dispositivo do destinatário.
|
||||
|
||||
**Importante**: Os servidores do WhatsApp não conseguem ler o conteúdo das mensagens - eles apenas facilitam a entrega dos dados criptografados.
|
||||
|
||||
### Fluxo de Criptografia
|
||||
|
||||
```
|
||||
┌────────────┐ ┌────────────┐
|
||||
│ Remetente │ │Destinatário│
|
||||
│ (Device) │ │ (Device) │
|
||||
└─────┬──────┘ └──────┬─────┘
|
||||
│ │
|
||||
│ 1. Mensagem: "Olá!" │
|
||||
│──────────┐ │
|
||||
│ │ │
|
||||
│ 2. Criptografa com Session Key │
|
||||
│<─────────┘ │
|
||||
│ │
|
||||
│ 3. Envia encrypted blob │
|
||||
│───────────────────────────────────────────────>│
|
||||
│ (via WhatsApp Servers) │
|
||||
│ │
|
||||
│ │ 4. Descriptografa
|
||||
│ │────────────┐
|
||||
│ │ │
|
||||
│ │ 5. "Olá!" │
|
||||
│ │<───────────┘
|
||||
│ │
|
||||
```
|
||||
|
||||
### Verificação de Segurança
|
||||
|
||||
**Código de Segurança (Safety Number)**:
|
||||
- É um código de 60 dígitos único para cada conversa
|
||||
- Compara as chaves de identidade dos participantes
|
||||
- Muda se um dos participantes trocar de dispositivo
|
||||
|
||||
**Como verificar no WhatsApp**:
|
||||
1. Abrir a conversa
|
||||
2. Tocar no nome do contato
|
||||
3. Selecionar "Criptografia"
|
||||
4. Comparar o código com o contato pessoalmente ou por outro canal seguro
|
||||
|
||||
---
|
||||
|
||||
## Limitações
|
||||
|
||||
### Limite de Devices
|
||||
|
||||
**Máximo**: 4 companion devices + 1 primary device (celular).
|
||||
|
||||
**Exemplo**:
|
||||
- ✅ Celular (Primary)
|
||||
- ✅ WhatsApp Web (Device 1)
|
||||
- ✅ WhatsApp Desktop (Device 2)
|
||||
- ✅ Evolution GO (Device 3)
|
||||
- ✅ WhatsApp Business API (Device 4)
|
||||
- ❌ Outro device → Erro: "Máximo de devices atingido"
|
||||
|
||||
**Solução**: Desconectar um device antes de conectar novo.
|
||||
|
||||
### Histórico Limitado
|
||||
|
||||
**Sincronização inicial**: Apenas últimos **3 meses**.
|
||||
|
||||
**Mensagens mais antigas**:
|
||||
- Não são sincronizadas automaticamente
|
||||
- Podem ser buscadas via History Sync Request (se disponíveis)
|
||||
- Mídia completa não é transferida (apenas thumbnails)
|
||||
|
||||
### Chamadas
|
||||
|
||||
**Limitação atual**: Evolution GO **não suporta atender** chamadas de voz/vídeo.
|
||||
|
||||
**Suportado**:
|
||||
- ✅ Receber notificação de chamada (evento `CALL`)
|
||||
- ✅ Rejeitar chamada automaticamente
|
||||
|
||||
**NÃO suportado**:
|
||||
- ❌ Atender chamada
|
||||
- ❌ Áudio/vídeo em tempo real
|
||||
|
||||
### Sessão Expira
|
||||
|
||||
**Inatividade**: Se device ficar offline por **>14 dias**, sessão expira.
|
||||
|
||||
**Solução**: Novo pareamento via QR Code necessário.
|
||||
|
||||
---
|
||||
|
||||
## Vantagens
|
||||
|
||||
### 1. Independência do Celular
|
||||
|
||||
**Evolution GO funciona mesmo com celular offline** (após sincronização inicial).
|
||||
|
||||
**Casos de uso**:
|
||||
- Celular sem bateria
|
||||
- Celular sem internet
|
||||
- Viagem internacional (celular desligado)
|
||||
|
||||
### 2. Sincronização em Tempo Real
|
||||
|
||||
**Todas as mensagens** aparecem em todos os devices simultaneamente.
|
||||
|
||||
**Exemplo**:
|
||||
- Enviar mensagem no Evolution GO
|
||||
- Aparece instantaneamente no WhatsApp Web
|
||||
- Aparece no celular
|
||||
- Aparece no Desktop
|
||||
|
||||
### 3. Múltiplas Contas Simultâneas
|
||||
|
||||
**Com containers Docker**, você pode ter **N instâncias** do Evolution GO, cada uma conectada a um número WhatsApp diferente:
|
||||
|
||||
```bash
|
||||
docker run -d --name evo-vendas evolution-go
|
||||
docker run -d --name evo-suporte evolution-go
|
||||
docker run -d --name evo-marketing evolution-go
|
||||
```
|
||||
|
||||
Cada container = 1 número WhatsApp separado.
|
||||
|
||||
### 4. Alta Disponibilidade
|
||||
|
||||
**Redundância**: Se um device falha, outros continuam funcionando.
|
||||
|
||||
**Load Balancing**: Distribua carga entre múltiplos Evolution GO instances.
|
||||
|
||||
---
|
||||
|
||||
## Comparação com Versão Antiga
|
||||
|
||||
| Aspecto | Legacy (Web WhatsApp) | Multi-Device (Atual) |
|
||||
|---------|----------------------|----------------------|
|
||||
| **Celular precisa online?** | ✅ Sim, sempre | ❌ Não (após pareamento) |
|
||||
| **Criptografia** | E2EE | E2EE (melhorada) |
|
||||
| **Sincronização** | Relay via celular | Peer-to-peer + servers |
|
||||
| **Histórico** | Depende do celular | 3 meses sincronizados |
|
||||
| **Latência** | Alta (2 hops) | Baixa (direto) |
|
||||
| **Devices simultâneos** | 1 (Web) | 4 companions |
|
||||
| **Chamadas** | Não suportado | Não suportado* |
|
||||
| **Mídia** | Relay via celular | Direct download |
|
||||
|
||||
*Chamadas não suportadas em companion devices (limitação WhatsApp).
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [Conexão QR Code](./qrcode-connection.md) - Processo de pareamento
|
||||
- [Sistema de Eventos](./events-system.md) - Receber eventos Multi-Device
|
||||
- [Instâncias WhatsApp](../conceitos-core/instances.md) - Gerenciamento de devices
|
||||
- [Banco de Dados](../conceitos-core/database.md) - Armazenamento de sessões
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,679 @@
|
||||
# Conexão QR Code
|
||||
|
||||
Como funciona o processo de autenticação via QR Code no Evolution GO.
|
||||
|
||||
## 📋 Índice
|
||||
|
||||
- [Visão Geral](#visão-geral)
|
||||
- [Fluxo de Conexão](#fluxo-de-conexão)
|
||||
- [Geração do QR Code](#geração-do-qr-code)
|
||||
- [Leitura do QR Code](#leitura-do-qr-code)
|
||||
- [Pareamento por Código](#pareamento-por-código)
|
||||
- [Estados da Conexão](#estados-da-conexão)
|
||||
- [Reconexão Automática](#reconexão-automática)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Boas Práticas](#boas-práticas)
|
||||
|
||||
---
|
||||
|
||||
## Visão Geral
|
||||
|
||||
O Evolution GO utiliza o protocolo Multi-Device do WhatsApp para autenticar instâncias. O processo é baseado em QR Code, similar ao WhatsApp Web.
|
||||
|
||||
### Como Funciona
|
||||
|
||||
1. **Gerar QR Code**: O Evolution GO cria um código único
|
||||
2. **Escanear**: Você escaneia o código com o WhatsApp no celular
|
||||
3. **Pareamento**: WhatsApp e Evolution GO trocam chaves de criptografia
|
||||
4. **Sessão Ativa**: Conexão estabelecida e salva no banco de dados
|
||||
|
||||
### Por que QR Code?
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Seguro: chaves criptográficas trocadas de forma protegida
|
||||
- ✅ Não requer senha ou número de telefone
|
||||
- ✅ Suporta múltiplos dispositivos conectados simultaneamente
|
||||
- ✅ Processo simples e rápido
|
||||
|
||||
**Importante**: O WhatsApp não oferece login com usuário e senha para APIs. A autenticação é exclusivamente via QR Code ou código de pareamento.
|
||||
|
||||
---
|
||||
|
||||
## Fluxo de Conexão
|
||||
|
||||
### Diagrama Completo
|
||||
|
||||
```
|
||||
┌──────────────┐ ┌──────────────┐
|
||||
│ Evolution GO │ │ WhatsApp │
|
||||
│ Client │ │ Servers │
|
||||
└──────┬───────┘ └──────┬───────┘
|
||||
│ │
|
||||
│ 1. POST /instance/connect │
|
||||
│────────────────────────┐ │
|
||||
│ │ │
|
||||
│ 2. StartClient() │ │
|
||||
│<───────────────────────┘ │
|
||||
│ │
|
||||
│ 3. Connect WebSocket │
|
||||
│──────────────────────────────────────────────────────>│
|
||||
│ │
|
||||
│ 4. Request QR Code │
|
||||
│──────────────────────────────────────────────────────>│
|
||||
│ │
|
||||
│ 5. QR Code Data (ref + public key) │
|
||||
│<──────────────────────────────────────────────────────│
|
||||
│ │
|
||||
│ 6. Generate PNG QR Code │
|
||||
│────────────┐ │
|
||||
│ │ │
|
||||
│<───────────┘ │
|
||||
│ │
|
||||
│ 7. Save QR to Database (base64|text) │
|
||||
│────────────┐ │
|
||||
│ │ │
|
||||
│<───────────┘ │
|
||||
│ │
|
||||
│ 8. Emit QR_CODE Event │
|
||||
│────────────┐ │
|
||||
│ │ (Webhook/WebSocket) │
|
||||
│<───────────┘ │
|
||||
│ │
|
||||
┌──────▼───────┐ │
|
||||
│ User │ │
|
||||
│ (Smartphone) │ │
|
||||
└──────┬───────┘ │
|
||||
│ │
|
||||
│ 9. Open WhatsApp App │
|
||||
│ → Linked Devices │
|
||||
│ → Scan QR Code │
|
||||
│ │
|
||||
│ 10. Send Pairing Data (encrypted) │
|
||||
│──────────────────────────────────────────────────────>│
|
||||
│ │
|
||||
│ 11. Pairing Success │
|
||||
│<──────────────────────────────────────────────────────│
|
||||
│ │
|
||||
┌──────▼───────┐ │
|
||||
│ Evolution GO │ │
|
||||
└──────┬───────┘ │
|
||||
│ │
|
||||
│ 12. Receive Pairing Success Event │
|
||||
│<──────────────────────────────────────────────────────│
|
||||
│ │
|
||||
│ 13. Generate Identity & Pre-Keys │
|
||||
│────────────┐ │
|
||||
│ │ │
|
||||
│<───────────┘ │
|
||||
│ │
|
||||
│ 14. Save Session to Database │
|
||||
│────────────┐ │
|
||||
│ │ (JID, Keys, Device Info) │
|
||||
│<───────────┘ │
|
||||
│ │
|
||||
│ 15. Update Instance (connected=true, jid=...) │
|
||||
│────────────┐ │
|
||||
│ │ │
|
||||
│<───────────┘ │
|
||||
│ │
|
||||
│ 16. Emit CONNECTED Event │
|
||||
│────────────┐ │
|
||||
│ │ │
|
||||
│<───────────┘ │
|
||||
│ │
|
||||
│ 17. Start Message Sync │
|
||||
│<─────────────────────────────────────────────────────>│
|
||||
│ (bidirectional) │
|
||||
│ │
|
||||
```
|
||||
|
||||
### Passos Detalhados
|
||||
|
||||
#### 1. Conectar Instância
|
||||
|
||||
**API Call**:
|
||||
```bash
|
||||
POST /instance/connect
|
||||
{
|
||||
"instanceName": "vendas"
|
||||
}
|
||||
```
|
||||
|
||||
**Ações**:
|
||||
- Verifica se instância existe no banco
|
||||
- Inicia goroutine com whatsmeow client
|
||||
- Estabelece WebSocket com servidores WhatsApp
|
||||
|
||||
#### 2. Solicitação de QR Code
|
||||
|
||||
O Evolution GO solicita ao WhatsApp um código QR único, que contém:
|
||||
- **Ref**: Referência única que identifica esta tentativa de conexão
|
||||
- **Public Key**: Chave pública para iniciar o pareamento criptografado
|
||||
|
||||
#### 3. Geração da Imagem QR
|
||||
|
||||
**Formato do texto no QR Code**:
|
||||
```
|
||||
versão@ref,chave_pública,segredo,dados_adicionais
|
||||
```
|
||||
|
||||
**Exemplo**:
|
||||
```
|
||||
2@ABC123DEF456,GHI789JKL012MNO345,PQR678STU901VWX234,YZA567
|
||||
```
|
||||
|
||||
**Armazenamento**:
|
||||
O QR Code é convertido em uma imagem PNG, codificada em base64 e salva no banco de dados junto com o texto original.
|
||||
|
||||
#### 4. Exibição do QR Code
|
||||
|
||||
**Via navegador**:
|
||||
```
|
||||
GET /instance/qr?instanceName=vendas
|
||||
```
|
||||
|
||||
**Resposta HTML**:
|
||||
```html
|
||||
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." />
|
||||
```
|
||||
|
||||
**Via API JSON**:
|
||||
```bash
|
||||
GET /instance/qr?instanceName=vendas
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"qrcode": "iVBORw0KGgoAAAANSUhEUgAA...",
|
||||
"code": "2@ABC123,DEF456,GHI789,JKL012"
|
||||
}
|
||||
```
|
||||
|
||||
#### 5. Usuário Escaneia
|
||||
|
||||
**No smartphone**:
|
||||
1. Abre WhatsApp
|
||||
2. Menu → Aparelhos conectados
|
||||
3. Conectar um aparelho
|
||||
4. Escaneia QR Code
|
||||
|
||||
**WhatsApp envia**:
|
||||
- Chaves públicas do device
|
||||
- JID (WhatsApp ID) do número
|
||||
- Device info (modelo, OS)
|
||||
|
||||
#### 6. Pareamento Concluído
|
||||
|
||||
Após o usuário escanear o QR Code:
|
||||
|
||||
1. **Evolution GO recebe confirmação** do WhatsApp
|
||||
2. **Sessão é salva** no banco de dados com:
|
||||
- Chaves de identidade
|
||||
- Chaves pré-geradas
|
||||
- JID (identificador do WhatsApp)
|
||||
- Informações do dispositivo
|
||||
3. **Instância marcada como conectada**
|
||||
4. **Evento CONNECTED** é publicado
|
||||
|
||||
---
|
||||
|
||||
## Geração do QR Code
|
||||
|
||||
### Evento de QR Code
|
||||
|
||||
Quando um QR Code é gerado:
|
||||
|
||||
1. **Texto do QR Code** é recebido do WhatsApp
|
||||
2. **Imagem PNG** é criada a partir do texto
|
||||
3. **Salvo no banco de dados** em formato base64
|
||||
4. **Evento QR_CODE** é publicado para webhooks/websockets configurados
|
||||
|
||||
### Formato do QR
|
||||
|
||||
**Estrutura**:
|
||||
```
|
||||
version@ref,pub_key,secret,adv
|
||||
```
|
||||
|
||||
**Componentes**:
|
||||
- `version`: Versão do protocolo (geralmente `2`)
|
||||
- `ref`: Referência única (identifica esta tentativa de pareamento)
|
||||
- `pub_key`: Chave pública do servidor
|
||||
- `secret`: Segredo compartilhado
|
||||
- `adv`: Dados de advertising (device info)
|
||||
|
||||
**Exemplo real**:
|
||||
```
|
||||
2@12345abcdef,67890ghijk,lmnop12345,qrstu67890
|
||||
```
|
||||
|
||||
### Expiração
|
||||
|
||||
**Tempo de vida**: ~40 segundos
|
||||
|
||||
**Após expiração**:
|
||||
- Whatsmeow emite novo evento QR
|
||||
- Novo QR Code é gerado
|
||||
- Repete até `max_attempts` (padrão: 5 tentativas)
|
||||
|
||||
**Evento de timeout**:
|
||||
```go
|
||||
case *events.QRTimeout:
|
||||
logger.Warn("QR Code expired, generating new one...")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Leitura do QR Code
|
||||
|
||||
### Endpoint HTTP
|
||||
|
||||
**Obter QR Code via API**:
|
||||
```bash
|
||||
GET /instance/qr?instanceName=vendas
|
||||
```
|
||||
|
||||
**Response (JSON)**:
|
||||
```json
|
||||
{
|
||||
"qrcode": "iVBORw0KGgoAAAANSUhEUgAABAA...",
|
||||
"code": "2@12345abcdef,67890ghijk,lmnop12345,qrstu67890"
|
||||
}
|
||||
```
|
||||
|
||||
**Response (HTML)** - Se aceitar `text/html`:
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>QR Code - vendas</title></head>
|
||||
<body>
|
||||
<h1>QR Code - Instância: vendas</h1>
|
||||
<img src="data:image/png;base64,iVBORw0KG..." />
|
||||
<p>Escaneie com WhatsApp</p>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Via WebSocket
|
||||
|
||||
**Conectar**:
|
||||
```javascript
|
||||
const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas');
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
if (data.queue === 'qrcode') {
|
||||
const payload = JSON.parse(data.payload);
|
||||
const qrBase64 = payload.qrcode;
|
||||
|
||||
// Exibir QR Code
|
||||
document.getElementById('qr-img').src =
|
||||
`data:image/png;base64,${qrBase64}`;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Via Webhook
|
||||
|
||||
**Configurar webhook**:
|
||||
```bash
|
||||
POST /instance/connect
|
||||
{
|
||||
"instanceName": "vendas",
|
||||
"webhookUrl": "https://meu-servidor.com/webhook",
|
||||
"subscribe": ["QRCODE"]
|
||||
}
|
||||
```
|
||||
|
||||
**Evento recebido**:
|
||||
```json
|
||||
{
|
||||
"event": "QRCODE",
|
||||
"instance": "vendas",
|
||||
"data": {
|
||||
"qrcode": "iVBORw0KGgoAAAANSUhEUgA...",
|
||||
"code": "2@12345abcdef,67890ghijk,lmnop12345,qrstu67890"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pareamento por Código
|
||||
|
||||
### Alternativa ao QR Code
|
||||
|
||||
Além de QR Code, é possível parear via **código de 8 dígitos**.
|
||||
|
||||
**Endpoint**:
|
||||
```bash
|
||||
POST /instance/pair
|
||||
{
|
||||
"instanceName": "vendas",
|
||||
"phone": "5511999999999"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"pairingCode": "ABCD-1234"
|
||||
}
|
||||
```
|
||||
|
||||
### Como Usar
|
||||
|
||||
**No smartphone**:
|
||||
1. Abre WhatsApp
|
||||
2. Menu → Aparelhos conectados
|
||||
3. Conectar um aparelho
|
||||
4. Link com código de aparelho
|
||||
5. Digita `ABCD-1234`
|
||||
|
||||
**Vantagens**:
|
||||
- ✅ Não precisa de camera/QR scanner
|
||||
- ✅ Mais fácil para compartilhar remotamente
|
||||
|
||||
**Desvantagens**:
|
||||
- ❌ Requer digitação manual
|
||||
- ❌ Menos visual que QR Code
|
||||
|
||||
### Como Funciona
|
||||
|
||||
O Evolution GO gera um código de 8 dígitos único e o retorna na API. Esse código é válido por tempo limitado e pode ser usado uma única vez.
|
||||
|
||||
---
|
||||
|
||||
## Estados da Conexão
|
||||
|
||||
### Máquina de Estados
|
||||
|
||||
```
|
||||
┌─────────────┐
|
||||
│ CREATED │ Instância criada, nunca conectada
|
||||
└──────┬──────┘
|
||||
│ POST /instance/connect
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ CONNECTING │ WebSocket iniciando
|
||||
└──────┬──────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ WAITING_QR │ Aguardando usuário escanear
|
||||
└──────┬──────┘
|
||||
│ Usuário escaneia QR
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ PAIRING │ Trocando chaves criptográficas
|
||||
└──────┬──────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ OPEN │ Conectado e autenticado
|
||||
└──────┬──────┘
|
||||
│
|
||||
│ Erro de conexão ou logout
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ DISCONNECTED│
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
### Eventos Associados
|
||||
|
||||
#### QRCODE
|
||||
```json
|
||||
{
|
||||
"event": "QRCODE",
|
||||
"data": {
|
||||
"qrcode": "base64...",
|
||||
"code": "2@..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### QR_TIMEOUT
|
||||
```json
|
||||
{
|
||||
"event": "QR_TIMEOUT",
|
||||
"data": {
|
||||
"attempts": 1,
|
||||
"maxAttempts": 5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### QR_SUCCESS
|
||||
```json
|
||||
{
|
||||
"event": "QR_SUCCESS",
|
||||
"data": {
|
||||
"jid": "5511999999999@s.whatsapp.net"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### CONNECTED
|
||||
```json
|
||||
{
|
||||
"event": "CONNECTED",
|
||||
"data": {
|
||||
"jid": "5511999999999@s.whatsapp.net",
|
||||
"name": "João Silva",
|
||||
"timestamp": "2025-11-11T10:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reconexão Automática
|
||||
|
||||
### Após Primeiro Pareamento
|
||||
|
||||
Depois do primeiro pareamento bem-sucedido via QR Code:
|
||||
|
||||
1. **Sessão é salva** no banco de dados PostgreSQL
|
||||
2. **Próxima inicialização**: Sessão é carregada automaticamente
|
||||
3. **Conecta diretamente** sem necessidade de novo QR Code
|
||||
|
||||
O Evolution GO mantém várias tabelas para armazenar as informações de sessão e chaves criptográficas necessárias para reconexão.
|
||||
|
||||
### Tentativas de Reconexão
|
||||
|
||||
Se uma conexão cair, o Evolution GO tenta reconectar automaticamente usando estratégia de intervalo crescente:
|
||||
|
||||
- Tentativa 1: 2 segundos
|
||||
- Tentativa 2: 4 segundos
|
||||
- Tentativa 3: 8 segundos
|
||||
- Tentativa 4: 16 segundos
|
||||
- Tentativa 5: 32 segundos
|
||||
|
||||
### Quando é Necessário Novo QR Code
|
||||
|
||||
Em alguns cenários, é necessário gerar um novo QR Code:
|
||||
|
||||
- ❌ Após logout explícito via API
|
||||
- ❌ Dispositivo removido manualmente no app WhatsApp
|
||||
- ❌ Sessão expirada (mais de 14 dias offline)
|
||||
- ❌ Conta temporariamente ou permanentemente bloqueada
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### QR Code não aparece
|
||||
|
||||
**Diagnóstico**:
|
||||
```bash
|
||||
GET /instance/logs/:instanceId?level=ERROR
|
||||
```
|
||||
|
||||
**Causas comuns**:
|
||||
1. Cliente não conectado ao WebSocket
|
||||
2. Firewall bloqueando conexão com WhatsApp servers
|
||||
3. Instância já conectada (não precisa de QR)
|
||||
|
||||
**Solução**:
|
||||
```bash
|
||||
# Forçar reconexão
|
||||
POST /instance/reconnect
|
||||
{
|
||||
"instanceName": "vendas"
|
||||
}
|
||||
```
|
||||
|
||||
### QR Code expira muito rápido
|
||||
|
||||
**Causa**: Delay entre geração e exibição.
|
||||
|
||||
**Solução**: Use WebSocket para receber QR em tempo real.
|
||||
|
||||
```javascript
|
||||
const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas');
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.queue === 'qrcode') {
|
||||
// Exibir imediatamente
|
||||
showQRCode(data.payload.qrcode);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Escaneou QR mas não conectou
|
||||
|
||||
**Diagnóstico**:
|
||||
```bash
|
||||
GET /instance/status?instanceName=vendas
|
||||
```
|
||||
|
||||
**Resposta esperada após scan**:
|
||||
```json
|
||||
{
|
||||
"connected": true,
|
||||
"loggedIn": true,
|
||||
"jid": "5511999999999@s.whatsapp.net"
|
||||
}
|
||||
```
|
||||
|
||||
**Se continuar `connected: false`**:
|
||||
1. Verificar logs de erro
|
||||
2. Tentar logout e novo QR
|
||||
3. Verificar se WhatsApp está atualizado
|
||||
|
||||
### Erro: "too many attempts"
|
||||
|
||||
**Causa**: QR Code expirou 5 vezes.
|
||||
|
||||
**Solução**:
|
||||
```bash
|
||||
# Desconectar
|
||||
POST /instance/disconnect
|
||||
|
||||
# Aguardar 30 segundos
|
||||
|
||||
# Reconectar
|
||||
POST /instance/connect
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Boas Práticas
|
||||
|
||||
### 1. Exibir QR em Tempo Real
|
||||
|
||||
Use WebSocket em vez de polling:
|
||||
|
||||
**❌ Ruim** (polling):
|
||||
```javascript
|
||||
setInterval(() => {
|
||||
fetch('/instance/qr?instanceName=vendas')
|
||||
.then(res => res.json())
|
||||
.then(data => showQR(data.qrcode));
|
||||
}, 5000); // A cada 5 segundos
|
||||
```
|
||||
|
||||
**✅ Bom** (WebSocket):
|
||||
```javascript
|
||||
const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas');
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.queue === 'qrcode') showQR(data.payload.qrcode);
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Feedback Visual
|
||||
|
||||
Mostre estado da conexão para o usuário:
|
||||
|
||||
```javascript
|
||||
ws.onmessage = (event) => {
|
||||
const { queue } = JSON.parse(event.data);
|
||||
|
||||
switch(queue) {
|
||||
case 'qrcode':
|
||||
showStatus('Escaneie o QR Code');
|
||||
break;
|
||||
case 'qr_success':
|
||||
showStatus('QR Code escaneado! Conectando...');
|
||||
break;
|
||||
case 'connected':
|
||||
showStatus('Conectado com sucesso!');
|
||||
break;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 3. Timeout de Inatividade
|
||||
|
||||
Desconecte se QR não for escaneado em tempo razoável:
|
||||
|
||||
```javascript
|
||||
let qrTimeout;
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
if (data.queue === 'qrcode') {
|
||||
// Cancela timeout anterior
|
||||
clearTimeout(qrTimeout);
|
||||
|
||||
// Timeout de 2 minutos
|
||||
qrTimeout = setTimeout(() => {
|
||||
alert('QR Code expirou. Por favor, tente novamente.');
|
||||
ws.close();
|
||||
}, 120000);
|
||||
}
|
||||
|
||||
if (data.queue === 'connected') {
|
||||
clearTimeout(qrTimeout);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 4. Validar Sessão Antes de Solicitar QR
|
||||
|
||||
```bash
|
||||
# Verificar status primeiro
|
||||
GET /instance/status?instanceName=vendas
|
||||
|
||||
# Se já conectado, não precisa de QR
|
||||
# Se desconectado mas tem sessão, tentar reconnect
|
||||
# Só gerar QR se não tem sessão
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Próximos Passos
|
||||
|
||||
- [Multi-Dispositivo](./multi-device.md) - Entender protocolo Multi-Device
|
||||
- [Instâncias WhatsApp](../conceitos-core/instances.md) - Ciclo de vida completo
|
||||
- [Sistema de Eventos](./events-system.md) - Receber eventos de conexão
|
||||
- [API de Instâncias](../guias-api/api-instances.md) - Todos os endpoints
|
||||
|
||||
---
|
||||
|
||||
**Documentação gerada para Evolution GO v1.0**
|
||||
@@ -0,0 +1,184 @@
|
||||
# Referência da API
|
||||
|
||||
Referência rápida de endpoints disponíveis na API Evolution GO.
|
||||
|
||||
## Autenticação
|
||||
|
||||
Todos os endpoints requerem header de autenticação:
|
||||
|
||||
```
|
||||
apikey: SUA-CHAVE-API
|
||||
```
|
||||
|
||||
## Base URL
|
||||
|
||||
```
|
||||
http://localhost:4000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Endpoints por Categoria
|
||||
|
||||
### Instâncias (16 endpoints)
|
||||
|
||||
**Gerenciamento (requer GLOBAL_API_KEY):**
|
||||
- `POST /instance/create` - Criar nova instância
|
||||
- `GET /instance/all` - Listar todas as instâncias
|
||||
- `GET /instance/info/:instanceId` - Detalhes da instância
|
||||
- `DELETE /instance/delete/:instanceId` - Remover instância
|
||||
|
||||
**Operações (requer token da instância):**
|
||||
- `POST /instance/connect` - Iniciar conexão
|
||||
- `GET /instance/status` - Status de conexão
|
||||
- `GET /instance/qr` - Obter QR Code
|
||||
- `POST /instance/pair` - Parear com código
|
||||
- `POST /instance/disconnect` - Desconectar
|
||||
- `POST /instance/reconnect` - Reconectar
|
||||
- `DELETE /instance/logout` - Fazer logout
|
||||
|
||||
**Documentação completa:** [API de Instâncias](../guias-api/api-instances.md)
|
||||
|
||||
---
|
||||
|
||||
### Mensagens (16 endpoints)
|
||||
|
||||
**Envio:**
|
||||
- `POST /send/text` - Mensagem de texto
|
||||
- `POST /send/media` - Mídia (imagem/vídeo/áudio/documento)
|
||||
- `POST /send/link` - Link com preview
|
||||
- `POST /send/location` - Localização
|
||||
- `POST /send/contact` - Contato
|
||||
- `POST /send/poll` - Enquete
|
||||
- `POST /send/sticker` - Sticker
|
||||
- `POST /send/button` - Botões interativos
|
||||
- `POST /send/list` - Lista de opções
|
||||
|
||||
**Operações:**
|
||||
- `POST /message/react` - Reagir à mensagem
|
||||
- `POST /message/markread` - Marcar como lida
|
||||
- `POST /message/edit` - Editar mensagem
|
||||
- `POST /message/delete` - Deletar mensagem
|
||||
- `POST /message/presence` - Status de presença (digitando/gravando)
|
||||
- `POST /message/downloadmedia` - Download de mídia
|
||||
- `POST /message/status` - Status de entrega/leitura
|
||||
|
||||
**Documentação completa:** [API de Mensagens](../guias-api/api-messages.md)
|
||||
|
||||
---
|
||||
|
||||
### Usuários (13 endpoints)
|
||||
|
||||
- `POST /user/info` - Informações do usuário
|
||||
- `POST /user/check` - Verificar número no WhatsApp
|
||||
- `POST /user/avatar` - Obter avatar
|
||||
- `GET /user/contacts` - Listar contatos
|
||||
- `GET /user/privacy` - Configurações de privacidade
|
||||
- `POST /user/privacy` - Atualizar privacidade
|
||||
- `POST /user/block` - Bloquear contato
|
||||
- `POST /user/unblock` - Desbloquear contato
|
||||
- `GET /user/blocklist` - Lista de bloqueados
|
||||
- `POST /user/profilePicture` - Atualizar foto de perfil
|
||||
- `POST /user/profileName` - Atualizar nome
|
||||
- `POST /user/profileStatus` - Atualizar status/recado
|
||||
|
||||
**Documentação completa:** [API de Usuários](../guias-api/api-user.md)
|
||||
|
||||
---
|
||||
|
||||
### Grupos (11 endpoints)
|
||||
|
||||
- `GET /group/list` - Listar grupos
|
||||
- `POST /group/create` - Criar grupo
|
||||
- `POST /group/info` - Informações do grupo
|
||||
- `POST /group/participant` - Gerenciar participantes
|
||||
- `POST /group/photo` - Atualizar foto
|
||||
- `POST /group/name` - Atualizar nome
|
||||
- `POST /group/description` - Atualizar descrição
|
||||
- `POST /group/invitelink` - Gerar link de convite
|
||||
- `POST /group/join` - Entrar via link
|
||||
- `POST /group/leave` - Sair do grupo
|
||||
- `GET /group/myall` - Grupos do usuário
|
||||
|
||||
**Documentação completa:** [API de Grupos](../guias-api/api-groups.md)
|
||||
|
||||
---
|
||||
|
||||
### Chats (7 endpoints)
|
||||
|
||||
- `POST /chat/pin` - Fixar conversa
|
||||
- `POST /chat/unpin` - Desfixar conversa
|
||||
- `POST /chat/archive` - Arquivar
|
||||
- `POST /chat/unarchive` - Desarquivar
|
||||
- `POST /chat/mute` - Silenciar
|
||||
- `POST /chat/unmute` - Reativar notificações
|
||||
- `POST /chat/history-sync` - Sincronizar histórico
|
||||
|
||||
**Documentação completa:** [API de Chats](../guias-api/api-chats.md)
|
||||
|
||||
---
|
||||
|
||||
### Labels (6 endpoints)
|
||||
|
||||
- `POST /label/chat` - Adicionar label ao chat
|
||||
- `POST /label/message` - Adicionar label à mensagem
|
||||
- `POST /label/edit` - Editar label
|
||||
- `GET /label/list` - Listar labels
|
||||
- `POST /unlabel/chat` - Remover label do chat
|
||||
- `POST /unlabel/message` - Remover label da mensagem
|
||||
|
||||
**Documentação completa:** [API de Labels](../guias-api/api-labels.md)
|
||||
|
||||
---
|
||||
|
||||
### Comunidades (3 endpoints)
|
||||
|
||||
- `POST /community/create` - Criar comunidade
|
||||
- `POST /community/add` - Adicionar grupo
|
||||
- `POST /community/remove` - Remover grupo
|
||||
|
||||
**Documentação completa:** [API de Comunidades](../guias-api/api-community.md)
|
||||
|
||||
---
|
||||
|
||||
### Newsletters (6 endpoints)
|
||||
|
||||
- `POST /newsletter/create` - Criar newsletter/canal
|
||||
- `GET /newsletter/list` - Listar newsletters
|
||||
- `POST /newsletter/info` - Informações da newsletter
|
||||
- `POST /newsletter/link` - Gerar link de convite
|
||||
- `POST /newsletter/subscribe` - Inscrever-se
|
||||
- `POST /newsletter/messages` - Listar mensagens
|
||||
|
||||
**Documentação completa:** [API de Newsletters](../guias-api/api-newsletter.md)
|
||||
|
||||
---
|
||||
|
||||
### Chamadas (1 endpoint)
|
||||
|
||||
- `POST /call/reject` - Rejeitar chamada recebida
|
||||
|
||||
**Documentação completa:** [API de Chamadas](../guias-api/api-call.md)
|
||||
|
||||
---
|
||||
|
||||
## Recursos Adicionais
|
||||
|
||||
### Documentação Interativa
|
||||
|
||||
- **Swagger UI**: http://localhost:4000/swagger/index.html (quando servidor estiver rodando)
|
||||
- Teste endpoints diretamente no navegador
|
||||
- Visualize payloads de request/response
|
||||
- Documentação completa com exemplos
|
||||
|
||||
### Guias de API
|
||||
|
||||
- [Visão Geral da API](../guias-api/api-overview.md)
|
||||
- [Autenticação](../conceitos-core/authentication.md)
|
||||
- [Sistema de Eventos](../recursos-avancados/events-system.md)
|
||||
|
||||
---
|
||||
|
||||
**Total de endpoints disponíveis: 79**
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,230 @@
|
||||
# Variáveis de Ambiente
|
||||
|
||||
Referência rápida de variáveis de ambiente do Evolution GO.
|
||||
|
||||
Para documentação detalhada, consulte: [Configuração](../fundamentos/configuration.md)
|
||||
|
||||
---
|
||||
|
||||
## Obrigatórias
|
||||
|
||||
| Variável | Descrição | Exemplo |
|
||||
|----------|-----------|---------|
|
||||
| `GLOBAL_API_KEY` | Chave de autenticação da API | `df16caad-d0d2-41b2-bec5-75b90048a0db` |
|
||||
| `DATABASE_SAVE_MESSAGES` | Salvar mensagens no banco | `false` |
|
||||
|
||||
---
|
||||
|
||||
## Servidor
|
||||
|
||||
| Variável | Padrão | Descrição |
|
||||
|----------|--------|-----------|
|
||||
| `SERVER_PORT` | `4000` | Porta HTTP |
|
||||
| `CLIENT_NAME` | `evolution` | Nome identificador |
|
||||
| `OS_NAME` | `Linux` | Sistema operacional |
|
||||
|
||||
---
|
||||
|
||||
## Banco de Dados
|
||||
|
||||
| Variável | Descrição |
|
||||
|----------|-----------|
|
||||
| `POSTGRES_AUTH_DB` | Connection string banco de autenticação |
|
||||
| `POSTGRES_USERS_DB` | Connection string banco de usuários |
|
||||
|
||||
**Formato:**
|
||||
```env
|
||||
POSTGRES_AUTH_DB=postgresql://user:pass@host:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://user:pass@host:5432/evogo_users?sslmode=disable
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Logs
|
||||
|
||||
| Variável | Padrão | Valores | Descrição |
|
||||
|----------|--------|---------|-----------|
|
||||
| `WADEBUG` | `INFO` | `DEBUG`, `INFO`, `WARN`, `ERROR` | Nível de log |
|
||||
| `LOGTYPE` | `console` | `console`, `file` | Destino de saída |
|
||||
| `LOG_DIRECTORY` | `/app/logs` | - | Diretório de arquivos de log |
|
||||
| `LOG_MAX_SIZE` | `100` | - | Tamanho máximo por arquivo (MB) |
|
||||
| `LOG_MAX_BACKUPS` | `5` | - | Arquivos de backup a manter |
|
||||
| `LOG_MAX_AGE` | `30` | - | Retenção em dias |
|
||||
| `LOG_COMPRESS` | `true` | `true`/`false` | Compressão de logs antigos |
|
||||
|
||||
---
|
||||
|
||||
## Conexão e Comportamento
|
||||
|
||||
| Variável | Padrão | Descrição |
|
||||
|----------|--------|-----------|
|
||||
| `CONNECT_ON_STARTUP` | `false` | Conectar instâncias ao iniciar servidor |
|
||||
| `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 |
|
||||
|
||||
---
|
||||
|
||||
## Eventos
|
||||
|
||||
| Variável | Padrão | Descrição |
|
||||
|----------|--------|-----------|
|
||||
| `EVENT_IGNORE_GROUP` | `false` | Ignorar eventos de grupos |
|
||||
| `EVENT_IGNORE_STATUS` | `true` | Ignorar eventos de status/stories |
|
||||
| `WEBHOOK_URL` | - | URL para callbacks HTTP |
|
||||
|
||||
---
|
||||
|
||||
## RabbitMQ (AMQP)
|
||||
|
||||
| Variável | Descrição |
|
||||
|----------|-----------|
|
||||
| `AMQP_URL` | URL de conexão RabbitMQ |
|
||||
| `AMQP_GLOBAL_ENABLED` | Habilitar filas globais |
|
||||
| `AMQP_GLOBAL_EVENTS` | Eventos a publicar (separados por vírgula) |
|
||||
| `AMQP_SPECIFIC_EVENTS` | Eventos específicos por instância |
|
||||
|
||||
**Exemplo:**
|
||||
```env
|
||||
AMQP_URL=amqp://user:pass@rabbitmq:5672/vhost
|
||||
AMQP_GLOBAL_ENABLED=true
|
||||
AMQP_GLOBAL_EVENTS=messages.upsert,messages.update,connection.update
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## NATS
|
||||
|
||||
| Variável | Descrição |
|
||||
|----------|-----------|
|
||||
| `NATS_URL` | URL de conexão NATS |
|
||||
| `NATS_GLOBAL_ENABLED` | Habilitar publicação global |
|
||||
| `NATS_GLOBAL_EVENTS` | Eventos a publicar |
|
||||
|
||||
**Exemplo:**
|
||||
```env
|
||||
NATS_URL=nats://nats:4222
|
||||
NATS_GLOBAL_ENABLED=true
|
||||
NATS_GLOBAL_EVENTS=messages.upsert,connection.update
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MinIO/S3
|
||||
|
||||
| Variável | Descrição |
|
||||
|----------|-----------|
|
||||
| `MINIO_ENABLED` | Habilitar armazenamento S3-compatible |
|
||||
| `MINIO_ENDPOINT` | Endpoint do servidor |
|
||||
| `MINIO_ACCESS_KEY` | Access Key para autenticação |
|
||||
| `MINIO_SECRET_KEY` | Secret Key para autenticação |
|
||||
| `MINIO_BUCKET` | Nome do bucket |
|
||||
| `MINIO_USE_SSL` | Utilizar HTTPS |
|
||||
| `MINIO_REGION` | Região do bucket (AWS) |
|
||||
|
||||
**Exemplo:**
|
||||
```env
|
||||
MINIO_ENABLED=true
|
||||
MINIO_ENDPOINT=localhost:9000
|
||||
MINIO_ACCESS_KEY=minioadmin
|
||||
MINIO_SECRET_KEY=minioadmin
|
||||
MINIO_BUCKET=evolution-media
|
||||
MINIO_USE_SSL=false
|
||||
MINIO_REGION=us-east-1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Proxy HTTP
|
||||
|
||||
| Variável | Descrição |
|
||||
|----------|-----------|
|
||||
| `PROXY_HOST` | Hostname do proxy |
|
||||
| `PROXY_PORT` | Porta do proxy |
|
||||
| `PROXY_USERNAME` | Usuário (opcional) |
|
||||
| `PROXY_PASSWORD` | Senha (opcional) |
|
||||
|
||||
**Exemplo:**
|
||||
```env
|
||||
PROXY_HOST=proxy.empresa.com
|
||||
PROXY_PORT=8080
|
||||
PROXY_USERNAME=usuario
|
||||
PROXY_PASSWORD=senha
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Recursos Adicionais
|
||||
|
||||
| Variável | Descrição |
|
||||
|----------|-----------|
|
||||
| `API_AUDIO_CONVERTER` | URL de serviço de conversão de áudio |
|
||||
| `API_AUDIO_CONVERTER_KEY` | Chave de autenticação do conversor |
|
||||
|
||||
---
|
||||
|
||||
## Versão WhatsApp (Avançado)
|
||||
|
||||
| Variável | Descrição |
|
||||
|----------|-----------|
|
||||
| `WHATSAPP_VERSION_MAJOR` | Versão major do WhatsApp Web |
|
||||
| `WHATSAPP_VERSION_MINOR` | Versão minor do WhatsApp Web |
|
||||
| `WHATSAPP_VERSION_PATCH` | Versão patch do WhatsApp Web |
|
||||
|
||||
**⚠️ Atenção**: Modificar versão do WhatsApp pode resultar em bloqueio. Deixar vazio para usar versão automática.
|
||||
|
||||
---
|
||||
|
||||
## Exemplo Completo
|
||||
|
||||
```env
|
||||
# Obrigatórias
|
||||
GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
|
||||
# Servidor
|
||||
SERVER_PORT=4000
|
||||
CLIENT_NAME=evolution
|
||||
OS_NAME=Linux
|
||||
|
||||
# Banco de Dados
|
||||
POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable
|
||||
POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable
|
||||
|
||||
# Logs
|
||||
WADEBUG=INFO
|
||||
LOGTYPE=console
|
||||
|
||||
# Comportamento
|
||||
CONNECT_ON_STARTUP=false
|
||||
WEBHOOK_FILES=true
|
||||
CHECK_USER_EXISTS=true
|
||||
EVENT_IGNORE_STATUS=true
|
||||
|
||||
# Webhook
|
||||
WEBHOOK_URL=https://seu-servidor.com/webhook
|
||||
|
||||
# RabbitMQ (opcional)
|
||||
AMQP_URL=amqp://admin:admin@rabbitmq:5672/default
|
||||
AMQP_GLOBAL_ENABLED=true
|
||||
AMQP_GLOBAL_EVENTS=messages.upsert,connection.update
|
||||
|
||||
# MinIO (opcional)
|
||||
MINIO_ENABLED=true
|
||||
MINIO_ENDPOINT=minio:9000
|
||||
MINIO_ACCESS_KEY=minioadmin
|
||||
MINIO_SECRET_KEY=minioadmin
|
||||
MINIO_BUCKET=evolution-media
|
||||
MINIO_USE_SSL=false
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Recursos
|
||||
|
||||
- **[Configuração Detalhada](../fundamentos/configuration.md)** - Documentação completa de cada variável
|
||||
- **[.env.example](https://git.evoai.app/Evolution/evolution-go/blob/main/docker/examples/.env.example)** - Arquivo de exemplo com todas as variáveis
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,274 @@
|
||||
# Códigos de Erro
|
||||
|
||||
Referência de códigos de erro HTTP e mensagens da aplicação.
|
||||
|
||||
## Códigos HTTP
|
||||
|
||||
| Código | Status | Descrição |
|
||||
|--------|--------|-----------|
|
||||
| `200` | OK | Requisição processada com sucesso |
|
||||
| `201` | Created | Recurso criado com sucesso |
|
||||
| `400` | Bad Request | Requisição inválida ou malformada |
|
||||
| `401` | Unauthorized | Autenticação ausente ou inválida |
|
||||
| `403` | Forbidden | Acesso negado ao recurso |
|
||||
| `404` | Not Found | Recurso não encontrado |
|
||||
| `409` | Conflict | Conflito com estado atual do recurso |
|
||||
| `500` | Internal Server Error | Erro interno não tratado |
|
||||
|
||||
---
|
||||
|
||||
## Erros de Autenticação
|
||||
|
||||
### 401 Unauthorized
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Unauthorized"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Header `apikey` ausente ou valor inválido.
|
||||
|
||||
**Resolução**:
|
||||
```bash
|
||||
curl -H "apikey: SUA-CHAVE-API" http://localhost:4000/endpoint
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Erros de Instância
|
||||
|
||||
### 404 Instance Not Found
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Instance not found"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Instância com nome especificado não existe.
|
||||
|
||||
**Resolução**: Verificar nome da instância ou criar nova via `POST /instance/create`.
|
||||
|
||||
### 409 Instance Already Exists
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Instance already exists"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Tentativa de criar instância com nome duplicado.
|
||||
|
||||
**Resolução**: Utilizar nome único ou deletar instância existente.
|
||||
|
||||
### Instance Not Connected
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Instance is not connected"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Operação requer instância conectada ao WhatsApp.
|
||||
|
||||
**Resolução**: Conectar instância via QR Code (`POST /instance/connect`) ou pairing code.
|
||||
|
||||
---
|
||||
|
||||
## Erros de Validação
|
||||
|
||||
### 400 Invalid Phone Number
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Invalid phone number format"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Formato de número incorreto.
|
||||
|
||||
**Resolução**: Utilizar formato internacional sem símbolos.
|
||||
- Correto: `5511999999999` (DDI + DDD + número)
|
||||
- Incorreto: `+55 (11) 99999-9999`, `11999999999`
|
||||
|
||||
### 400 Required Field Missing
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Field 'instanceName' is required"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Campo obrigatório ausente no body da requisição.
|
||||
|
||||
**Resolução**: Incluir campo obrigatório no payload JSON.
|
||||
|
||||
### 400 Invalid JSON
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Invalid JSON"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Sintaxe JSON inválida ou header Content-Type incorreto.
|
||||
|
||||
**Resolução**:
|
||||
- Validar sintaxe JSON
|
||||
- Incluir header: `Content-Type: application/json`
|
||||
|
||||
---
|
||||
|
||||
## Erros de Infraestrutura
|
||||
|
||||
### 500 Database Connection Error
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Database connection failed"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Falha ao conectar com PostgreSQL.
|
||||
|
||||
**Diagnóstico**:
|
||||
```bash
|
||||
# Verificar status do PostgreSQL
|
||||
docker-compose ps postgres
|
||||
|
||||
# Verificar logs
|
||||
docker-compose logs postgres
|
||||
|
||||
# Testar conectividade
|
||||
docker-compose exec evolution-go nc -zv postgres 5432
|
||||
```
|
||||
|
||||
**Resolução**:
|
||||
- Verificar variáveis `POSTGRES_AUTH_DB` e `POSTGRES_USERS_DB`
|
||||
- Confirmar que PostgreSQL está rodando
|
||||
- Validar credenciais de acesso
|
||||
|
||||
### 500 Queue Connection Error
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Failed to connect to message queue"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Falha ao conectar com RabbitMQ/NATS.
|
||||
|
||||
**Resolução**:
|
||||
- Verificar variável `AMQP_URL` ou `NATS_URL`
|
||||
- Confirmar que serviço de fila está rodando
|
||||
- Validar credenciais e permissões
|
||||
|
||||
---
|
||||
|
||||
## Erros de Negócio
|
||||
|
||||
### User Not Found on WhatsApp
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "User not found on WhatsApp"
|
||||
}
|
||||
```
|
||||
|
||||
**Causa**: Número destinatário não está registrado no WhatsApp.
|
||||
|
||||
**Resolução**: Verificar número ou desabilitar validação (`CHECK_USER_EXISTS=false`).
|
||||
|
||||
### Message Send Failed
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Failed to send message",
|
||||
"details": "..."
|
||||
}
|
||||
```
|
||||
|
||||
**Causas comuns**:
|
||||
- Número bloqueou sua instância
|
||||
- Mensagem violou políticas do WhatsApp
|
||||
- Instância foi bloqueada/banida
|
||||
- Problema de conectividade
|
||||
|
||||
**Diagnóstico**:
|
||||
```bash
|
||||
# Verificar logs detalhados
|
||||
docker-compose logs -f evolution-go
|
||||
|
||||
# Verificar status da instância
|
||||
curl -H "apikey: SUA-CHAVE" \
|
||||
"http://localhost:4000/instance/status?instanceName=NOME"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Debugging
|
||||
|
||||
### Habilitar Logs Detalhados
|
||||
|
||||
```env
|
||||
WADEBUG=DEBUG
|
||||
```
|
||||
|
||||
### Verificar Logs
|
||||
|
||||
```bash
|
||||
# Docker Compose
|
||||
docker-compose logs -f evolution-go
|
||||
|
||||
# Docker (container específico)
|
||||
docker logs -f evolution-go --tail=100
|
||||
|
||||
# Arquivo (se LOGTYPE=file)
|
||||
tail -f logs/evolution-go.log
|
||||
```
|
||||
|
||||
### Logs Estruturados
|
||||
|
||||
Logs incluem:
|
||||
- **Timestamp**: Data/hora do evento
|
||||
- **Level**: DEBUG, INFO, WARN, ERROR
|
||||
- **Module**: Componente que gerou o log
|
||||
- **Message**: Descrição do evento
|
||||
- **Context**: Dados adicionais (instanceName, userId, etc)
|
||||
|
||||
---
|
||||
|
||||
## Códigos de Erro por Categoria
|
||||
|
||||
### Autenticação (401, 403)
|
||||
- API key inválida
|
||||
- Token expirado
|
||||
- Permissões insuficientes
|
||||
|
||||
### Validação (400)
|
||||
- JSON malformado
|
||||
- Campos obrigatórios ausentes
|
||||
- Formato inválido
|
||||
|
||||
### Recurso (404, 409)
|
||||
- Instância não encontrada
|
||||
- Recurso duplicado
|
||||
- Estado inconsistente
|
||||
|
||||
### Servidor (500, 503)
|
||||
- Erro de banco de dados
|
||||
- Timeout de operação
|
||||
- Serviço indisponível
|
||||
|
||||
---
|
||||
|
||||
## Recursos Adicionais
|
||||
|
||||
- **[Debugging](../desenvolvimento/debugging.md)** - Guia completo de debugging
|
||||
- **[FAQ](./faq.md)** - Problemas comuns e soluções
|
||||
- **[Logs](../fundamentos/configuration.md#logs-e-debug)** - Configuração de logs
|
||||
|
||||
---
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
@@ -0,0 +1,274 @@
|
||||
# FAQ - Perguntas Frequentes
|
||||
|
||||
Respostas para questões comuns sobre o Evolution GO.
|
||||
|
||||
## Visão Geral
|
||||
|
||||
### O que é Evolution GO?
|
||||
|
||||
Gateway de API WhatsApp construído em Go que fornece interface RESTful para comunicação com o protocolo WhatsApp Web. Permite automação de mensagens, gerenciamento multi-instância e integração via APIs padronizadas.
|
||||
|
||||
### Diferença entre Evolution GO e Evolution API (Node.js)?
|
||||
|
||||
- **Evolution GO**: Implementação em Go, foco em performance e baixo consumo de recursos
|
||||
- **Evolution API V2**: Implementação em Node.js/TypeScript, maior maturidade e conjunto de features
|
||||
|
||||
Ambos utilizam a biblioteca whatsmeow para conexão com WhatsApp.
|
||||
|
||||
### Suporte a múltiplas instâncias?
|
||||
|
||||
Sim. É possível gerenciar quantas instâncias forem necessárias, cada uma representando uma conta WhatsApp independente com sessão isolada.
|
||||
|
||||
---
|
||||
|
||||
## Instalação
|
||||
|
||||
### SQLite vs PostgreSQL
|
||||
|
||||
**PostgreSQL** é fortemente recomendado para produção devido a:
|
||||
- Performance superior em ambientes multiusuário
|
||||
- Suporte a conexões concorrentes
|
||||
- Recursos empresariais (replicação, backup incremental)
|
||||
|
||||
SQLite é adequado apenas para desenvolvimento/testes.
|
||||
|
||||
### Geração de API Key
|
||||
|
||||
```bash
|
||||
# UUID v4 (recomendado)
|
||||
uuidgen
|
||||
|
||||
# OpenSSL
|
||||
openssl rand -hex 32
|
||||
|
||||
# Python
|
||||
python3 -c "import uuid; print(uuid.uuid4())"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Operações
|
||||
|
||||
### Processo de Conexão
|
||||
|
||||
1. Criar instância: `POST /instance/create`
|
||||
2. Iniciar conexão: `POST /instance/connect`
|
||||
3. Obter QR Code: `GET /instance/qr?instanceName=NOME`
|
||||
4. Escanear QR Code no WhatsApp (Aparelhos Conectados)
|
||||
5. Aguardar estabelecimento da conexão
|
||||
|
||||
### Validade do QR Code
|
||||
|
||||
Aproximadamente 40 segundos. Após expiração, novo QR Code é gerado automaticamente até atingir `QRCODE_MAX_COUNT` (padrão: 5 tentativas).
|
||||
|
||||
### Envio para Múltiplos Destinatários
|
||||
|
||||
Realizar requisições individuais para cada destinatário. Para volume alto:
|
||||
- Implementar fila de envio
|
||||
- Adicionar delay entre requisições (2-5 segundos recomendado)
|
||||
- Utilizar worker pool para paralelização controlada
|
||||
|
||||
### Limites de Envio
|
||||
|
||||
O WhatsApp não divulga limites oficiais, mas observa-se:
|
||||
- Aproximadamente 1000 mensagens/dia para números não salvos
|
||||
- Risco de bloqueio com padrões identificados como spam
|
||||
- Recomendações:
|
||||
- Começar com volume baixo (~100/dia)
|
||||
- Escalar gradualmente
|
||||
- Personalizar mensagens
|
||||
- Evitar conteúdo idêntico em massa
|
||||
- Respeitar opt-out de usuários
|
||||
|
||||
### Recepção de Mensagens
|
||||
|
||||
Configure webhook ao criar instância ou via atualização:
|
||||
|
||||
```json
|
||||
{
|
||||
"instanceName": "nome-instancia",
|
||||
"webhook": "https://seu-servidor.com/webhook"
|
||||
}
|
||||
```
|
||||
|
||||
Eventos serão enviados via POST HTTP para o endpoint configurado.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### QR Code Não Exibido
|
||||
|
||||
**Diagnóstico**:
|
||||
```bash
|
||||
docker-compose logs -f evolution-go
|
||||
```
|
||||
|
||||
**Soluções**:
|
||||
- Verificar conectividade com banco de dados
|
||||
- Deletar e recriar instância
|
||||
- Verificar logs para erros específicos
|
||||
|
||||
### Falha no Envio de Mensagens
|
||||
|
||||
**Verificações**:
|
||||
1. Status da conexão: `GET /instance/status?instanceName=NOME`
|
||||
2. Formato do número: DDI + DDD + número (ex: `5511999999999`)
|
||||
3. Validação do destinatário: `CHECK_USER_EXISTS=true`
|
||||
|
||||
### Desconexão Espontânea
|
||||
|
||||
**Causas comuns**:
|
||||
- WhatsApp Web ativo em outro dispositivo
|
||||
- Bloqueio preventivo do WhatsApp
|
||||
- Instabilidade de rede
|
||||
- Versão do protocolo desatualizada
|
||||
|
||||
**Resolução**: Reconectar via `POST /instance/reconnect`
|
||||
|
||||
### Webhook Não Recebe Eventos
|
||||
|
||||
**Verificações**:
|
||||
- URL acessível publicamente (não localhost)
|
||||
- Endpoint retorna status 200
|
||||
- Firewall/proxy não bloqueando
|
||||
- Logs: `docker-compose logs -f evolution-go | grep webhook`
|
||||
|
||||
---
|
||||
|
||||
## Performance
|
||||
|
||||
### Capacidade por Servidor
|
||||
|
||||
Estimativas baseadas em uso típico:
|
||||
|
||||
| RAM | CPU | Instâncias Estimadas |
|
||||
|-----|-----|---------------------|
|
||||
| 1GB | 1 core | 5-10 |
|
||||
| 2GB | 2 cores | 20-30 |
|
||||
| 4GB | 4 cores | 50-100 |
|
||||
| 8GB | 8 cores | 200+ |
|
||||
|
||||
**Fatores de impacto**:
|
||||
- Volume de mensagens
|
||||
- Uso de webhook vs filas
|
||||
- `DATABASE_SAVE_MESSAGES` habilitado
|
||||
- Processamento de mídia
|
||||
|
||||
### Otimização
|
||||
|
||||
**Configuração**:
|
||||
```env
|
||||
# Desabilitar salvamento de mensagens
|
||||
DATABASE_SAVE_MESSAGES=false
|
||||
|
||||
# Ignorar eventos desnecessários
|
||||
EVENT_IGNORE_STATUS=true
|
||||
EVENT_IGNORE_GROUP=false # conforme necessidade
|
||||
|
||||
# Usar PostgreSQL
|
||||
POSTGRES_AUTH_DB=postgresql://...
|
||||
POSTGRES_USERS_DB=postgresql://...
|
||||
```
|
||||
|
||||
**Infraestrutura**:
|
||||
- Connection pooling adequado
|
||||
- Índices de banco otimizados
|
||||
- Escalabilidade horizontal (múltiplos servidores)
|
||||
- Load balancer para distribuição
|
||||
|
||||
---
|
||||
|
||||
## Segurança
|
||||
|
||||
### Proteção de API Key
|
||||
|
||||
- Não versionar no controle de código
|
||||
- Utilizar variáveis de ambiente
|
||||
- Rotação periódica (recomendado: 90 dias)
|
||||
- HTTPS obrigatório em produção
|
||||
- Rate limiting por chave
|
||||
|
||||
### Armazenamento de Mensagens
|
||||
|
||||
Configurar `DATABASE_SAVE_MESSAGES=false` se histórico não for necessário:
|
||||
- Reduz uso de storage
|
||||
- Melhora privacidade
|
||||
- Aumenta performance
|
||||
|
||||
### Backup Seguro
|
||||
|
||||
```bash
|
||||
# Backup com criptografia
|
||||
docker exec postgres pg_dumpall -U postgres | \
|
||||
gzip | \
|
||||
gpg --encrypt --recipient seu@email.com \
|
||||
> backup-$(date +%Y%m%d).sql.gz.gpg
|
||||
|
||||
# Restauração
|
||||
gpg --decrypt backup-20250111.sql.gz.gpg | \
|
||||
gunzip | \
|
||||
docker exec -i postgres psql -U postgres
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Limitações do WhatsApp
|
||||
|
||||
### Envio para Números Não Salvos
|
||||
|
||||
WhatsApp limita envios para números não salvos na agenda. Boas práticas:
|
||||
- Priorizar números salvos
|
||||
- Aguardar resposta antes de enviar mais mensagens
|
||||
- Evitar volume alto para números desconhecidos
|
||||
|
||||
### Prevenção de Banimento
|
||||
|
||||
**Práticas recomendadas**:
|
||||
- Não enviar spam
|
||||
- Respeitar opt-out de usuários
|
||||
- Usar contas WhatsApp Business verificadas
|
||||
- Adicionar delay entre mensagens
|
||||
- Personalizar conteúdo
|
||||
|
||||
**Em caso de bloqueio**:
|
||||
- Utilizar número diferente
|
||||
- Considerar WhatsApp Business API oficial
|
||||
- Revisar práticas de envio
|
||||
|
||||
---
|
||||
|
||||
## Desenvolvimento
|
||||
|
||||
### Contribuição
|
||||
|
||||
Consulte [Guia de Contribuição](../desenvolvimento/contributing.md) para processo de contribuição ao projeto.
|
||||
|
||||
### Reporte de Bugs
|
||||
|
||||
Utilize [Issues no GitLab](https://git.evoai.app/Evolution/evolution-go/issues) incluindo:
|
||||
- Versão do Evolution GO
|
||||
- Ambiente (Docker/local, SO)
|
||||
- Steps to reproduce
|
||||
- Logs relevantes
|
||||
- Comportamento esperado vs observado
|
||||
|
||||
---
|
||||
|
||||
## Recursos
|
||||
|
||||
### Documentação
|
||||
- [Guia de Instalação](../fundamentos/installation.md)
|
||||
- [Configuração](../fundamentos/configuration.md)
|
||||
- [Referência de API](./api-reference.md)
|
||||
- [Swagger UI](http://localhost:4000/swagger/index.html)
|
||||
|
||||
### Suporte
|
||||
- [Issues GitLab](https://git.evoai.app/Evolution/evolution-go/issues)
|
||||
- [Documentação Completa](https://git.evoai.app/Evolution/evolution-go/-/wikis)
|
||||
|
||||
---
|
||||
|
||||
**Não encontrou resposta?** Abra uma [issue](https://git.evoai.app/Evolution/evolution-go/issues) com sua questão.
|
||||
|
||||
**Documentação Evolution GO v1.0**
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,101 @@
|
||||
module github.com/evolution-foundation/evolution-go
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/chai2010/webp v1.1.1
|
||||
github.com/gabriel-vasile/mimetype v1.4.5
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/gomessguii/logger v0.0.3
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/lib/pq v1.10.9
|
||||
github.com/minio/minio-go/v7 v7.0.80
|
||||
github.com/nats-io/nats.go v1.39.0
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/rabbitmq/amqp091-go v1.10.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.0
|
||||
github.com/swaggo/swag v1.16.3
|
||||
github.com/vincent-petithory/dataurl v1.0.0
|
||||
go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f
|
||||
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410
|
||||
golang.org/x/net v0.61.0
|
||||
google.golang.org/protobuf v1.36.12
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gorm.io/driver/postgres v1.5.9
|
||||
gorm.io/gorm v1.25.10
|
||||
modernc.org/sqlite v1.33.1
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/beeper/argo-go v1.1.2 // indirect
|
||||
github.com/bytedance/sonic v1.12.2 // indirect
|
||||
github.com/bytedance/sonic/loader v0.2.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
||||
github.com/go-openapi/jsonreference v0.21.0 // indirect
|
||||
github.com/go-openapi/spec v0.21.0 // indirect
|
||||
github.com/go-openapi/swag v0.23.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.22.0 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/nats-io/nkeys v0.4.9 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rogpeppe/go-internal v1.12.0 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/rs/zerolog v1.35.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/vektah/gqlparser/v2 v2.5.27 // indirect
|
||||
go.mau.fi/libsignal v0.2.2 // indirect
|
||||
go.mau.fi/util v0.11.0 // indirect
|
||||
golang.org/x/arch v0.10.0 // indirect
|
||||
golang.org/x/crypto v0.58.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
golang.org/x/tools v0.52.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.8.0 // indirect
|
||||
modernc.org/strutil v1.2.0 // indirect
|
||||
modernc.org/token v1.1.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,276 @@
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||
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/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=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs=
|
||||
github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4=
|
||||
github.com/bytedance/sonic v1.12.2 h1:oaMFuRTpMHYLpCntGca65YWt5ny+wAceDERTkT2L9lg=
|
||||
github.com/bytedance/sonic v1.12.2/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM=
|
||||
github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/chai2010/webp v1.1.1 h1:jTRmEccAJ4MGrhFOrPMpNGIJ/eybIgwKpcACsrTEapk=
|
||||
github.com/chai2010/webp v1.1.1/go.mod h1:0XVwvZWdjjdxpUEIf7b9g9VkHFnInUSYujwqTLEuldU=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg=
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=
|
||||
github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4=
|
||||
github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4=
|
||||
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
|
||||
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
||||
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
||||
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
|
||||
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
|
||||
github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=
|
||||
github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=
|
||||
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.22.0 h1:k6HsTZ0sTnROkhS//R0O+55JgM8C4Bx7ia+JlgcnOao=
|
||||
github.com/go-playground/validator/v10 v10.22.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/gomessguii/logger v0.0.3 h1:985MqDkp2Fi6IQ3eQ3NG7VXZo8flbWd+6QUj9hASWJA=
|
||||
github.com/gomessguii/logger v0.0.3/go.mod h1:JBfDf2h4qUFaIjpE/0T4/jeLpIHopc73k+G9+iu9+ms=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
|
||||
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdog8U=
|
||||
github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.80 h1:2mdUHXEykRdY/BigLt3Iuu1otL0JTogT0Nmltg0wujk=
|
||||
github.com/minio/minio-go/v7 v7.0.80/go.mod h1:84gmIilaX4zcvAWWzJ5Z1WI5axN+hAbM5w25xf8xvC0=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/nats-io/nats.go v1.39.0 h1:2/yg2JQjiYYKLwDuBzV0FbB2sIV+eFNkEevlRi4n9lI=
|
||||
github.com/nats-io/nats.go v1.39.0/go.mod h1:MgRb8oOdigA6cYpEPhXJuRVH6UE/V4jblJ2jQ27IXYM=
|
||||
github.com/nats-io/nkeys v0.4.9 h1:qe9Faq2Gxwi6RZnZMXfmGMZkg3afLLOtrU+gDZJ35b0=
|
||||
github.com/nats-io/nkeys v0.4.9/go.mod h1:jcMqs+FLG+W5YO36OX6wFIFcmpdAns+w1Wm6D3I/evE=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
|
||||
github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b h1:OzNsuVdSWGwXvWKTtChx9ve89k4cFJ6NxYM4Aw4/f+E=
|
||||
github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
|
||||
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
|
||||
github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
|
||||
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
|
||||
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
|
||||
github.com/swaggo/gin-swagger v1.6.0 h1:y8sxvQ3E20/RCyrXeFfg60r6H0Z+SwpTjMYsMm+zy8M=
|
||||
github.com/swaggo/gin-swagger v1.6.0/go.mod h1:BG00cCEy294xtVpyIAHG6+e2Qzj/xKlRdOqDkvq0uzo=
|
||||
github.com/swaggo/swag v1.16.3 h1:PnCYjPCah8FK4I26l2F/KQ4yz3sILcVUN3cTlBFA9Pg=
|
||||
github.com/swaggo/swag v1.16.3/go.mod h1:DImHIuOFXKpMFAQjcC7FG4m3Dg4+QuUgUzJmKjI/gRk=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s=
|
||||
github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo=
|
||||
github.com/vincent-petithory/dataurl v1.0.0 h1:cXw+kPto8NLuJtlMsI152irrVw9fRDX8AbShPRpg2CI=
|
||||
github.com/vincent-petithory/dataurl v1.0.0/go.mod h1:FHafX5vmDzyP+1CQATJn7WFKc9CvnvxyvZy6I1MrG/U=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.mau.fi/libsignal v0.2.2 h1:QV+XdzQkm3x3aSG7FcqfGSZuFXz83pRZPBFaPygHbOU=
|
||||
go.mau.fi/libsignal v0.2.2/go.mod h1:CRlIQg2J8uYTfDFvNoO8/KcZjs5cey0vbc6oj/bssY0=
|
||||
go.mau.fi/util v0.11.0 h1:JNEpkVRxfTdJUC0DIGKiRlLKzl4G/qLX/eVzoP7QuwY=
|
||||
go.mau.fi/util v0.11.0/go.mod h1:04AEFVsc4zNdIkDC1gkdqbg/nZFolHY50pyXh2DSy7s=
|
||||
go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f h1:UFm189GiALMSjhuywDHDQhRdhH6y8AD+eaGn5C75B1w=
|
||||
go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f/go.mod h1:iY4lm61nTLWsNiIE1EmHUZwhKGBeoV4dhnVE2uMtNoQ=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8=
|
||||
golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A=
|
||||
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
|
||||
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
|
||||
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
|
||||
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
|
||||
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
||||
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
|
||||
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
|
||||
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
|
||||
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
|
||||
modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
|
||||
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
|
||||
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
|
||||
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
|
||||
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
|
||||
modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
|
||||
modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
|
||||
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
|
||||
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
|
||||
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
|
||||
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
|
||||
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
|
||||
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
|
||||
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
|
||||
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
|
||||
modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM=
|
||||
modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k=
|
||||
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
|
||||
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
+1
@@ -0,0 +1 @@
|
||||
@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-100: oklch(93.6% .032 17.717);--color-red-500: oklch(63.7% .237 25.331);--color-red-600: oklch(57.7% .245 27.325);--color-red-700: oklch(50.5% .213 27.518);--color-red-800: oklch(44.4% .177 26.899);--color-orange-100: oklch(95.4% .038 75.164);--color-orange-500: oklch(70.5% .213 47.604);--color-orange-600: oklch(64.6% .222 41.116);--color-orange-700: oklch(55.3% .195 38.402);--color-yellow-100: oklch(97.3% .071 103.193);--color-yellow-400: oklch(85.2% .199 91.936);--color-yellow-500: oklch(79.5% .184 86.047);--color-yellow-600: oklch(68.1% .162 75.834);--color-yellow-700: oklch(55.4% .135 66.442);--color-green-50: oklch(98.2% .018 155.826);--color-green-100: oklch(96.2% .044 156.743);--color-green-200: oklch(92.5% .084 155.995);--color-green-400: oklch(79.2% .209 151.711);--color-green-500: oklch(72.3% .219 149.579);--color-green-600: oklch(62.7% .194 149.214);--color-green-700: oklch(52.7% .154 150.069);--color-green-800: oklch(44.8% .119 151.328);--color-blue-50: oklch(97% .014 254.604);--color-blue-100: oklch(93.2% .032 255.585);--color-blue-200: oklch(88.2% .059 254.128);--color-blue-400: oklch(70.7% .165 254.624);--color-blue-500: oklch(62.3% .214 259.815);--color-blue-600: oklch(54.6% .245 262.881);--color-blue-700: oklch(48.8% .243 264.376);--color-blue-800: oklch(42.4% .199 265.638);--color-blue-900: oklch(37.9% .146 265.522);--color-purple-50: oklch(97.7% .014 308.299);--color-purple-100: oklch(94.6% .033 307.174);--color-purple-200: oklch(90.2% .063 306.703);--color-purple-500: oklch(62.7% .265 303.9);--color-purple-600: oklch(55.8% .288 302.321);--color-purple-700: oklch(49.6% .265 301.924);--color-purple-900: oklch(38.1% .176 304.987);--color-pink-50: oklch(97.1% .014 343.198);--color-pink-500: oklch(65.6% .241 354.308);--color-pink-600: oklch(59.2% .249 .584);--color-slate-50: oklch(98.4% .003 247.858);--color-slate-800: oklch(27.9% .041 260.031);--color-slate-900: oklch(20.8% .042 265.755);--color-gray-400: oklch(70.7% .022 261.325);--color-gray-600: oklch(44.6% .03 256.802);--color-gray-700: oklch(37.3% .034 259.733);--color-gray-900: oklch(21% .034 264.665);--color-black: #000;--color-white: #fff;--spacing: .25rem;--container-xs: 20rem;--container-sm: 24rem;--container-md: 28rem;--container-lg: 32rem;--container-2xl: 42rem;--container-4xl: 56rem;--container-6xl: 72rem;--text-xs: .75rem;--text-xs--line-height: calc(1 / .75);--text-sm: .875rem;--text-sm--line-height: calc(1.25 / .875);--text-base: 1rem;--text-base--line-height: 1.5 ;--text-lg: 1.125rem;--text-lg--line-height: calc(1.75 / 1.125);--text-xl: 1.25rem;--text-xl--line-height: calc(1.75 / 1.25);--text-2xl: 1.5rem;--text-2xl--line-height: calc(2 / 1.5);--text-3xl: 1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl: 2.25rem;--text-4xl--line-height: calc(2.5 / 2.25);--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--font-weight-bold: 700;--tracking-tight: -.025em;--tracking-widest: .1em;--leading-tight: 1.25;--leading-snug: 1.375;--leading-relaxed: 1.625;--radius-xs: .125rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--animate-pulse: pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--aspect-video: 16 / 9;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-background: var(--background);--color-foreground: var(--foreground);--color-primary: var(--primary);--color-primary-foreground: var(--primary-foreground);--color-secondary: var(--secondary);--color-secondary-foreground: var(--secondary-foreground);--color-muted: var(--muted);--color-muted-foreground: var(--muted-foreground);--color-accent: var(--accent);--color-accent-foreground: var(--accent-foreground);--color-destructive: var(--destructive);--color-destructive-foreground: var(--destructive-foreground);--color-border: var(--border);--color-input: var(--input);--color-ring: var(--ring)}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1Line truncated
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
var kC=Object.defineProperty;var OC=(t,n,r)=>n in t?kC(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r;var gb=(t,n,r)=>OC(t,typeof n!="symbol"?n+"":n,r);function MC(t,n){for(var r=0;r<n.length;r++){const s=n[r];if(typeof s!="string"&&!Array.isArray(s)){for(const i in s)if(i!=="default"&&!(i in t)){const c=Object.getOwnPropertyDescriptor(s,i);c&&Object.defineProperty(t,i,c.get?c:{enumerable:!0,get:()=>s[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&s(u)}).observe(document,{childList:!0,subtree:!0});function r(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(i){if(i.ep)return;i.ep=!0;const c=r(i);fetch(i.href,c)}})();function N0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var dm={exports:{}},Vi={};/**
|
||||
* @license React
|
||||
* react-jsx-runtime.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/var yb;function DC(){if(yb)return Vi;yb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(s,i,c){var u=null;if(c!==void 0&&(u=""+c),i.key!==void 0&&(u=""+i.key),"key"in i){c={};for(var f in i)f!=="key"&&(c[f]=i[f])}else c=i;return i=c.ref,{$$typeof:t,type:s,key:u,ref:i!==void 0?i:null,props:c}}return Vi.Fragment=n,Vi.jsx=r,Vi.jsxs=r,Vi}var vb;function zC(){return vb||(vb=1,dm.exports=DC()),dm.exports}var m=zC(),fm={exports:{}},Ye={};/**
|
||||
* @license React
|
||||
* react.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/var bb;function LC(){if(bb)return Ye;bb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),w=Symbol.iterator;function C(T){return T===null||typeof T!="object"?null:(T=w&&T[w]||T["@@iterator"],typeof T=="function"?T:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,_={};function R(T,V,L){this.props=T,this.context=V,this.refs=_,this.updater=L||S}R.prototype.isReactComponent={},R.prototype.setState=function(T,V){if(typeof T!="object"&&typeof T!="function"&&T!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,T,V,"setState")},R.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function O(){}O.prototype=R.prototype;function A(T,V,L){this.props=T,this.context=V,this.refs=_,this.updater=L||S}var D=A.prototype=new O;D.constructor=A,E(D,R.prototype),D.isPureReactComponent=!0;var B=Array.isArray;function I(){}var U={H:null,A:null,T:null,S:null},$=Object.prototype.hasOwnProperty;function me(T,V,L){var K=L.ref;return{$$typeof:t,type:T,key:V,ref:K!==void 0?K:null,props:L}}function fe(T,V){return me(T.type,V,T.props)}function pe(T){return typeof T=="object"&&T!==null&&T.$$typeof===t}function re(T){var V={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(L){return V[L]})}var Y=/\/+/g;function ue(T,V){return typeof T=="object"&&T!==null&&T.key!=null?re(""+T.key):V.toString(36)}function ye(T){switch(T.status){case"fulfilled":return T.value;case"rejected":throw T.reason;default:switch(typeof T.status=="string"?T.then(I,I):(T.status="pending",T.then(function(V){T.status==="pending"&&(T.status="fulfilled",T.value=V)},function(V){T.status==="pending"&&(T.status="rejected",T.reason=V)})),T.status){case"fulfilled":return T.value;case"rejected":throw T.reason}}throw T}function j(T,V,L,K,W){var le=typeof T;(le==="undefined"||le==="boolean")&&(T=null);var ge=!1;if(T===null)ge=!0;else switch(le){case"bigint":case"string":case"number":ge=!0;break;case"object":switch(T.$$typeof){case t:case n:ge=!0;break;case v:return ge=T._init,j(ge(T._payload),V,L,K,W)}}if(ge)return W=W(T),ge=K===""?"."+ue(T,0):K,B(W)?(L="",ge!=null&&(L=ge.replace(Y,"$&/")+"/"),j(W,V,L,"",function(Ee){return Ee})):W!=null&&(pe(W)&&(W=fe(W,L+(W.key==null||T&&T.key===W.key?"":(""+W.key).replace(Y,"$&/")+"/")+ge)),V.push(W)),1;ge=0;var q=K===""?".":K+":";if(B(T))for(var ae=0;ae<T.length;ae++)K=T[ae],le=q+ue(K,ae),ge+=j(K,V,L,le,W);else if(ae=C(T),typeof ae=="function")for(T=ae.call(T),ae=0;!(K=T.next()).done;)K=K.value,le=q+ue(K,ae++),ge+=j(K,V,L,le,W);else if(le==="object"){if(typeof T.then=="function")return j(ye(T),V,L,K,W);throw V=String(T),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys(T).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.")}return ge}function X(T,V,L){if(T==null)return T;var K=[],W=0;return j(T,K,"","",function(le){return V.call(L,le,W++)}),K}function te(T){if(T._status===-1){var V=T._result;V=V(),V.then(function(L){(T._status===0||T._status===-1)&&(T._status=1,T._result=L)},function(L){(T._status===0||T._status===-1)&&(T._status=2,T._result=L)}),T._status===-1&&(T._status=0,T._result=V)}if(T._status===1)return T._result.default;throw T._result}var se=typeof reportError=="function"?reportError:function(T){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var V=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof T=="object"&&T!==null&&typeof T.message=="string"?String(T.message):String(T),error:T});if(!window.dispatchEvent(V))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",T);return}console.error(T)},ne={map:X,forEach:function(T,V,L){X(T,function(){V.apply(this,arguments)},L)},count:function(T){var V=0;return X(T,function(){V++}),V},toArray:function(T){return X(T,function(V){return V})||[]},only:function(T){if(!pe(T))throw Error("React.Children.only expected to receive a single React element child.");return T}};return Ye.Activity=y,Ye.Children=ne,Ye.Component=R,Ye.Fragment=r,Ye.Profiler=i,Ye.PureComponent=A,Ye.StrictMode=s,Ye.Suspense=g,Ye.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=U,Ye.__COMPILER_RUNTIME={__proto__:null,c:function(T){return U.H.useMemoCache(T)}},Ye.cache=function(T){return function(){return T.apply(null,arguments)}},Ye.cacheSignal=function(){return null},Ye.cloneElement=function(T,V,L){if(T==null)throw Error("The argument must be
Line truncated
|
||||
* @license React
|
||||
* scheduler.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/var wb;function UC(){return wb||(wb=1,(function(t){function n(j,X){var te=j.length;j.push(X);e:for(;0<te;){var se=te-1>>>1,ne=j[se];if(0<i(ne,X))j[se]=X,j[te]=ne,te=se;else break e}}function r(j){return j.length===0?null:j[0]}function s(j){if(j.length===0)return null;var X=j[0],te=j.pop();if(te!==X){j[0]=te;e:for(var se=0,ne=j.length,T=ne>>>1;se<T;){var V=2*(se+1)-1,L=j[V],K=V+1,W=j[K];if(0>i(L,te))K<ne&&0>i(W,L)?(j[se]=W,j[K]=te,se=K):(j[se]=L,j[V]=te,se=V);else if(K<ne&&0>i(W,te))j[se]=W,j[K]=te,se=K;else break e}}return X}function i(j,X){var te=j.sortIndex-X.sortIndex;return te!==0?te:j.id-X.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;t.unstable_now=function(){return c.now()}}else{var u=Date,f=u.now();t.unstable_now=function(){return u.now()-f}}var g=[],p=[],v=1,y=null,w=3,C=!1,S=!1,E=!1,_=!1,R=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,A=typeof setImmediate<"u"?setImmediate:null;function D(j){for(var X=r(p);X!==null;){if(X.callback===null)s(p);else if(X.startTime<=j)s(p),X.sortIndex=X.expirationTime,n(g,X);else break;X=r(p)}}function B(j){if(E=!1,D(j),!S)if(r(g)!==null)S=!0,I||(I=!0,re());else{var X=r(p);X!==null&&ye(B,X.startTime-j)}}var I=!1,U=-1,$=5,me=-1;function fe(){return _?!0:!(t.unstable_now()-me<$)}function pe(){if(_=!1,I){var j=t.unstable_now();me=j;var X=!0;try{e:{S=!1,E&&(E=!1,O(U),U=-1),C=!0;var te=w;try{t:{for(D(j),y=r(g);y!==null&&!(y.expirationTime>j&&fe());){var se=y.callback;if(typeof se=="function"){y.callback=null,w=y.priorityLevel;var ne=se(y.expirationTime<=j);if(j=t.unstable_now(),typeof ne=="function"){y.callback=ne,D(j),X=!0;break t}y===r(g)&&s(g),D(j)}else s(g);y=r(g)}if(y!==null)X=!0;else{var T=r(p);T!==null&&ye(B,T.startTime-j),X=!1}}break e}finally{y=null,w=te,C=!1}X=void 0}}finally{X?re():I=!1}}}var re;if(typeof A=="function")re=function(){A(pe)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,ue=Y.port2;Y.port1.onmessage=pe,re=function(){ue.postMessage(null)}}else re=function(){R(pe,0)};function ye(j,X){U=R(function(){j(t.unstable_now())},X)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(j){j.callback=null},t.unstable_forceFrameRate=function(j){0>j||125<j?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):$=0<j?Math.floor(1e3/j):5},t.unstable_getCurrentPriorityLevel=function(){return w},t.unstable_next=function(j){switch(w){case 1:case 2:case 3:var X=3;break;default:X=w}var te=w;w=X;try{return j()}finally{w=te}},t.unstable_requestPaint=function(){_=!0},t.unstable_runWithPriority=function(j,X){switch(j){case 1:case 2:case 3:case 4:case 5:break;default:j=3}var te=w;w=j;try{return X()}finally{w=te}},t.unstable_scheduleCallback=function(j,X,te){var se=t.unstable_now();switch(typeof te=="object"&&te!==null?(te=te.delay,te=typeof te=="number"&&0<te?se+te:se):te=se,j){case 1:var ne=-1;break;case 2:ne=250;break;case 5:ne=1073741823;break;case 4:ne=1e4;break;default:ne=5e3}return ne=te+ne,j={id:v++,callback:X,priorityLevel:j,startTime:te,expirationTime:ne,sortIndex:-1},te>se?(j.sortIndex=te,n(p,j),r(g)===null&&j===r(p)&&(E?(O(U),U=-1):E=!0,ye(B,te-se))):(j.sortIndex=ne,n(g,j),S||C||(S=!0,I||(I=!0,re()))),j},t.unstable_shouldYield=fe,t.unstable_wrapCallback=function(j){var X=w;return function(){var te=w;w=X;try{return j.apply(this,arguments)}finally{w=te}}}})(pm)),pm}var Sb;function BC(){return Sb||(Sb=1,hm.exports=UC()),hm.exports}var gm={exports:{}},mn={};/**
|
||||
* @license React
|
||||
* react-dom.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/var Eb;function PC(){if(Eb)return mn;Eb=1;var t=Nh();function n(g){var p="https://react.dev/errors/"+g;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var v=2;v<arguments.length;v++)p+="&args[]="+encodeURIComponent(arguments[v])}return"Minified React error #"+g+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(){}var s={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},i=Symbol.for("react.portal");function c(g,p,v){var y=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:y==null?null:""+y,children:g,containerInfo:p,implementation:v}}var u=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function f(g,p){if(g==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return mn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,mn.createPortal=function(g,p){var v=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(n(299));return c(g,p,null,v)},mn.flushSync=function(g){var p=u.T,v=s.p;try{if(u.T=null,s.p=2,g)return g()}finally{u.T=p,s.p=v,s.d.f()}},mn.preconnect=function(g,p){typeof g=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,s.d.C(g,p))},mn.prefetchDNS=function(g){typeof g=="string"&&s.d.D(g)},mn.preinit=function(g,p){if(typeof g=="string"&&p&&typeof p.as=="string"){var v=p.as,y=f(v,p.crossOrigin),w=typeof p.integrity=="string"?p.integrity:void 0,C=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;v==="style"?s.d.S(g,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:y,integrity:w,fetchPriority:C}):v==="script"&&s.d.X(g,{crossOrigin:y,integrity:w,fetchPriority:C,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},mn.preinitModule=function(g,p){if(typeof g=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var v=f(p.as,p.crossOrigin);s.d.M(g,{crossOrigin:v,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&s.d.M(g)},mn.preload=function(g,p){if(typeof g=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var v=p.as,y=f(v,p.crossOrigin);s.d.L(g,v,{crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},mn.preloadModule=function(g,p){if(typeof g=="string")if(p){var v=f(p.as,p.crossOrigin);s.d.m(g,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:v,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else s.d.m(g)},mn.requestFormReset=function(g){s.d.r(g)},mn.unstable_batchedUpdates=function(g,p){return g(p)},mn.useFormState=function(g,p,v){return u.H.useFormState(g,p,v)},mn.useFormStatus=function(){return u.H.useHostTransitionStatus()},mn.version="19.2.4",mn}var _b;function R0(){if(_b)return gm.exports;_b=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),gm.exports=PC(),gm.exports}/**
|
||||
* @license React
|
||||
* react-dom-client.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/var Cb;function HC(){if(Cb)return Ii;Cb=1;var t=BC(),n=Nh(),r=R0();function s(e){var a="https://react.dev/errors/"+e;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var o=2;o<arguments.length;o++)a+="&args[]="+encodeURIComponent(arguments[o])}return"Minified React error #"+e+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function c(e){var a=e,o=e;if(e.alternate)for(;a.return;)a=a.return;else{e=a;do a=e,(a.flags&4098)!==0&&(o=a.return),e=a.return;while(e)}return a.tag===3?o:null}function u(e){if(e.tag===13){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function f(e){if(e.tag===31){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function g(e){if(c(e)!==e)throw Error(s(188))}function p(e){var a=e.alternate;if(!a){if(a=c(e),a===null)throw Error(s(188));return a!==e?null:e}for(var o=e,l=a;;){var d=o.return;if(d===null)break;var h=d.alternate;if(h===null){if(l=d.return,l!==null){o=l;continue}break}if(d.child===h.child){for(h=d.child;h;){if(h===o)return g(d),e;if(h===l)return g(d),a;h=h.sibling}throw Error(s(188))}if(o.return!==l.return)o=d,l=h;else{for(var x=!1,N=d.child;N;){if(N===o){x=!0,o=d,l=h;break}if(N===l){x=!0,l=d,o=h;break}N=N.sibling}if(!x){for(N=h.child;N;){if(N===o){x=!0,o=h,l=d;break}if(N===l){x=!0,l=h,o=d;break}N=N.sibling}if(!x)throw Error(s(189))}}if(o.alternate!==l)throw Error(s(190))}if(o.tag!==3)throw Error(s(188));return o.stateNode.current===o?e:a}function v(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e;for(e=e.child;e!==null;){if(a=v(e),a!==null)return a;e=e.sibling}return null}var y=Object.assign,w=Symbol.for("react.element"),C=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),R=Symbol.for("react.profiler"),O=Symbol.for("react.consumer"),A=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),B=Symbol.for("react.suspense"),I=Symbol.for("react.suspense_list"),U=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),me=Symbol.for("react.activity"),fe=Symbol.for("react.memo_cache_sentinel"),pe=Symbol.iterator;function re(e){return e===null||typeof e!="object"?null:(e=pe&&e[pe]||e["@@iterator"],typeof e=="function"?e:null)}var Y=Symbol.for("react.client.reference");function ue(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Y?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case E:return"Fragment";case R:return"Profiler";case _:return"StrictMode";case B:return"Suspense";case I:return"SuspenseList";case me:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case S:return"Portal";case A:return e.displayName||"Context";case O:return(e._context.displayName||"Context")+".Consumer";case D:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case U:return a=e.displayName||null,a!==null?a:ue(e.type)||"Memo";case $:a=e._payload,e=e._init;try{return ue(e(a))}catch{}}return null}var ye=Array.isArray,j=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,X=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te={pending:!1,data:null,method:null,action:null},se=[],ne=-1;function T(e){return{current:e}}function V(e){0>ne||(e.current=se[ne],se[ne]=null,ne--)}function L(e,a){ne++,se[ne]=e.current,e.current=a}var K=T(null),W=T(null),le=T(null),ge=T(null);function q(e,a){switch(L(le,a),L(W,e),L(K,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?Pv(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=Pv(a),e=Hv(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}V(K),L(K,e)}function ae(){V(K),V(W),V(le)}function Ee(e){e.memoizedState!==null&&L(ge,e);var a=K.current,o=Hv(a,e.type);a!==o&&(L(W,e),L(K,o))}function ke(e){W.current===e&&(V(K),V(W)),ge.current===e&&(V(ge),Ui._currentValue=te)}var ce,_e;function be(e){if(ce===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);ce=a&&a[1]||"",_e=-1<o.stack.indexOf(`
|
||||
at`)?" (<anonymous>)":-1<o.stack.indexOf("@")?"@unknown:0:0":""}return`
|
||||
`+ce+e+_e}var Re=!1;function Pe(e,a){if(!e||Re)return"";Re=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(a){var he=function(){throw Error()};if(Object.defineProperty(he.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(he,[])}catch(ee){var Q=ee}Reflect.construct(e,[],he)}else{try{he.call()}catch(ee){Q=ee}e.call(he.prototype)}}else{try{throw Error()}catch(ee){Q=ee}(he=e())&&typeof he.catch=="function"&&he.catch(function(){})}}catch(ee){if(ee&&Q&&typeof ee.stack=="string")return[ee.stack,Q.stack]}return[null,null]}};l.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var d=Object.getOwnPropertyDescriptor(l.DetermineComponentFrameRoot,"name");d&&d.configurable&&Object.defineProperty(l.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var h=l.DetermineComponentFrameRoot(),x=h[0],N=h[1];if(x&&N){var M=x.split(`
|
||||
`),Z=N.split(`
|
||||
`);for(d=l=0;l<M.length&&!M[l].includes("DetermineComponentFrameRoot");)l++;for(;d<Z.length&&!Z[d].includes("DetermineComponentFrameRoot");)d++;if(l===M.length||d===Z.length)for(l=M.length-1,d=Z.length-1;1<=l&&0<=d&&M[l]!==Z[d];)d--;for(;1<=l&&0<=d;l--,d--)if(M[l]!==Z[d]){if(l!==1||d!==1)do if(l--,d--,0>d||M[l]!==Z[d]){var ie=`
|
||||
`+M[l].replace(" at new "," at ");return e.displayName&&ie.includes("<anonymous>")&&(ie=ie.replace("<anonymous>",e.displayName)),ie}while(1<=l&&0<=d);break}}}finally{Re=!1,Error.prepareStackTrace=o}return(o=e?e.displayName||e.name:"")?be(o):""}function qe(e,a){switch(e.tag){case 26:case 27:case 5:return be(e.type);case 16:return be("Lazy");case 13:return e.child!==a&&a!==null?be("Suspense Fallback"):be("Suspense");case 19:return be("SuspenseList");case 0:case 15:return Pe(e.type,!1);case 11:return Pe(e.type.render,!1);case 1:return Pe(e.type,!0);case 31:return be("Activity");default:return""}}function Ue(e){try{var a="",o=null;do a+=qe(e,o),o=e,e=e.return;while(e);return a}catch(l){return`
|
||||
Error generating stack: `+l.message+`
|
||||
`+l.stack}}var Le=Object.prototype.hasOwnProperty,pt=t.unstable_scheduleCallback,Zt=t.unstable_cancelCallback,k=t.unstable_shouldYield,P=t.unstable_requestPaint,F=t.unstable_now,Se=t.unstable_getCurrentPriorityLevel,ve=t.unstable_ImmediatePriority,xe=t.unstable_UserBlockingPriority,Ce=t.unstable_NormalPriority,Ve=t.unstable_LowPriority,We=t.unstable_IdlePriority,Pt=t.log,Dt=t.unstable_setDisableYieldValue,ht=null,zt=null;function rn(e){if(typeof Pt=="function"&&Dt(e),zt&&typeof zt.setStrictMode=="function")try{zt.setStrictMode(ht,e)}catch{}}var Ht=Math.clz32?Math.clz32:Yn,Qo=Math.log,ur=Math.LN2;function Yn(e){return e>>>=0,e===0?32:31-(Qo(e)/ur|0)|0}var Ua=256,Ms=262144,Wr=4194304;function xa(e){var a=e&42;if(a!==0)return a;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function $e(e,a,o){var l=e.pendingLanes;if(l===0)return 0;var d=0,h=e.suspendedLanes,x=e.pingedLanes;e=e.warmLanes;var N=l&134217727;return N!==0?(l=N&~h,l!==0?d=xa(l):(x&=N,x!==0?d=xa(x):o||(o=N&~e,o!==0&&(d=xa(o))))):(N=l&~h,N!==0?d=xa(N):x!==0?d=xa(x):o||(o=l&~e,o!==0&&(d=xa(o)))),d===0?0:a!==0&&a!==d&&(a&h)===0&&(h=d&-d,o=a&-a,h>=o||h===32&&(o&4194048)!==0)?a:d}function Ct(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function tn(e,a){switch(e){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function fn(){var e=Wr;return Wr<<=1,(Wr&62914560)===0&&(Wr=4194304),e}function dr(e){for(var a=[],o=0;31>o;o++)a.push(e);return a}function At(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function bn(e,a,o,l,d,h){var x=e.pendingLanes;e.pendingLanes=o,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=o,e.entangledLanes&=o,e.errorRecoveryDisabledLanes&=o,e.shellSuspendCounter=0;var N=e.entanglements,M=e.expirationTimes,Z=e.hiddenUpdates;for(o=x&~o;0<o;){var ie=31-Ht(o),he=1<<ie;N[ie]=0,M[ie]=-1;var Q=Z[ie];if(Q!==null)for(Z[ie]=null,ie=0;ie<Q.length;ie++){var ee=Q[ie];ee!==null&&(ee.lane&=-536870913)}o&=~he}l!==0&&Jr(e,l,0),h!==0&&d===0&&e.tag!==0&&(e.suspendedLanes|=h&~(x&~a))}function Jr(e,a,o){e.pendingLanes|=a,e.suspendedLanes&=~a;var l=31-Ht(a);e.entangledLanes|=a,e.entanglements[l]=e.entanglements[l]|1073741824|o&261930}function xn(e,a){var o=e.entangledLanes|=a;for(e=e.entanglements;o;){var l=31-Ht(o),d=1<<l;d&a|e[l]&a&&(e[l]|=a),o&=~d}}function wn(e,a){var o=a&-a;return o=(o&42)!==0?1:Ds(o),(o&(e.suspendedLanes|a))!==0?0:o}function Ds(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function ca(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function ed(){var e=X.p;return e!==0?e:(e=window.event,e===void 0?32:cb(e.type))}function Cp(e,a){var o=X.p;try{return X.p=e,a()}finally{X.p=o}}var fr=Math.random().toString(36).slice(2),sn="__reactFiber$"+fr,Sn="__reactProps$"+fr,zs="__reactContainer$"+fr,td="__reactEvents$"+fr,xE="__reactListeners$"+fr,wE="__reactHandles$"+fr,Np="__reactResources$"+fr,Wo="__reactMarker$"+fr;function nd(e){delete e[sn],delete e[Sn],delete e[td],delete e[xE],delete e[wE]}function Ls(e){var a=e[sn];if(a)return a;for(var o=e.parentNode;o;){if(a=o[zs]||o[sn]){if(o=a.alternate,a.child!==null||o!==null&&o.child!==null)for(e=Yv(e);e!==null;){if(o=e[sn])return o;e=Yv(e)}return a}e=o,o=e.parentNode}return null}function Us(e){if(e=e[sn]||e[zs]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function Jo(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(s(33))}function Bs(e){var a=e[Np];return a||(a=e[Np]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function nn(e){e[Wo]=!0}var Rp=new Set,Ap={};function es(e,a){Ps(e,a),Ps(e+"Capture",a)}function Ps(e,a){for(Ap[e]=a,e=0;e<a.length;e++)Rp.add(a[e])}var SE=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\
Line truncated
|
||||
`).replace(J_,"")}function Uv(e,a){return a=Lv(a),Lv(e)===a}function bt(e,a,o,l,d,h){switch(o){case"children":typeof l=="string"?a==="body"||a==="textarea"&&l===""||Vs(e,l):(typeof l=="number"||typeof l=="bigint")&&a!=="body"&&Vs(e,""+l);break;case"className":Al(e,"class",l);break;case"tabIndex":Al(e,"tabindex",l);break;case"dir":case"role":case"viewBox":case"width":case"height":Al(e,o,l);break;case"style":Up(e,l,h);break;case"data":if(a!=="object"){Al(e,"data",l);break}case"src":case"href":if(l===""&&(a!=="a"||o!=="href")){e.removeAttribute(o);break}if(l==null||typeof l=="function"||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=Tl(""+l),e.setAttribute(o,l);break;case"action":case"formAction":if(typeof l=="function"){e.setAttribute(o,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof h=="function"&&(o==="formAction"?(a!=="input"&&bt(e,a,"name",d.name,d,null),bt(e,a,"formEncType",d.formEncType,d,null),bt(e,a,"formMethod",d.formMethod,d,null),bt(e,a,"formTarget",d.formTarget,d,null)):(bt(e,a,"encType",d.encType,d,null),bt(e,a,"method",d.method,d,null),bt(e,a,"target",d.target,d,null)));if(l==null||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=Tl(""+l),e.setAttribute(o,l);break;case"onClick":l!=null&&(e.onclick=Pa);break;case"onScroll":l!=null&&at("scroll",e);break;case"onScrollEnd":l!=null&&at("scrollend",e);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(s(61));if(o=l.__html,o!=null){if(d.children!=null)throw Error(s(60));e.innerHTML=o}}break;case"multiple":e.multiple=l&&typeof l!="function"&&typeof l!="symbol";break;case"muted":e.muted=l&&typeof l!="function"&&typeof l!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(l==null||typeof l=="function"||typeof l=="boolean"||typeof l=="symbol"){e.removeAttribute("xlink:href");break}o=Tl(""+l),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,""+l):e.removeAttribute(o);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":l&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,""):e.removeAttribute(o);break;case"capture":case"download":l===!0?e.setAttribute(o,""):l!==!1&&l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,l):e.removeAttribute(o);break;case"cols":case"rows":case"size":case"span":l!=null&&typeof l!="function"&&typeof l!="symbol"&&!isNaN(l)&&1<=l?e.setAttribute(o,l):e.removeAttribute(o);break;case"rowSpan":case"start":l==null||typeof l=="function"||typeof l=="symbol"||isNaN(l)?e.removeAttribute(o):e.setAttribute(o,l);break;case"popover":at("beforetoggle",e),at("toggle",e),Rl(e,"popover",l);break;case"xlinkActuate":Ba(e,"http://www.w3.org/1999/xlink","xlink:actuate",l);break;case"xlinkArcrole":Ba(e,"http://www.w3.org/1999/xlink","xlink:arcrole",l);break;case"xlinkRole":Ba(e,"http://www.w3.org/1999/xlink","xlink:role",l);break;case"xlinkShow":Ba(e,"http://www.w3.org/1999/xlink","xlink:show",l);break;case"xlinkTitle":Ba(e,"http://www.w3.org/1999/xlink","xlink:title",l);break;case"xlinkType":Ba(e,"http://www.w3.org/1999/xlink","xlink:type",l);break;case"xmlBase":Ba(e,"http://www.w3.org/XML/1998/namespace","xml:base",l);break;case"xmlLang":Ba(e,"http://www.w3.org/XML/1998/namespace","xml:lang",l);break;case"xmlSpace":Ba(e,"http://www.w3.org/XML/1998/namespace","xml:space",l);break;case"is":Rl(e,"is",l);break;case"innerText":case"textContent":break;default:(!(2<o.length)||o[0]!=="o"&&o[0]!=="O"||o[1]!=="n"&&o[1]!=="N")&&(o=RE.get(o)||o,Rl(e,o,l))}}function Yf(e,a,o,l,d,h){switch(o){case"style":Up(e,l,h);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(s(61));if(o=l.__html,o!=null){if(d.children!=null)throw Error(s(60));e.innerHTML=o}}break;case"children":typeof l=="string"?Vs(e,l):(typeof l=="number"||typeof l=="bigint")&&Vs(e,""+l);break;case"onScroll":l!=null&&at("scroll",e);break;case"onScrollEnd":l!=null&&at("scrollend",e);break;case"onClick":l!=null&&(e.onclick=Pa);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne
Line truncated
|
||||
* react-router v7.13.2
|
||||
*
|
||||
* Copyright (c) Remix Software Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE.md file in the root directory of this source tree.
|
||||
*
|
||||
* @license MIT
|
||||
*/var Rb="popstate";function Ab(t){return typeof t=="object"&&t!=null&&"pathname"in t&&"search"in t&&"hash"in t&&"state"in t&&"key"in t}function qC(t={}){function n(s,i){var p;let c=(p=i.state)==null?void 0:p.masked,{pathname:u,search:f,hash:g}=c||s.location;return Gm("",{pathname:u,search:f,hash:g},i.state&&i.state.usr||null,i.state&&i.state.key||"default",c?{pathname:s.location.pathname,search:s.location.search,hash:s.location.hash}:void 0)}function r(s,i){return typeof i=="string"?i:sl(i)}return $C(n,r,null,t)}function Rt(t,n){if(t===!1||t===null||typeof t>"u")throw new Error(n)}function oa(t,n){if(!t){typeof console<"u"&&console.warn(n);try{throw new Error(n)}catch{}}}function FC(){return Math.random().toString(36).substring(2,10)}function jb(t,n){return{usr:t.state,key:t.key,idx:n,masked:t.unstable_mask?{pathname:t.pathname,search:t.search,hash:t.hash}:void 0}}function Gm(t,n,r=null,s,i){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof n=="string"?Fo(n):n,state:r,key:n&&n.key||s||FC(),unstable_mask:i}}function sl({pathname:t="/",search:n="",hash:r=""}){return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Fo(t){let n={};if(t){let r=t.indexOf("#");r>=0&&(n.hash=t.substring(r),t=t.substring(0,r));let s=t.indexOf("?");s>=0&&(n.search=t.substring(s),t=t.substring(0,s)),t&&(n.pathname=t)}return n}function $C(t,n,r,s={}){let{window:i=document.defaultView,v5Compat:c=!1}=s,u=i.history,f="POP",g=null,p=v();p==null&&(p=0,u.replaceState({...u.state,idx:p},""));function v(){return(u.state||{idx:null}).idx}function y(){f="POP";let _=v(),R=_==null?null:_-p;p=_,g&&g({action:f,location:E.location,delta:R})}function w(_,R){f="PUSH";let O=Ab(_)?_:Gm(E.location,_,R);p=v()+1;let A=jb(O,p),D=E.createHref(O.unstable_mask||O);try{u.pushState(A,"",D)}catch(B){if(B instanceof DOMException&&B.name==="DataCloneError")throw B;i.location.assign(D)}c&&g&&g({action:f,location:E.location,delta:1})}function C(_,R){f="REPLACE";let O=Ab(_)?_:Gm(E.location,_,R);p=v();let A=jb(O,p),D=E.createHref(O.unstable_mask||O);u.replaceState(A,"",D),c&&g&&g({action:f,location:E.location,delta:0})}function S(_){return GC(_)}let E={get action(){return f},get location(){return t(i,u)},listen(_){if(g)throw new Error("A history only accepts one active listener");return i.addEventListener(Rb,y),g=_,()=>{i.removeEventListener(Rb,y),g=null}},createHref(_){return n(i,_)},createURL:S,encodeLocation(_){let R=S(_);return{pathname:R.pathname,search:R.search,hash:R.hash}},push:w,replace:C,go(_){return u.go(_)}};return E}function GC(t,n=!1){let r="http://localhost";typeof window<"u"&&(r=window.location.origin!=="null"?window.location.origin:window.location.href),Rt(r,"No window.location.(origin|href) available to create URL");let s=typeof t=="string"?t:sl(t);return s=s.replace(/ $/,"%20"),!n&&s.startsWith("//")&&(s=r+s),new URL(s,r)}function A0(t,n,r="/"){return YC(t,n,r,!1)}function YC(t,n,r,s){let i=typeof n=="string"?Fo(n):n,c=rr(i.pathname||"/",r);if(c==null)return null;let u=j0(t);ZC(u);let f=null;for(let g=0;f==null&&g<u.length;++g){let p=sN(c);f=aN(u[g],p,s)}return f}function j0(t,n=[],r=[],s="",i=!1){let c=(u,f,g=i,p)=>{let v={relativePath:p===void 0?u.path||"":p,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(v.relativePath.startsWith("/")){if(!v.relativePath.startsWith(s)&&g)return;Rt(v.relativePath.startsWith(s),`Absolute route path "${v.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),v.relativePath=v.relativePath.slice(s.length)}let y=ka([s,v.relativePath]),w=r.concat(v);u.children&&u.children.length>0&&(Rt(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${y}".`),j0(u.children,n,w,y,g)),!(u.path==null&&!u.index)&&n.push({path:y,score:tN(y,u.index),routesMeta:w})};return t.forEach((u,f)=>{var g;if(u.path===""||!((g=u.path)!=null&&g.includes("?")))c(u,f);else for(let p of T0(u.path))c(u,f,!0,p)}),n}function T0(t){let n=t.split("/");if(n.length===0)return[];let[r,...s]=n,i=r.endsWith("?"),c=r.replace(/\?$/,"");if(s.length===0)return i?[c,""]:[c];let u=T0(s.join("/")),f=[];return f.push(...u.map(g=>g===""?c:[c,g].join("/"))),i&&f.push(...u),f.map(g=>t.startsWith("/")&&g===""?"/":g)}function ZC(t){t.sort((n,r)=>n.score!==r.score?r.score-n.score:nN(n.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}var XC=/^:[\w-]+$/,KC=3,QC=2,WC=1,JC=10,eN=-2,Tb=t=>t==="*";function tN(t,n){let r=t.split("/"),s=r.length;return r.some(Tb)&&(s+=eN),n&&(s+=QC),r.filter(i=>!Tb(i)).reduce((i,c)=>i+(XC.test(c)?KC:c===""?WC:JC),s)}function nN(t,n){return t.length===n.length&&t.slice(0,-1).every((s,i)=>s===n[i])?t[t.length-1]-n[n.length-1]:0}function aN(t,n,r=!1){let{routesMeta:s}=t,i={},c="/",u=[];for(let f=0;f<s.length;++f){let g=s[f],p=f===s.length-1,v=c==="/"?n:n.slice(c.length)||"/",y=iu({path:g.relativePath,cas
Line truncated
|
||||
|
||||
Please change the parent <Route path="${R}"> to <Route path="${R==="/"?"*":`${R}/*`}">.`)}let v=Da(),y;if(n){let R=typeof n=="string"?Fo(n):n;Rt(g==="/"||((_=R.pathname)==null?void 0:_.startsWith(g)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${g}" but pathname "${R.pathname}" was given in the \`location\` prop.`),y=R}else y=v;let w=y.pathname||"/",C=w;if(g!=="/"){let R=g.replace(/^\//,"").split("/");C="/"+w.replace(/^\//,"").split("/").slice(R.length).join("/")}let S=A0(t,{pathname:C});oa(p||S!=null,`No routes matched location "${y.pathname}${y.search}${y.hash}" `),oa(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${y.pathname}${y.search}${y.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let E=MN(S&&S.map(R=>Object.assign({},R,{params:Object.assign({},u,R.params),pathname:ka([g,s.encodeLocation?s.encodeLocation(R.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?g:ka([g,s.encodeLocation?s.encodeLocation(R.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathnameBase])})),i,r);return n&&E?b.createElement(ml.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...y},navigationType:"POP"}},E):E}function jN(){let t=BN(),n=mN(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,s="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:s},c={padding:"2px 4px",backgroundColor:s},u=null;return console.error("Error handled by React Router default ErrorBoundary:",t),u=b.createElement(b.Fragment,null,b.createElement("p",null,"💿 Hey developer 👋"),b.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",b.createElement("code",{style:c},"ErrorBoundary")," or"," ",b.createElement("code",{style:c},"errorElement")," prop on your route.")),b.createElement(b.Fragment,null,b.createElement("h2",null,"Unexpected Application Error!"),b.createElement("h3",{style:{fontStyle:"italic"}},n),r?b.createElement("pre",{style:i},r):null,u)}var TN=b.createElement(jN,null),P0=class extends b.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){this.props.onError?this.props.onError(t,n):console.error("React Router caught the following error during render",t)}render(){let t=this.state.error;if(this.context&&typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){const r=SN(t.digest);r&&(t=r)}let n=t!==void 0?b.createElement(ia.Provider,{value:this.props.routeContext},b.createElement(Ah.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?b.createElement(kN,{error:t},n):n}};P0.contextType=gN;var vm=new WeakMap;function kN({children:t,error:n}){let{basename:r}=b.useContext(Gn);if(typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){let s=wN(n.digest);if(s){let i=vm.get(n);if(i)throw i;let c=O0(s.location,r);if(k0&&!vm.get(n))if(c.isExternal||s.reloadDocument)window.location.href=c.absoluteURL||c.to;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(c.to,{replace:s.replace}));throw vm.set(n,u),u}return b.createElement("meta",{httpEquiv:"refresh",content:`0;url=${c.absoluteURL||c.to}`})}}return t}function ON({routeContext:t,match:n,children:r}){let s=b.useContext($o);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),b.createElement(ia.Provider,{value:t},r)}function MN(t,n=[],r){let s=r==null?void 0:r.state;if(t==null){if(!s)return null;if(s.errors)t=s.matches;else if(n.length===0&&!s.initialized&&s.matches.length>0)t=s.matches;else return null}let i=t,c=s==null?void 0:s.errors;if(c!=null){let v=i.findIndex(y=>y.route.id&&(c==null?void 0:c[y.route.id])!==void 0);Rt(v>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(c).join(",")}`),i=i.slice(0,Math.min(i.length,v+1))}let u=!1,f=-1;if(r&&s){u=s.renderFallback;for(let v=0;v<i.length;v++){let y=i[v];if((y.route.HydrateFallback||y.route.hydrateFallbackElement)&&(f=v),y.route.id){let{loaderData:w,errors:C}=s,S=yLine truncated
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Q2=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),W2=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),Lb=t=>{const n=W2(t);return n.charAt(0).toUpperCase()+n.slice(1)},Y0=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),J2=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0};/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/var eR={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const tR=b.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...f},g)=>b.createElement("svg",{ref:g,...eR,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:Y0("lucide",i),...!c&&!J2(f)&&{"aria-hidden":"true"},...f},[...u.map(([p,v])=>b.createElement(p,v)),...Array.isArray(c)?c:[c]]));/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Ge=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(tR,{ref:c,iconNode:n,className:Y0(`lucide-${Q2(Lb(t))}`,`lucide-${t}`,s),...i}));return r.displayName=Lb(t),r};/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const nR=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ub=Ge("arrow-left",nR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const aR=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],rR=Ge("arrow-right",aR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const sR=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],oR=Ge("book-open",sR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const iR=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Km=Ge("chevron-down",iR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const lR=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Qm=Ge("chevron-right",lR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const cR=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],uR=Ge("chevron-up",cR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const dR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],fR=Ge("circle-alert",dR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const mR=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],hR=Ge("circle-check-big",mR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const pR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Bb=Ge("circle-check",pR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const gR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],yR=Ge("circle-x",gR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const vR=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],bR=Ge("clock",vR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const xR=[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]],wR=Ge("code-xml",xR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const SR=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],ER=Ge("ellipsis-vertical",SR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const _R=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],CR=Ge("external-link",_R);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const NR=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],RR=Ge("eye-off",NR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const AR=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],jR=Ge("eye",AR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const TR=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"1oajmo"}],["path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"mpwhp6"}]],Pb=Ge("file-json",TR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const kR=[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]],Wm=Ge("flask-conical",kR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const OR=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],MR=Ge("funnel",OR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const DR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],zR=Ge("globe",DR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const LR=[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]],Z0=Ge("key-round",LR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const UR=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],BR=Ge("layers",UR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const PR=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],HR=Ge("layout-dashboard",PR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const VR=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ol=Ge("loader-circle",VR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const IR=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],qR=Ge("log-out",IR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const FR=[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]],$R=Ge("message-square",FR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const GR=[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]],YR=Ge("moon",GR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const ZR=[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]],XR=Ge("play",ZR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const KR=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Jm=Ge("plus",KR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const QR=[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],WR=Ge("power-off",QR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const JR=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],X0=Ge("power",JR);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const eA=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],Hb=Ge("qr-code",eA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const tA=[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]],nA=Ge("refresh-ccw",tA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const aA=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Vb=Ge("refresh-cw",aA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const rA=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],Ib=Ge("save",rA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const sA=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],K0=Ge("search",sA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const oA=[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],iA=Ge("settings",oA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const lA=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],cA=Ge("shield-check",lA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const uA=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],dA=Ge("shield",uA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const fA=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],mA=Ge("smartphone",fA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const hA=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],pA=Ge("square-terminal",hA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const gA=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],yA=Ge("sun",gA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const vA=[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]],zh=Ge("trash-2",vA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const bA=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],xA=Ge("triangle-alert",bA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const wA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Es=Ge("x",wA);/**
|
||||
* @license lucide-react v0.525.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const SA=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],EA=Ge("zap",SA);class _A extends b.Component{constructor(r){super(r);gb(this,"handleReset",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r,errorInfo:null}}componentDidCatch(r,s){console.error("ErrorBoundary caught an error:",r,s),this.setState({error:r,errorInfo:s})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:m.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-50 px-4",children:m.jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-8 shadow-lg",children:[m.jsx("div",{className:"mb-4 flex items-center justify-center",children:m.jsx("div",{className:"rounded-full bg-red-100 p-3",children:m.jsx(xA,{className:"h-8 w-8 text-red-600"})})}),m.jsx("h1",{className:"mb-2 text-center text-2xl font-bold text-gray-900",children:"Algo deu errado"}),m.jsx("p",{className:"mb-6 text-center text-gray-600",children:"Ocorreu um erro inesperado na aplicação."}),this.state.error&&m.jsxs("div",{className:"mb-6 rounded-md bg-red-50 p-4",children:[m.jsx("p",{className:"text-sm font-medium text-red-800",children:this.state.error.message}),!1]}),m.jsxs("div",{className:"flex gap-3",children:[m.jsx("button",{onClick:this.handleReset,className:"flex-1 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",children:"Tentar novamente"}),m.jsx("button",{onClick:()=>window.location.href="/",className:"flex-1 rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",children:"Voltar ao início"})]})]})}):this.props.children}}function Q0(t){var n,r,s="";if(typeof t=="string"||typeof t=="number")s+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(n=0;n<i;n++)t[n]&&(r=Q0(t[n]))&&(s&&(s+=" "),s+=r)}else for(r in t)t[r]&&(s&&(s+=" "),s+=r);return s}function Lh(){for(var t,n,r=0,s="",i=arguments.length;r<i;r++)(t=arguments[r])&&(n=Q0(t))&&(s&&(s+=" "),s+=n);return s}const CA=(t,n)=>{const r=new Array(t.length+n.length);for(let s=0;s<t.length;s++)r[s]=t[s];for(let s=0;s<n.length;s++)r[t.length+s]=n[s];return r},NA=(t,n)=>({classGroupId:t,validator:n}),W0=(t=new Map,n=null,r)=>({nextPart:t,validators:n,classGroupId:r}),lu="-",qb=[],RA="arbitrary..",AA=t=>{const n=TA(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=t;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return jA(u);const f=u.split(lu),g=f[0]===""&&f.length>1?1:0;return J0(f,g,n)},getConflictingClassGroupIds:(u,f)=>{if(f){const g=s[u],p=r[u];return g?p?CA(p,g):g:p||qb}return r[u]||qb}}},J0=(t,n,r)=>{if(t.length-n===0)return r.classGroupId;const i=t[n],c=r.nextPart.get(i);if(c){const p=J0(t,n+1,c);if(p)return p}const u=r.validators;if(u===null)return;const f=n===0?t.join(lu):t.slice(n).join(lu),g=u.length;for(let p=0;p<g;p++){const v=u[p];if(v.validator(f))return v.classGroupId}},jA=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const n=t.slice(1,-1),r=n.indexOf(":"),s=n.slice(0,r);return s?RA+s:void 0})(),TA=t=>{const{theme:n,classGroups:r}=t;return kA(r,n)},kA=(t,n)=>{const r=W0();for(const s in t){const i=t[s];Uh(i,r,s,n)}return r},Uh=(t,n,r,s)=>{const i=t.length;for(let c=0;c<i;c++){const u=t[c];OA(u,n,r,s)}},OA=(t,n,r,s)=>{if(typeof t=="string"){MA(t,n,r);return}if(typeof t=="function"){DA(t,n,r,s);return}zA(t,n,r,s)},MA=(t,n,r)=>{const s=t===""?n:e1(n,t);s.classGroupId=r},DA=(t,n,r,s)=>{if(LA(t)){Uh(t(s),n,r,s);return}n.validators===null&&(n.validators=[]),n.validators.push(NA(r,t))},zA=(t,n,r,s)=>{const i=Object.entries(t),c=i.length;for(let u=0;u<c;u++){const[f,g]=i[u];Uh(g,e1(n,f),r,s)}},e1=(t,n)=>{let r=t;const s=n.split(lu),i=s.length;for(let c=0;c<i;c++){const u=s[c];let f=r.nextPart.get(u);f||(f=W0(),r.nextPart.set(u,f)),r=f}return r},LA=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,UA=t=>{if(t<1)return{get:()=>{},set:()=>{}};let n=0,r=Object.create(null),s=Object.create(null);const i=(c,u)=>{r[c]=u,n++,n>t&&(n=0,s=r,r=Object.create(null))};return{get(c){let u=r[c];if(u!==void 0)return u;if((u=s[c])!==void 0)return i(c,u),u},set(c,u){c in r?r[c]=u:i(c,u)}}},eh="!",Fb=":",BA=[],$b=(t,n,r,s,i)=>({modifiers:t,hasImportantModifier:n,baseClassName:r,maybePostfixModifierPosition:s,isExternal:i}),PA=t=>{const{prefix:n,experimentalParseClassName:r}=t;let s=i=>{const c=[];let u=0,f=0,g=0,p;const v=i.length;for(let E=0;E<v;E++){const _=i[E];if(u===0&&f===0){if(_===Fb){c.push(i.slice(g,E)),g=E+1;continue}if(_==="/"){p=E;continue}}_==="["?u++:_==="]"?u--:_==="("?f++:_===")"&&f--}const y=c.length===0?i:i.slice(g);let w=y,C=!1;y.endsWith(eLine truncated
|
||||
`).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),s=u.substring(i+1).trim(),!(!r||n[r]&&NT[r])&&(r==="set-cookie"?n[r]?n[r].push(s):n[r]=[s]:n[r]=n[r]?n[r]+", "+s:s)}),n},tx=Symbol("internals");function $i(t){return t&&String(t).trim().toLowerCase()}function nu(t){return t===!1||t==null?t:J.isArray(t)?t.map(nu):String(t)}function AT(t){const n=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=r.exec(t);)n[s[1]]=s[2];return n}const jT=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Em(t,n,r,s,i){if(J.isFunction(s))return s.call(this,n,r);if(i&&(n=r),!!J.isString(n)){if(J.isString(s))return n.indexOf(s)!==-1;if(J.isRegExp(s))return s.test(n)}}function TT(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(n,r,s)=>r.toUpperCase()+s)}function kT(t,n){const r=J.toCamelCase(" "+n);["get","set","has"].forEach(s=>{Object.defineProperty(t,s+r,{value:function(i,c,u){return this[s].call(this,n,i,c,u)},configurable:!0})})}let Mn=class{constructor(n){n&&this.set(n)}set(n,r,s){const i=this;function c(f,g,p){const v=$i(g);if(!v)throw new Error("header name must be a non-empty string");const y=J.findKey(i,v);(!y||i[y]===void 0||p===!0||p===void 0&&i[y]!==!1)&&(i[y||g]=nu(f))}const u=(f,g)=>J.forEach(f,(p,v)=>c(p,v,g));if(J.isPlainObject(n)||n instanceof this.constructor)u(n,r);else if(J.isString(n)&&(n=n.trim())&&!jT(n))u(RT(n),r);else if(J.isObject(n)&&J.isIterable(n)){let f={},g,p;for(const v of n){if(!J.isArray(v))throw TypeError("Object iterator must return a key-value pair");f[p=v[0]]=(g=f[p])?J.isArray(g)?[...g,v[1]]:[g,v[1]]:v[1]}u(f,r)}else n!=null&&c(r,n,s);return this}get(n,r){if(n=$i(n),n){const s=J.findKey(this,n);if(s){const i=this[s];if(!r)return i;if(r===!0)return AT(i);if(J.isFunction(r))return r.call(this,i,s);if(J.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(n,r){if(n=$i(n),n){const s=J.findKey(this,n);return!!(s&&this[s]!==void 0&&(!r||Em(this,this[s],s,r)))}return!1}delete(n,r){const s=this;let i=!1;function c(u){if(u=$i(u),u){const f=J.findKey(s,u);f&&(!r||Em(s,s[f],f,r))&&(delete s[f],i=!0)}}return J.isArray(n)?n.forEach(c):c(n),i}clear(n){const r=Object.keys(this);let s=r.length,i=!1;for(;s--;){const c=r[s];(!n||Em(this,this[c],c,n,!0))&&(delete this[c],i=!0)}return i}normalize(n){const r=this,s={};return J.forEach(this,(i,c)=>{const u=J.findKey(s,c);if(u){r[u]=nu(i),delete r[c];return}const f=n?TT(c):String(c).trim();f!==c&&delete r[c],r[f]=nu(i),s[f]=!0}),this}concat(...n){return this.constructor.concat(this,...n)}toJSON(n){const r=Object.create(null);return J.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=n&&J.isArray(s)?s.join(", "):s)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([n,r])=>n+": "+r).join(`
|
||||
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(n){return n instanceof this?n:new this(n)}static concat(n,...r){const s=new this(n);return r.forEach(i=>s.set(i)),s}static accessor(n){const s=(this[tx]=this[tx]={accessors:{}}).accessors,i=this.prototype;function c(u){const f=$i(u);s[f]||(kT(i,u),s[f]=!0)}return J.isArray(n)?n.forEach(c):c(n),this}};Mn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);J.reduceDescriptors(Mn.prototype,({value:t},n)=>{let r=n[0].toUpperCase()+n.slice(1);return{get:()=>t,set(s){this[r]=s}}});J.freezeMethods(Mn);function _m(t,n){const r=this||vl,s=n||r,i=Mn.from(s.headers);let c=s.data;return J.forEach(t,function(f){c=f.call(r,c,i.normalize(),n?n.status:void 0)}),i.normalize(),c}function R1(t){return!!(t&&t.__CANCEL__)}let bl=class extends Ie{constructor(n,r,s){super(n??"canceled",Ie.ERR_CANCELED,r,s),this.name="CanceledError",this.__CANCEL__=!0}};function A1(t,n,r){const s=r.config.validateStatus;!r.status||!s||s(r.status)?t(r):n(new Ie("Request failed with status code "+r.status,[Ie.ERR_BAD_REQUEST,Ie.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function OT(t){const n=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return n&&n[1]||""}function MT(t,n){t=t||10;const r=new Array(t),s=new Array(t);let i=0,c=0,u;return n=n!==void 0?n:1e3,function(g){const p=Date.now(),v=s[c];u||(u=p),r[i]=g,s[i]=p;let y=c,w=0;for(;y!==i;)w+=r[y++],y=y%t;if(i=(i+1)%t,i===c&&(c=(c+1)%t),p-u<n)return;const C=v&&p-v;return C?Math.round(w*1e3/C):void 0}}function DT(t,n){let r=0,s=1e3/n,i,c;const u=(p,v=Date.now())=>{r=v,i=null,c&&(clearTimeout(c),c=null),t(...p)};return[(...p)=>{const v=Date.now(),y=v-r;y>=s?u(p,v):(i=p,c||(c=setTimeout(()=>{c=null,u(i)},s-y)))},()=>i&&u(i)]}const cu=(t,n,r=3)=>{let s=0;const i=MT(50,250);return DT(c=>{const u=c.loaded,f=c.lengthComputable?c.total:void 0,g=u-s,p=i(g),v=u<=f;s=u;const y={loaded:u,total:f,progress:f?u/f:void 0,bytes:g,rate:p||void 0,estimated:p&&f&&v?(f-u)/p:void 0,event:c,lengthComputable:f!=null,[n?"download":"upload"]:!0};t(y)},r)},nx=(t,n)=>{const r=t!=null;return[s=>n[0]({lengthComputable:r,total:t,loaded:s}),n[1]]},ax=t=>(...n)=>J.asap(()=>t(...n)),zT=hn.hasStandardBrowserEnv?((t,n)=>r=>(r=new URL(r,hn.origin),t.protocol===r.protocol&&t.host===r.host&&(n||t.port===r.port)))(new URL(hn.origin),hn.navigator&&/(msie|trident)/i.test(hn.navigator.userAgent)):()=>!0,LT=hn.hasStandardBrowserEnv?{write(t,n,r,s,i,c,u){if(typeof document>"u")return;const f=[`${t}=${encodeURIComponent(n)}`];J.isNumber(r)&&f.push(`expires=${new Date(r).toUTCString()}`),J.isString(s)&&f.push(`path=${s}`),J.isString(i)&&f.push(`domain=${i}`),c===!0&&f.push("secure"),J.isString(u)&&f.push(`SameSite=${u}`),document.cookie=f.join("; ")},read(t){if(typeof document>"u")return null;const n=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return n?decodeURIComponent(n[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function UT(t){return typeof t!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function BT(t,n){return n?t.replace(/\/?\/$/,"")+"/"+n.replace(/^\/+/,""):t}function j1(t,n,r){let s=!UT(n);return t&&(s||r==!1)?BT(t,n):n}const rx=t=>t instanceof Mn?{...t}:t;function _s(t,n){n=n||{};const r={};function s(p,v,y,w){return J.isPlainObject(p)&&J.isPlainObject(v)?J.merge.call({caseless:w},p,v):J.isPlainObject(v)?J.merge({},v):J.isArray(v)?v.slice():v}function i(p,v,y,w){if(J.isUndefined(v)){if(!J.isUndefined(p))return s(void 0,p,y,w)}else return s(p,v,y,w)}function c(p,v){if(!J.isUndefined(v))return s(void 0,v)}function u(p,v){if(J.isUndefined(v)){if(!J.isUndefined(p))return s(void 0,p)}else return s(void 0,v)}function f(p,v,y){if(y in n)return s(p,v);if(y in t)return s(void 0,p)}const g={url:c,method:c,data:c,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:f,headers:(p,v,y)=>i(rx(p),rx(v),y,!0)};return J.forEach(Object.keys({...t,...n}),function(v){if(v==="__proto__"||v==="constructor"||v==="prototype")return;const y=J.hasOwnProp(g,v)?g[v]:i,w=y(t[v],n[v],v);J.isUndefined(w)&&y!==f||(r[v]=w)}),r}const T1=t=>{const n=_s({},t);let{data:r,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:c,headers:u,auth:f}=n;if(n.headers=u=Mn.from(u),n.url=C1(j1(n.baseURL,n.url,n.allowAbsoluteUrls),t.params,t.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):""))),J.isFormData(r)){if(hn.hasStandardBrowserEnv||hn.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if(J.isFunction(r.getHeader
Line truncated
|
||||
`+u.map(ux).join(`
|
||||
`):" "+ux(u[0]):"as no adapter specified";throw new Ie("There is no suitable adapter to dispatch the request "+f,"ERR_NOT_SUPPORT")}return i}const O1={getAdapter:XT,adapters:qh};function Cm(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new bl(null,t)}function dx(t){return Cm(t),t.headers=Mn.from(t.headers),t.data=_m.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),O1.getAdapter(t.adapter||vl.adapter,t)(t).then(function(s){return Cm(t),s.data=_m.call(t,t.transformResponse,s),s.headers=Mn.from(s.headers),s},function(s){return R1(s)||(Cm(t),s&&s.response&&(s.response.data=_m.call(t,t.transformResponse,s.response),s.response.headers=Mn.from(s.response.headers))),Promise.reject(s)})}const M1="1.13.6",Lu={};["object","boolean","number","function","string","symbol"].forEach((t,n)=>{Lu[t]=function(s){return typeof s===t||"a"+(n<1?"n ":" ")+t}});const fx={};Lu.transitional=function(n,r,s){function i(c,u){return"[Axios v"+M1+"] Transitional option '"+c+"'"+u+(s?". "+s:"")}return(c,u,f)=>{if(n===!1)throw new Ie(i(u," has been removed"+(r?" in "+r:"")),Ie.ERR_DEPRECATED);return r&&!fx[u]&&(fx[u]=!0,console.warn(i(u," has been deprecated since v"+r+" and will be removed in the near future"))),n?n(c,u,f):!0}};Lu.spelling=function(n){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${n}`),!0)};function KT(t,n,r){if(typeof t!="object")throw new Ie("options must be an object",Ie.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let i=s.length;for(;i-- >0;){const c=s[i],u=n[c];if(u){const f=t[c],g=f===void 0||u(f,c,t);if(g!==!0)throw new Ie("option "+c+" must be "+g,Ie.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Ie("Unknown option "+c,Ie.ERR_BAD_OPTION)}}const au={assertOptions:KT,validators:Lu},ra=au.validators;let Ss=class{constructor(n){this.defaults=n||{},this.interceptors={request:new ex,response:new ex}}async request(n,r){try{return await this._request(n,r)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const c=i.stack?i.stack.replace(/^.+\n/,""):"";try{s.stack?c&&!String(s.stack).endsWith(c.replace(/^.+\n.+\n/,""))&&(s.stack+=`
|
||||
`+c):s.stack=c}catch{}}throw s}}_request(n,r){typeof n=="string"?(r=r||{},r.url=n):r=n||{},r=_s(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:c}=r;s!==void 0&&au.assertOptions(s,{silentJSONParsing:ra.transitional(ra.boolean),forcedJSONParsing:ra.transitional(ra.boolean),clarifyTimeoutError:ra.transitional(ra.boolean),legacyInterceptorReqResOrdering:ra.transitional(ra.boolean)},!1),i!=null&&(J.isFunction(i)?r.paramsSerializer={serialize:i}:au.assertOptions(i,{encode:ra.function,serialize:ra.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),au.assertOptions(r,{baseUrl:ra.spelling("baseURL"),withXsrfToken:ra.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let u=c&&J.merge(c.common,c[r.method]);c&&J.forEach(["delete","get","head","post","put","patch","common"],S=>{delete c[S]}),r.headers=Mn.concat(u,c);const f=[];let g=!0;this.interceptors.request.forEach(function(E){if(typeof E.runWhen=="function"&&E.runWhen(r)===!1)return;g=g&&E.synchronous;const _=r.transitional||Vh;_&&_.legacyInterceptorReqResOrdering?f.unshift(E.fulfilled,E.rejected):f.push(E.fulfilled,E.rejected)});const p=[];this.interceptors.response.forEach(function(E){p.push(E.fulfilled,E.rejected)});let v,y=0,w;if(!g){const S=[dx.bind(this),void 0];for(S.unshift(...f),S.push(...p),w=S.length,v=Promise.resolve(r);y<w;)v=v.then(S[y++],S[y++]);return v}w=f.length;let C=r;for(;y<w;){const S=f[y++],E=f[y++];try{C=S(C)}catch(_){E.call(this,_);break}}try{v=dx.call(this,C)}catch(S){return Promise.reject(S)}for(y=0,w=p.length;y<w;)v=v.then(p[y++],p[y++]);return v}getUri(n){n=_s(this.defaults,n);const r=j1(n.baseURL,n.url,n.allowAbsoluteUrls);return C1(r,n.params,n.paramsSerializer)}};J.forEach(["delete","get","head","options"],function(n){Ss.prototype[n]=function(r,s){return this.request(_s(s||{},{method:n,url:r,data:(s||{}).data}))}});J.forEach(["post","put","patch"],function(n){function r(s){return function(c,u,f){return this.request(_s(f||{},{method:n,headers:s?{"Content-Type":"multipart/form-data"}:{},url:c,data:u}))}}Ss.prototype[n]=r(),Ss.prototype[n+"Form"]=r(!0)});let QT=class D1{constructor(n){if(typeof n!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(c){r=c});const s=this;this.promise.then(i=>{if(!s._listeners)return;let c=s._listeners.length;for(;c-- >0;)s._listeners[c](i);s._listeners=null}),this.promise.then=i=>{let c;const u=new Promise(f=>{s.subscribe(f),c=f}).then(i);return u.cancel=function(){s.unsubscribe(c)},u},n(function(c,u,f){s.reason||(s.reason=new bl(c,u,f),r(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(n){if(this.reason){n(this.reason);return}this._listeners?this._listeners.push(n):this._listeners=[n]}unsubscribe(n){if(!this._listeners)return;const r=this._listeners.indexOf(n);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const n=new AbortController,r=s=>{n.abort(s)};return this.subscribe(r),n.signal.unsubscribe=()=>this.unsubscribe(r),n.signal}static source(){let n;return{token:new D1(function(i){n=i}),cancel:n}}};function WT(t){return function(r){return t.apply(null,r)}}function JT(t){return J.isObject(t)&&t.isAxiosError===!0}const oh={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(oh).forEach(([t,n])=>{oh[n]=t});function z1(t){const n=new Ss(t),r=h1(Ss.prototype.request,n);return J.extend(r,Ss.prototype,n,{allOwnKeys:!0}),J.extend(r,n,null,{allOwnKeys:!0}),r.create=function(i){return z1(_s(t,i))},r}const Tt=z1(vl);Tt.Axios=Ss;Tt.CanceledError=bl;Tt.CancelToken=QT;Tt.isCancel=R1;Tt.VERSION=M1;
Line truncated
|
||||
* @license lucide-react v0.522.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Nk=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Rk=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),hx=t=>{const n=Rk(t);return n.charAt(0).toUpperCase()+n.slice(1)},H1=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),Ak=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0};/**
|
||||
* @license lucide-react v0.522.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/var jk={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
||||
* @license lucide-react v0.522.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Tk=b.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...f},g)=>b.createElement("svg",{ref:g,...jk,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:H1("lucide",i),...!c&&!Ak(f)&&{"aria-hidden":"true"},...f},[...u.map(([p,v])=>b.createElement(p,v)),...Array.isArray(c)?c:[c]]));/**
|
||||
* @license lucide-react v0.522.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const kk=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(Tk,{ref:c,iconNode:n,className:H1(`lucide-${Nk(hx(t))}`,`lucide-${t}`,s),...i}));return r.displayName=hx(t),r};/**
|
||||
* @license lucide-react v0.522.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Ok=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Mk=kk("x",Ok),px=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,gx=Lh,$h=(t,n)=>r=>{var s;if((n==null?void 0:n.variants)==null)return gx(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:c}=n,u=Object.keys(i).map(p=>{const v=r==null?void 0:r[p],y=c==null?void 0:c[p];if(v===null)return null;const w=px(v)||px(y);return i[p][w]}),f=r&&Object.entries(r).reduce((p,v)=>{let[y,w]=v;return w===void 0||(p[y]=w),p},{}),g=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((p,v)=>{let{class:y,className:w,...C}=v;return Object.entries(C).every(S=>{let[E,_]=S;return Array.isArray(_)?_.includes({...c,...f}[E]):{...c,...f}[E]===_})?[...p,y,w]:p},[]);return gx(t,u,g,r==null?void 0:r.class,r==null?void 0:r.className)};function sr(t){const n=b.useRef(t);return b.useEffect(()=>{n.current=t}),b.useMemo(()=>(...r)=>{var s;return(s=n.current)==null?void 0:s.call(n,...r)},[])}function Dk(t,n=globalThis==null?void 0:globalThis.document){const r=sr(t);b.useEffect(()=>{const s=i=>{i.key==="Escape"&&r(i)};return n.addEventListener("keydown",s,{capture:!0}),()=>n.removeEventListener("keydown",s,{capture:!0})},[r,n])}var zk="DismissableLayer",ih="dismissableLayer.update",Lk="dismissableLayer.pointerDownOutside",Uk="dismissableLayer.focusOutside",yx,V1=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Uu=b.forwardRef((t,n)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:c,onInteractOutside:u,onDismiss:f,...g}=t,p=b.useContext(V1),[v,y]=b.useState(null),w=(v==null?void 0:v.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,C]=b.useState({}),S=Wt(n,U=>y(U)),E=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),R=E.indexOf(_),O=v?E.indexOf(v):-1,A=p.layersWithOutsidePointerEventsDisabled.size>0,D=O>=R,B=Hk(U=>{const $=U.target,me=[...p.branches].some(fe=>fe.contains($));!D||me||(i==null||i(U),u==null||u(U),U.defaultPrevented||f==null||f())},w),I=Vk(U=>{const $=U.target;[...p.branches].some(fe=>fe.contains($))||(c==null||c(U),u==null||u(U),U.defaultPrevented||f==null||f())},w);return Dk(U=>{O===p.layers.size-1&&(s==null||s(U),!U.defaultPrevented&&f&&(U.preventDefault(),f()))},w),b.useEffect(()=>{if(v)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(yx=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(v)),p.layers.add(v),vx(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=yx)}},[v,w,r,p]),b.useEffect(()=>()=>{v&&(p.layers.delete(v),p.layersWithOutsidePointerEventsDisabled.delete(v),vx())},[v,p]),b.useEffect(()=>{const U=()=>C({});return document.addEventListener(ih,U),()=>document.removeEventListener(ih,U)},[]),m.jsx(Mt.div,{...g,ref:S,style:{pointerEvents:A?D?"auto":"none":void 0,...t.style},onFocusCapture:Xe(t.onFocusCapture,I.onFocusCapture),onBlurCapture:Xe(t.onBlurCapture,I.onBlurCapture),onPointerDownCapture:Xe(t.onPointerDownCapture,B.onPointerDownCapture)})});Uu.displayName=zk;var Bk="DismissableLayerBranch",Pk=b.forwardRef((t,n)=>{const r=b.useContext(V1),s=b.useRef(null),i=Wt(n,s);return b.useEffect(()=>{const c=s.current;if(c)return r.branches.add(c),()=>{r.branches.delete(c)}},[r.branches]),m.jsx(Mt.div,{...t,ref:i})});Pk.displayName=Bk;function Hk(t,n=globalThis==null?void 0:globalThis.document){const r=sr(t),s=b.useRef(!1),i=b.useRef(()=>{});return b.useEffect(()=>{const c=f=>{if(f.target&&!s.current){let g=function(){I1(Lk,r,p,{discrete:!0})};const p={originalEvent:f};f.pointerType==="touch"?(n.removeEventListener("click",i.current),i.current=g,n.addEventListener("click",i.current,{once:!0})):g()}else n.removeEventListener("click",i.current);s.current=!1},u=window.setTimeout(()=>{n.addEventListener("pointerdown",c)},0);return()=>{window.clearTimeout(u),n.removeEventListener("pointerdown",c),n.removeEventListener("click",i.current)}},[n,r]),{onPointerDownCapture:()=>s.current=!0}}function Vk(t,n=globalThis==null?void 0:globalThis.document){const r=sr(t),s=b.useRef(!1);return b.useEffect(()=>{const i=c=>{c.target&&!s.current&&I1(Uk,r,{originalEvent:c},{discrete:!1})};return n.addEventListener("focusin",i),()=>n.removeEventListener("focusin",i)},[n,r]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function vx(){const t=new CustomEvent(ih);document.dispatchEvent(t)}function I1(t,n,r,{discrete:s}){const i=r.originalEvent.target,c=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});n&&i.addEventListener(t,n,{once:!0}),s?B1(i,c):i.dispatchEvent(c)}var Nm="focusScope.autoFocusOnMount",Rm="focusScope.autoFocusOnUnmount",bx={bubbles:!1,cancelable:!0},Ik="FocusScope",Bu=b.forwardRef((t,n)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:i,onUnmountAutoFocus:c,...u}=t,[f,g]=b.useState(null),p=sr(i),v=sr(c),y=b.useRef(null),w=Wt(n,E=>g(ELine truncated
|
||||
.`.concat(Qk,` {
|
||||
overflow: hidden `).concat(s,`;
|
||||
padding-right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
body[`).concat(ko,`] {
|
||||
overflow: hidden `).concat(s,`;
|
||||
overscroll-behavior: contain;
|
||||
`).concat([n&&"position: relative ".concat(s,";"),r==="margin"&&`
|
||||
padding-left: `.concat(i,`px;
|
||||
padding-top: `).concat(c,`px;
|
||||
padding-right: `).concat(u,`px;
|
||||
margin-left:0;
|
||||
margin-top:0;
|
||||
margin-right: `).concat(f,"px ").concat(s,`;
|
||||
`),r==="padding"&&"padding-right: ".concat(f,"px ").concat(s,";")].filter(Boolean).join(""),`
|
||||
}
|
||||
|
||||
.`).concat(ru,` {
|
||||
right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(su,` {
|
||||
margin-right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(ru," .").concat(ru,` {
|
||||
right: 0 `).concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(su," .").concat(su,` {
|
||||
margin-right: 0 `).concat(s,`;
|
||||
}
|
||||
|
||||
body[`).concat(ko,`] {
|
||||
`).concat(Wk,": ").concat(f,`px;
|
||||
}
|
||||
`)},Cx=function(){var t=parseInt(document.body.getAttribute(ko)||"0",10);return isFinite(t)?t:0},yO=function(){b.useEffect(function(){return document.body.setAttribute(ko,(Cx()+1).toString()),function(){var t=Cx()-1;t<=0?document.body.removeAttribute(ko):document.body.setAttribute(ko,t.toString())}},[])},vO=function(t){var n=t.noRelative,r=t.noImportant,s=t.gapMode,i=s===void 0?"margin":s;yO();var c=b.useMemo(function(){return hO(i)},[i]);return b.createElement(pO,{styles:gO(c,!n,i,r?"":"!important")})},lh=!1;if(typeof window<"u")try{var $c=Object.defineProperty({},"passive",{get:function(){return lh=!0,!0}});window.addEventListener("test",$c,$c),window.removeEventListener("test",$c,$c)}catch{lh=!1}var xo=lh?{passive:!1}:!1,bO=function(t){return t.tagName==="TEXTAREA"},Z1=function(t,n){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[n]!=="hidden"&&!(r.overflowY===r.overflowX&&!bO(t)&&r[n]==="visible")},xO=function(t){return Z1(t,"overflowY")},wO=function(t){return Z1(t,"overflowX")},Nx=function(t,n){var r=n.ownerDocument,s=n;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var i=X1(t,s);if(i){var c=K1(t,s),u=c[1],f=c[2];if(u>f)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},SO=function(t){var n=t.scrollTop,r=t.scrollHeight,s=t.clientHeight;return[n,r,s]},EO=function(t){var n=t.scrollLeft,r=t.scrollWidth,s=t.clientWidth;return[n,r,s]},X1=function(t,n){return t==="v"?xO(n):wO(n)},K1=function(t,n){return t==="v"?SO(n):EO(n)},_O=function(t,n){return t==="h"&&n==="rtl"?-1:1},CO=function(t,n,r,s,i){var c=_O(t,window.getComputedStyle(n).direction),u=c*s,f=r.target,g=n.contains(f),p=!1,v=u>0,y=0,w=0;do{if(!f)break;var C=K1(t,f),S=C[0],E=C[1],_=C[2],R=E-_-c*S;(S||R)&&X1(t,f)&&(y+=R,w+=S);var O=f.parentNode;f=O&&O.nodeType===Node.DOCUMENT_FRAGMENT_NODE?O.host:O}while(!g&&f!==document.body||g&&(n.contains(f)||n===f));return(v&&Math.abs(y)<1||!v&&Math.abs(w)<1)&&(p=!0),p},Gc=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},Rx=function(t){return[t.deltaX,t.deltaY]},Ax=function(t){return t&&"current"in t?t.current:t},NO=function(t,n){return t[0]===n[0]&&t[1]===n[1]},RO=function(t){return`
|
||||
.block-interactivity-`.concat(t,` {pointer-events: none;}
|
||||
.allow-interactivity-`).concat(t,` {pointer-events: all;}
|
||||
`)},AO=0,wo=[];function jO(t){var n=b.useRef([]),r=b.useRef([0,0]),s=b.useRef(),i=b.useState(AO++)[0],c=b.useState(Y1)[0],u=b.useRef(t);b.useEffect(function(){u.current=t},[t]),b.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var E=Kk([t.lockRef.current],(t.shards||[]).map(Ax),!0).filter(Boolean);return E.forEach(function(_){return _.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),E.forEach(function(_){return _.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var f=b.useCallback(function(E,_){if("touches"in E&&E.touches.length===2||E.type==="wheel"&&E.ctrlKey)return!u.current.allowPinchZoom;var R=Gc(E),O=r.current,A="deltaX"in E?E.deltaX:O[0]-R[0],D="deltaY"in E?E.deltaY:O[1]-R[1],B,I=E.target,U=Math.abs(A)>Math.abs(D)?"h":"v";if("touches"in E&&U==="h"&&I.type==="range")return!1;var $=window.getSelection(),me=$&&$.anchorNode,fe=me?me===I||me.contains(I):!1;if(fe)return!1;var pe=Nx(U,I);if(!pe)return!0;if(pe?B=U:(B=U==="v"?"h":"v",pe=Nx(U,I)),!pe)return!1;if(!s.current&&"changedTouches"in E&&(A||D)&&(s.current=B),!B)return!0;var re=s.current||B;return CO(re,_,E,re==="h"?A:D)},[]),g=b.useCallback(function(E){var _=E;if(!(!wo.length||wo[wo.length-1]!==c)){var R="deltaY"in _?Rx(_):Gc(_),O=n.current.filter(function(B){return B.name===_.type&&(B.target===_.target||_.target===B.shadowParent)&&NO(B.delta,R)})[0];if(O&&O.should){_.cancelable&&_.preventDefault();return}if(!O){var A=(u.current.shards||[]).map(Ax).filter(Boolean).filter(function(B){return B.contains(_.target)}),D=A.length>0?f(_,A[0]):!u.current.noIsolation;D&&_.cancelable&&_.preventDefault()}}},[]),p=b.useCallback(function(E,_,R,O){var A={name:E,delta:_,target:R,should:O,shadowParent:TO(R)};n.current.push(A),setTimeout(function(){n.current=n.current.filter(function(D){return D!==A})},1)},[]),v=b.useCallback(function(E){r.current=Gc(E),s.current=void 0},[]),y=b.useCallback(function(E){p(E.type,Rx(E),E.target,f(E,t.lockRef.current))},[]),w=b.useCallback(function(E){p(E.type,Gc(E),E.target,f(E,t.lockRef.current))},[]);b.useEffect(function(){return wo.push(c),t.setCallbacks({onScrollCapture:y,onWheelCapture:y,onTouchMoveCapture:w}),document.addEventListener("wheel",g,xo),document.addEventListener("touchmove",g,xo),document.addEventListener("touchstart",v,xo),function(){wo=wo.filter(function(E){return E!==c}),document.removeEventListener("wheel",g,xo),document.removeEventListener("touchmove",g,xo),document.removeEventListener("touchstart",v,xo)}},[]);var C=t.removeScrollBar,S=t.inert;return b.createElement(b.Fragment,null,S?b.createElement(c,{styles:RO(i)}):null,C?b.createElement(vO,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function TO(t){for(var n=null;t!==null;)t instanceof ShadowRoot&&(n=t.host,t=t.host),t=t.parentNode;return n}const kO=sO(G1,jO);var Vu=b.forwardRef(function(t,n){return b.createElement(Hu,Aa({},t,{ref:n,sideCar:kO}))});Vu.classNames=Hu.classNames;var OO=function(t){if(typeof document>"u")return null;var n=Array.isArray(t)?t[0]:t;return n.ownerDocument.body},So=new WeakMap,Yc=new WeakMap,Zc={},Om=0,Q1=function(t){return t&&(t.host||Q1(t.parentNode))},MO=function(t,n){return n.map(function(r){if(t.contains(r))return r;var s=Q1(r);return s&&t.contains(s)?s:(console.error("aria-hidden",r,"in not contained inside",t,". Doing nothing"),null)}).filter(function(r){return!!r})},DO=function(t,n,r,s){var i=MO(n,Array.isArray(t)?t:[t]);Zc[r]||(Zc[r]=new WeakMap);var c=Zc[r],u=[],f=new Set,g=new Set(i),p=function(y){!y||f.has(y)||(f.add(y),p(y.parentNode))};i.forEach(p);var v=function(y){!y||g.has(y)||Array.prototype.forEach.call(y.children,function(w){if(f.has(w))v(w);else try{var C=w.getAttribute(s),S=C!==null&&C!=="false",E=(So.get(w)||0)+1,_=(c.get(w)||0)+1;So.set(w,E),c.set(w,_),u.push(w),E===1&&S&&Yc.set(w,!0),_===1&&w.setAttribute(r,"true"),S||w.setAttribute(s,"true")}catch(R){console.error("aria-hidden: cannot operate on ",w,R)}})};return v(n),f.clear(),Om++,function(){u.forEach(function(y){var w=So.get(y)-1,C=c.get(y)-1;So.set(y,w),c.set(y,C),w||(Yc.has(y)||y.removeAttribute(s),Yc.delete(y)),C||y.removeAttribute(r)}),Om--,Om||(So=new WeakMap,So=new WeakMap,Yc=new WeakMap,Zc={})}},Yh=function(t,n,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(t)?t:[t]),i=OO(t);return i?(s.push.apply(s,Array.from(i.querySelectorAll("[aria-live], script"))),DO(s,i,r,"aria-hidden")):function(){return null}},Iu="Dialog",[W1]=Ts(Iu),[zO,ba]=W1(Iu),J1=t=>{const{__scopeDialog:n,children:r,open:s,defaultOpen:i,onOpenChange:c,modal:u=!0}=t,f=b.useRef(null),g=b.useRef(null),[p,v]=Fh({prop:s,defaultProp:i??!1,onChange:c,caller:Iu});return m.jsx(zO,{scope:n,triggerRef:f,contentRef:g,contentId:To(),titleId:To(),descriptionId:To(),open:p,onOpenChange:v,onOpenToggle:b.useCallback(()=>v(y=>!y),[v]),modal:u,children:r})};J1.displayName=Iu;var ew="DialogTrigger",LO=b.forwardRef
Line truncated
|
||||
|
||||
If you want to hide the \`${n.titleName}\`, you can wrap it with our VisuallyHidden component.
|
||||
|
||||
For more information, see https://radix-ui.com/primitives/docs/components/${n.docsSlug}`;return b.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},qO="DialogDescriptionWarning",FO=({contentRef:t,descriptionId:n})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${fw(qO).contentName}}.`;return b.useEffect(()=>{var c;const i=(c=t.current)==null?void 0:c.getAttribute("aria-describedby");n&&i&&(document.getElementById(n)||console.warn(s))},[s,t,n]),null},$O=J1,GO=nw,mw=aw,hw=rw,YO=ow,ZO=lw,XO=uw,KO=Symbol.for("react.lazy"),du=Au[" use ".trim().toString()];function QO(t){return typeof t=="object"&&t!==null&&"then"in t}function pw(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===KO&&"_payload"in t&&QO(t._payload)}function gw(t){const n=WO(t),r=b.forwardRef((s,i)=>{let{children:c,...u}=s;pw(c)&&typeof du=="function"&&(c=du(c._payload));const f=b.Children.toArray(c),g=f.find(eM);if(g){const p=g.props.children,v=f.map(y=>y===g?b.Children.count(p)>1?b.Children.only(null):b.isValidElement(p)?p.props.children:null:y);return m.jsx(n,{...u,ref:i,children:b.isValidElement(p)?b.cloneElement(p,void 0,v):null})}return m.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}var yw=gw("Slot");function WO(t){const n=b.forwardRef((r,s)=>{let{children:i,...c}=r;if(pw(i)&&typeof du=="function"&&(i=du(i._payload)),b.isValidElement(i)){const u=nM(i),f=tM(c,i.props);return i.type!==b.Fragment&&(f.ref=s?wl(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var JO=Symbol("radix.slottable");function eM(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===JO}function tM(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function nM(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var aM=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rM=aM.reduce((t,n)=>{const r=gw(`Primitive.${n}`),s=b.forwardRef((i,c)=>{const{asChild:u,...f}=i,g=u?r:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m.jsx(g,{...f,ref:c})});return s.displayName=`Primitive.${n}`,{...t,[n]:s}},{});function sM(t){const[n,r]=b.useState(void 0);return Fr(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const s=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const c=i[0];let u,f;if("borderBoxSize"in c){const g=c.borderBoxSize,p=Array.isArray(g)?g[0]:g;u=p.inlineSize,f=p.blockSize}else u=t.offsetWidth,f=t.offsetHeight;r({width:u,height:f})});return s.observe(t,{box:"border-box"}),()=>s.unobserve(t)}else r(void 0)},[t]),n}const oM=["top","right","bottom","left"],$r=Math.min,In=Math.max,fu=Math.round,Xc=Math.floor,Oa=t=>({x:t,y:t}),iM={left:"right",right:"left",bottom:"top",top:"bottom"};function ch(t,n,r){return In(t,$r(n,r))}function or(t,n){return typeof t=="function"?t(n):t}function ir(t){return t.split("-")[0]}function Zo(t){return t.split("-")[1]}function Qh(t){return t==="x"?"y":"x"}function Wh(t){return t==="y"?"height":"width"}function Ta(t){const n=t[0];return n==="t"||n==="b"?"y":"x"}function Jh(t){return Qh(Ta(t))}function lM(t,n,r){r===void 0&&(r=!1);const s=Zo(t),i=Jh(t),c=Wh(i);let u=i==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return n.reference[c]>n.floating[c]&&(u=mu(u)),[u,mu(u)]}function cM(t){const n=mu(t);return[uh(t),n,uh(n)]}function uh(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}const jx=["left","right"],Tx=["right","left"],uM=["top","bottom"],dM=["bottom","top"];function fM(t,n,r){switch(t){case"top":case"bottom":return r?n?Tx:jx:n?jx:Tx;case"left":case"right":return n?uM:dM;default:return[]}}function mM(t,n,r,s){const i=Zo(t);let c=fM(ir(t),r==="start",s);return i&&(c=c.map(u=>u+"-"+i),n&&(c=c.concat(c.map(uh)))),c}function mu(t){const n=ir(t);return iM[n]+t.slice(n.length)}function hM(t){return{top:0,right:0,bottom:0,left:0,...t}}function vw(t){return typeof t!="number"?hM(t):{top:t,right:t,bottom:t,left:t}}function hu(t){const{x:n,y:r,width:s,height:i}=t;return{width:s,height:i,top:r,left:n,right:n+s,bottom:r+i,x:n,y:r}}function kx(t,n,r){let{reference:s,floating:i}=t;const c=Ta(n),u=Jh(n),f=Wh(u),g=ir(n),p=c==="y",v=s.x+s.width/2-i.width/2,y=s.y+s.height/2-i.height/2,w=s[f]/2-i[f]/2;let C;switch(g){case"top":C={x:v,y:s.y-i.height};break;case"bottom":C={x:v,y:s.y+s.height};break;case"right":C={x:s.x+s.width,y};break;case"left":C={x:s.x-i.width,y};brea
Line truncated
|
||||
[data-state=closed]
|
||||
){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function SD(t,n){typeof t=="function"?t(n):t!=null&&(t.current=n)}function ED(...t){return n=>t.forEach(r=>SD(r,n))}function gS(...t){return b.useCallback(ED(...t),t)}const Vx=t=>{switch(t){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return t}};function Um(t,n){if(!t)return()=>{};const r=t.style.cssText;return Object.assign(t.style,n),()=>{t.style.cssText=r}}function _D(...t){return(...n)=>{for(const r of t)typeof r=="function"&&r(...n)}}const Bm={DURATION:.5,EASE:[.32,.72,0,1]},CD=8,ND=26,RD=()=>()=>{};function AD(){const{direction:t,isOpen:n,shouldScaleBackground:r,setBackgroundColorOnScale:s,noBodyStyles:i}=Ku(),c=oe.useRef(null),u=b.useMemo(()=>document.body.style.backgroundColor,[]);function f(){return(window.innerWidth-ND)/window.innerWidth}oe.useEffect(()=>{if(n&&r){c.current&&clearTimeout(c.current);const g=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!g)return;_D(s&&!i?Um(document.body,{background:"black"}):RD,Um(g,{transformOrigin:Vx(t)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Bm.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Bm.EASE.join(",")})`}));const p=Um(g,{borderRadius:`${CD}px`,overflow:"hidden",...Vx(t)?{transform:`scale(${f()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${f()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{p(),c.current=window.setTimeout(()=>{u?document.body.style.background=u:document.body.style.removeProperty("background")},Bm.DURATION*1e3)}}},[n,r,u])}const jD=oe.forwardRef(function({...t},n){const{overlayRef:r,snapPoints:s,onRelease:i,shouldFade:c,isOpen:u,modal:f,shouldAnimate:g}=Ku(),p=gS(n,r),v=s&&s.length>0;if(!f)return null;const y=oe.useCallback(w=>i(w),[i]);return oe.createElement(mw,{onMouseUp:y,ref:p,"data-vaul-overlay":"","data-vaul-snap-points":u&&v?"true":"false","data-vaul-snap-points-overlay":u&&c?"true":"false","data-vaul-animate":g!=null&&g.current?"true":"false",...t})});jD.displayName="Drawer.Overlay";const TD=oe.forwardRef(function({onPointerDownOutside:t,style:n,onOpenAutoFocus:r,...s},i){const{drawerRef:c,onPress:u,onRelease:f,onDrag:g,keyboardIsOpen:p,snapPointsOffset:v,activeSnapPointIndex:y,modal:w,isOpen:C,direction:S,snapPoints:E,container:_,handleOnly:R,shouldAnimate:O,autoFocus:A}=Ku(),[D,B]=oe.useState(!1),I=gS(i,c),U=oe.useRef(null),$=oe.useRef(null),me=oe.useRef(!1),fe=E&&E.length>0;AD();const pe=(Y,ue,ye=0)=>{if(me.current)return!0;const j=Math.abs(Y.y),X=Math.abs(Y.x),te=X>j,se=["bottom","right"].includes(ue)?1:-1;if(ue==="left"||ue==="right"){if(!(Y.x*se<0)&&X>=0&&X<=ye)return te}else if(!(Y.y*se<0)&&j>=0&&j<=ye)return!te;return me.current=!0,!0};oe.useEffect(()=>{fe&&window.requestAnimationFrame(()=>{B(!0)})},[]);function re(Y){U.current=null,me.current=!1,f(Y)}return oe.createElement(hw,{"data-vaul-drawer-direction":S,"data-vaul-drawer":"","data-vaul-delayed-snap-points":D?"true":"false","data-vaul-snap-points":C&&fe?"true":"false","data-vaul-custom-container":_?"true":"false","data-vaul-animate":O!=null&&O.current?"true":"false",...s,ref:I,style:v&&v.length>0?{"--snap-point-height":`${v[y??0]}px`,...n}:n,onPointerDown:Y=>{R||(s.onPointerDown==null||s.onPointerDown.call(s,Y),U.current={x:Y.pageX,y:Y.pageY},u(Y))},onOpenAutoFocus:Y=>{r==null||r(Y),A||Y.preventDefault()},onPointerDownOutside:Y=>{i
Line truncated
|
||||
[data-input-otp] {
|
||||
--nojs-bg: white !important;
|
||||
--nojs-fg: black !important;
|
||||
|
||||
background-color: var(--nojs-bg) !important;
|
||||
color: var(--nojs-fg) !important;
|
||||
caret-color: var(--nojs-fg) !important;
|
||||
letter-spacing: .25em !important;
|
||||
text-align: center !important;
|
||||
border: 1px solid var(--nojs-fg) !important;
|
||||
border-radius: 4px !important;
|
||||
width: 100% !important;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
[data-input-otp] {
|
||||
--nojs-bg: black !important;
|
||||
--nojs-fg: white !important;
|
||||
}
|
||||
}`,BS="Popover",[PS]=Ts(BS,[Yu]),Ju=Yu(),[qL,Qr]=PS(BS),HS="PopoverAnchor",Z5=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(HS,r),c=Ju(r),{onCustomAnchorAdd:u,onCustomAnchorRemove:f}=i;return b.useEffect(()=>(u(),()=>f()),[u,f]),m.jsx(sp,{...c,...s,ref:n})});Z5.displayName=HS;var VS="PopoverTrigger",X5=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(VS,r),c=Ju(r),u=Wt(n,i.triggerRef),f=m.jsx(Mt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":GS(i.open),...s,ref:u,onClick:Xe(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?f:m.jsx(sp,{asChild:!0,...c,children:f})});X5.displayName=VS;var bp="PopoverPortal",[K5,Q5]=PS(bp,{forceMount:void 0}),IS=t=>{const{__scopePopover:n,forceMount:r,children:s,container:i}=t,c=Qr(bp,n);return m.jsx(K5,{scope:n,forceMount:r,children:m.jsx(za,{present:r||c.open,children:m.jsx(Pu,{asChild:!0,container:i,children:s})})})};IS.displayName=bp;var Bo="PopoverContent",qS=b.forwardRef((t,n)=>{const r=Q5(Bo,t.__scopePopover),{forceMount:s=r.forceMount,...i}=t,c=Qr(Bo,t.__scopePopover);return m.jsx(za,{present:s||c.open,children:c.modal?m.jsx(J5,{...i,ref:n}):m.jsx(e3,{...i,ref:n})})});qS.displayName=Bo;var W5=zo("PopoverContent.RemoveScroll"),J5=b.forwardRef((t,n)=>{const r=Qr(Bo,t.__scopePopover),s=b.useRef(null),i=Wt(n,s),c=b.useRef(!1);return b.useEffect(()=>{const u=s.current;if(u)return Yh(u)},[]),m.jsx(Vu,{as:W5,allowPinchZoom:!0,children:m.jsx(FS,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Xe(t.onCloseAutoFocus,u=>{var f;u.preventDefault(),c.current||(f=r.triggerRef.current)==null||f.focus()}),onPointerDownOutside:Xe(t.onPointerDownOutside,u=>{const f=u.detail.originalEvent,g=f.button===0&&f.ctrlKey===!0,p=f.button===2||g;c.current=p},{checkForDefaultPrevented:!1}),onFocusOutside:Xe(t.onFocusOutside,u=>u.preventDefault(),{checkForDefaultPrevented:!1})})})}),e3=b.forwardRef((t,n)=>{const r=Qr(Bo,t.__scopePopover),s=b.useRef(!1),i=b.useRef(!1);return m.jsx(FS,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var u,f;(u=t.onCloseAutoFocus)==null||u.call(t,c),c.defaultPrevented||(s.current||(f=r.triggerRef.current)==null||f.focus(),c.preventDefault()),s.current=!1,i.current=!1},onInteractOutside:c=>{var g,p;(g=t.onInteractOutside)==null||g.call(t,c),c.defaultPrevented||(s.current=!0,c.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=c.target;((p=r.triggerRef.current)==null?void 0:p.contains(u))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&i.current&&c.preventDefault()}})}),FS=b.forwardRef((t,n)=>{const{__scopePopover:r,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:c,disableOutsidePointerEvents:u,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:p,onInteractOutside:v,...y}=t,w=Qr(Bo,r),C=Ju(r);return Gh(),m.jsx(Bu,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:i,onUnmountAutoFocus:c,children:m.jsx(Uu,{asChild:!0,disableOutsidePointerEvents:u,onInteractOutside:v,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:p,onDismiss:()=>w.onOpenChange(!1),children:m.jsx(Pw,{"data-state":GS(w.open),role:"dialog",id:w.contentId,...C,...y,ref:n,style:{...y.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),$S="PopoverClose",t3=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr($S,r);return m.jsx(Mt.button,{type:"button",...s,ref:n,onClick:Xe(t.onClick,()=>i.onOpenChange(!1))})});t3.displayName=$S;var n3="PopoverArrow",a3=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Ju(r);return m.jsx(Hw,{...i,...s,ref:n})});a3.displayName=n3;function GS(t){return t?"open":"closed"}var r3=IS,YS=qS;const xp=b.createContext(null);xp.displayName="PanelGroupContext";const qn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandleId:"data-panel-resize-handle-id"},wp=10,Mo=b.useLayoutEffect,e0=Au.useId,s3=typeof e0=="function"?e0:()=>null;let o3=0;function ZS(t=null){const n=s3(),r=b.useRef(t||n||null);return r.current===null&&(r.current=""+o3++),t??r.current}function XS({children:t,className:n="",collapsedSize:r,collapsible:s,defaultSize:i,forwardedRef:c,id:u,maxSize:f,minSize:g,onCollapse:p,onExpand:v,onResize:y,order:w,style:C,tagName:S="div",...E}){const _=b.useContext(xp);if(_===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:R,expandPanel:O,getPanelSize:A,getPanelStyle:D,groupId:B,isPanelCollapsed:I,reevaluatePanelConstraints:U,registerPanel:$,resizeP
Line truncated
|
||||
`)){const ke=Ee.indexOf(":");if(ke>0){const ce=Ee.slice(0,ke).trim(),_e=Ee.slice(ke+1).trim();ce&&(ae[ce]=_e)}}}return ae},ge=async()=>{if(!V)return;if(!t){Fe.error("apiUrl nao definida no store");return}Y(!0),ye(null),X(null);const q=t.replace(/\/$/,""),ae=W(),Ee=`${q}${ae}`,ke={...le(D)};L&&(ke.apikey=L);let ce;if(["POST","PUT","PATCH","DELETE"].includes(V.method)&&O.trim())try{ce=JSON.parse(O),ke["Content-Type"]=ke["Content-Type"]||"application/json"}catch{X("Body nao e um JSON valido."),Y(!1);return}const be=performance.now();try{const Re=await Tt.request({url:Ee,method:V.method,headers:ke,data:ce,validateStatus:()=>!0,transformRequest:Le=>Le===void 0?void 0:JSON.stringify(Le)}),Pe=Math.round(performance.now()-be),qe={},Ue=Re.headers;if(Ue instanceof ek)Ue.forEach((Le,pt)=>{qe[pt]=String(Le)});else if(Ue&&typeof Ue=="object")for(const[Le,pt]of Object.entries(Ue))qe[Le]=String(pt);ye({status:Re.status,statusText:Re.statusText||"",durationMs:Pe,data:Re.data,headers:qe,finalUrl:Ee,request:{method:V.method,url:Ee,headers:ke,body:ce}})}catch(Re){const Pe=Math.round(performance.now()-be),qe=(Re==null?void 0:Re.message)||"Erro de rede desconhecido";X(`${qe} (em ${Pe}ms)`)}finally{Y(!1)}};return m.jsxs("div",{className:"flex h-[calc(100vh-4rem)] overflow-hidden",children:[m.jsxs("aside",{className:"flex w-80 flex-col border-r border-sidebar-border bg-sidebar/60",children:[m.jsxs("div",{className:"border-b border-sidebar-border p-3",children:[m.jsxs("h2",{className:"mb-2 flex items-center gap-2 text-sm font-semibold text-foreground",children:[m.jsx(wR,{className:"h-4 w-4 text-purple-500"}),"Endpoints",m.jsx("button",{type:"button",onClick:te,className:"ml-auto rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground",title:"Recarregar swagger",children:m.jsx(nA,{className:"h-3.5 w-3.5"})})]}),m.jsxs("div",{className:"relative",children:[m.jsx(K0,{className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),m.jsx("input",{type:"text",placeholder:"Filtrar por path, metodo, tag...",value:v,onChange:q=>y(q.target.value),className:"w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-2 text-xs text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"})]})]}),m.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[u&&m.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[m.jsx(ol,{className:"mx-auto mb-2 h-5 w-5 animate-spin"}),"Carregando swagger..."]}),g&&m.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive",children:g}),!u&&!g&&T.length===0&&m.jsx("p",{className:"p-4 text-center text-xs text-muted-foreground",children:"Nenhum endpoint encontrado."}),T.map(([q,ae])=>m.jsxs("div",{className:"mb-3",children:[m.jsx("p",{className:"mb-1 px-2 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:q}),m.jsx("div",{className:"space-y-0.5",children:ae.map(Ee=>{const ke=C0[Ee.method.toLowerCase()]||"",ce=Ee.key===w;return m.jsxs("button",{onClick:()=>C(Ee.key),className:`group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs transition-colors ${ce?"bg-primary/10 ring-1 ring-primary/40":"hover:bg-accent"}`,children:[m.jsx("span",{className:`inline-block w-12 shrink-0 rounded border px-1.5 py-0.5 text-center font-mono text-[10px] font-bold ${ke}`,children:Ee.method}),m.jsx("span",{className:"flex-1 truncate font-mono text-foreground",children:Ee.path}),m.jsx(Qm,{className:"h-3 w-3 shrink-0 text-muted-foreground opacity-0 group-hover:opacity-100"})]},Ee.key)})})]},q))]})]}),m.jsx("section",{className:"flex flex-1 flex-col overflow-hidden",children:V?m.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[m.jsxs("div",{className:"border-b border-sidebar-border bg-sidebar/30 px-5 py-3",children:[m.jsxs("div",{className:"flex items-center gap-3",children:[m.jsx("span",{className:`rounded border px-2 py-0.5 font-mono text-xs font-bold ${C0[V.method.toLowerCase()]||""}`,children:V.method}),m.jsx("code",{className:"flex-1 truncate font-mono text-sm text-foreground",children:V.path}),m.jsx("button",{type:"button",onClick:ge,disabled:re,className:"inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:re?m.jsxs(m.Fragment,{children:[m.jsx(ol,{className:"h-3.5 w-3.5 animate-spin"}),"Executando..."]}):m.jsxs(m.Fragment,{children:[m.jsx(XR,{className:"h-3.5 w-3.5"}),"Executar"]})})]}),V.operation.summary&&m.jsx("p",{className:"mt-2 text-xs text-foreground/80",children:V.operation.summary})]}),m.jsxs("div",{className:"grid flex-1 grid-cols-1 gap-0 overflow-hidden lg:grid-cols-2",children:[m.jsx("div",{className:"overflow-y-auto border-r border-sidebar-border p-5",children:m.jsxs("div",{className:"space-y-4",children:[m.jsxs("div",{className:"rounded-md border bor
Line truncated
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Evolution GO Manager</title>
|
||||
<script type="module" crossorigin src="/assets/index-B7iM18f_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-B6NZfWVh.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,66 @@
|
||||
# Evolution Passkey Helper
|
||||
|
||||
Extensão de navegador que conclui o pareamento por **chave de acesso (passkey)**
|
||||
do WhatsApp Web para o Evolution GO.
|
||||
|
||||
Desde que o WhatsApp passou a exigir passkey ao vincular um novo dispositivo, o
|
||||
QR Code sozinho não basta em algumas contas: é preciso executar uma cerimônia
|
||||
WebAuthn (`navigator.credentials.get`), e o navegador só permite isso quando o
|
||||
código roda no origin da _relying party_ — `whatsapp.com`. Esta extensão roda
|
||||
**somente** em `web.whatsapp.com` e serve apenas como "palco" com o origin
|
||||
correto para a biometria/PIN. Ela **não** interage com o login do WhatsApp Web e
|
||||
**não** coleta nem envia dados para terceiros.
|
||||
|
||||
## Como funciona
|
||||
|
||||
1. Você escaneia o QR normalmente no Evolution (manager). Se a conta exigir
|
||||
passkey, o painel de conexão mostra o botão **"Abrir WhatsApp Web"**.
|
||||
2. Esse botão abre `https://web.whatsapp.com/#wapk=<payload>`, onde `payload` é
|
||||
um base64url de `{ "t": "<token da instância>", "b": "<url base da API>" }`.
|
||||
3. O content script lê esse payload, consulta o status da cerimônia na API,
|
||||
executa a cerimônia WebAuthn no origin `whatsapp.com` e envia a assinatura de
|
||||
volta para o Evolution.
|
||||
4. Se o pareamento exigir confirmação manual do código, o painel mostra o código
|
||||
e um botão **"Confirmar código"**. Na maioria dos casos (QR escaneado antes),
|
||||
o Evolution confirma automaticamente e você só precisa voltar ao manager.
|
||||
|
||||
Nenhuma `host_permission` é necessária: as chamadas partem do origin
|
||||
`web.whatsapp.com` e o backend do Evolution já libera CORS para essa origem.
|
||||
|
||||
## Endpoints usados (Evolution GO)
|
||||
|
||||
- `GET {base}/passkey-ceremony/{token}` — status/desafio da cerimônia
|
||||
- `POST {base}/passkey-ceremony/{token}/response` — envia a assertion WebAuthn
|
||||
- `POST {base}/passkey-ceremony/{token}/confirm` — confirma o código (quando aplicável)
|
||||
|
||||
Onde `base` é a URL da sua API Evolution e `token` é o token da instância.
|
||||
|
||||
## Instalar no Google Chrome
|
||||
|
||||
1. Baixe/descompacte esta pasta (a que contém `manifest.json`).
|
||||
2. Abra `chrome://extensions`.
|
||||
3. Ative o **Modo do desenvolvedor** (canto superior direito).
|
||||
4. Clique em **Carregar sem compactação**.
|
||||
5. Selecione esta pasta.
|
||||
6. Volte ao Evolution e clique em **"Abrir WhatsApp Web"**.
|
||||
|
||||
## Instalar no Microsoft Edge
|
||||
|
||||
1. Baixe/descompacte esta pasta (a que contém `manifest.json`).
|
||||
2. Abra `edge://extensions`.
|
||||
3. Ative o **Modo de desenvolvedor** (canto inferior esquerdo).
|
||||
4. Clique em **Carregar sem pacote**.
|
||||
5. Selecione esta pasta.
|
||||
6. Volte ao Evolution e clique em **"Abrir WhatsApp Web"**.
|
||||
|
||||
## Dicas
|
||||
|
||||
- Use o navegador logado na mesma conta (Google/iCloud) onde a passkey do
|
||||
WhatsApp está salva, ou tenha o celular por perto para o fluxo de biometria.
|
||||
- A cerimônia tem validade curta. Se expirar, gere um novo QR no Evolution.
|
||||
|
||||
## Whitelabel
|
||||
|
||||
A extensão é genérica: nada de URL ou token fica embutido no código — tudo vem
|
||||
no `payload` da URL. Para personalizar nome/ícone, edite o `manifest.json` e o
|
||||
título/descrição do painel em `content.js`.
|
||||
@@ -0,0 +1,481 @@
|
||||
/*
|
||||
* Evolution Passkey Helper
|
||||
* ------------------------
|
||||
* Executa a cerimonia WebAuthn (passkey) do WhatsApp Web no dominio correto
|
||||
* (web.whatsapp.com) para concluir um pareamento iniciado pelo Evolution GO.
|
||||
*
|
||||
* Fluxo:
|
||||
* 1. O manager/CRM abre https://web.whatsapp.com/#wapk=<payload>, onde payload
|
||||
* e um base64url de JSON { t: <token_da_instancia>, b: <url_base_da_api> }.
|
||||
* 2. Este content script le o payload, faz polling do status da cerimonia na
|
||||
* API, e quando o desafio (publicKey) esta disponivel executa
|
||||
* navigator.credentials.get() (permitido pois roda no origin whatsapp.com).
|
||||
* 3. A assertion e enviada de volta para a API; quando o pareamento exige a
|
||||
* confirmacao manual do codigo, um botao de confirmar e exibido.
|
||||
*
|
||||
* Nenhuma host_permission e necessaria: as chamadas partem do origin
|
||||
* web.whatsapp.com e o backend libera CORS para essa origem.
|
||||
*
|
||||
* A extensao e whitelabel: nada e hardcoded, tudo vem no payload da URL.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var STORAGE_KEY = "__evo_wapk_ceremony__";
|
||||
var POLL_INTERVAL_MS = 2000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// base64url helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
function b64uToBuf(value) {
|
||||
var b64 = String(value || "").replace(/-/g, "+").replace(/_/g, "/");
|
||||
while (b64.length % 4) b64 += "=";
|
||||
var bin = atob(b64);
|
||||
var bytes = new Uint8Array(bin.length);
|
||||
for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
function bufToB64u(buf) {
|
||||
var bytes = new Uint8Array(buf);
|
||||
var bin = "";
|
||||
for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
||||
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ceremony payload (URL hash -> sessionStorage)
|
||||
// ---------------------------------------------------------------------------
|
||||
function readCeremonyFromHash() {
|
||||
try {
|
||||
var m = (location.hash || "").match(/[#&]wapk=([^&]+)/);
|
||||
if (!m) return null;
|
||||
var json = atob(m[1].replace(/-/g, "+").replace(/_/g, "/"));
|
||||
var obj = JSON.parse(json);
|
||||
if (obj && obj.t && obj.b) return { t: obj.t, b: obj.b };
|
||||
} catch (e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getCeremony() {
|
||||
var fromHash = readCeremonyFromHash();
|
||||
if (fromHash) {
|
||||
try {
|
||||
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(fromHash));
|
||||
} catch (e) {}
|
||||
try {
|
||||
history.replaceState(null, "", location.pathname + location.search);
|
||||
} catch (e) {}
|
||||
return fromHash;
|
||||
}
|
||||
try {
|
||||
var raw = sessionStorage.getItem(STORAGE_KEY);
|
||||
if (raw) return JSON.parse(raw);
|
||||
} catch (e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
function clearCeremony() {
|
||||
try {
|
||||
sessionStorage.removeItem(STORAGE_KEY);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API calls (Evolution GO passkey ceremony endpoints)
|
||||
// ---------------------------------------------------------------------------
|
||||
function apiBase(cer) {
|
||||
return String(cer.b || "").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
async function fetchStatus(cer) {
|
||||
var res = await fetch(apiBase(cer) + "/passkey-ceremony/" + encodeURIComponent(cer.t), {
|
||||
method: "GET",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
var json = await res.json().catch(function () {
|
||||
return null;
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error((json && json.error) || "Falha ao consultar o status (HTTP " + res.status + ").");
|
||||
}
|
||||
return (json && json.data) || json || {};
|
||||
}
|
||||
|
||||
async function sendResponse(cer, webauthnResponse) {
|
||||
var res = await fetch(apiBase(cer) + "/passkey-ceremony/" + encodeURIComponent(cer.t) + "/response", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(webauthnResponse),
|
||||
});
|
||||
var json = await res.json().catch(function () {
|
||||
return null;
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error((json && json.error) || "Falha ao enviar a chave de acesso.");
|
||||
}
|
||||
}
|
||||
|
||||
async function sendConfirm(cer) {
|
||||
var res = await fetch(apiBase(cer) + "/passkey-ceremony/" + encodeURIComponent(cer.t) + "/confirm", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
var json = await res.json().catch(function () {
|
||||
return null;
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error((json && json.error) || "Falha ao confirmar o codigo.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WebAuthn ceremony
|
||||
// ---------------------------------------------------------------------------
|
||||
function buildPublicKeyOptions(pk) {
|
||||
return {
|
||||
challenge: b64uToBuf(pk.challenge),
|
||||
timeout: pk.timeout || 60000,
|
||||
rpId: pk.rpId || "whatsapp.com",
|
||||
allowCredentials: (pk.allowCredentials || []).map(function (c) {
|
||||
return {
|
||||
type: c.type || "public-key",
|
||||
id: b64uToBuf(c.id),
|
||||
transports: c.transports,
|
||||
};
|
||||
}),
|
||||
userVerification: pk.userVerification || "required",
|
||||
};
|
||||
}
|
||||
|
||||
function toWebAuthnResponse(cred) {
|
||||
var r = cred.response;
|
||||
var body = {
|
||||
id: cred.id,
|
||||
rawId: bufToB64u(cred.rawId),
|
||||
type: cred.type,
|
||||
response: {
|
||||
clientDataJSON: bufToB64u(r.clientDataJSON),
|
||||
authenticatorData: bufToB64u(r.authenticatorData),
|
||||
signature: bufToB64u(r.signature),
|
||||
},
|
||||
};
|
||||
if (r.userHandle && r.userHandle.byteLength) {
|
||||
body.response.userHandle = bufToB64u(r.userHandle);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UI
|
||||
// ---------------------------------------------------------------------------
|
||||
var prefersDark = false;
|
||||
try {
|
||||
prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
} catch (e) {}
|
||||
|
||||
var THEME = prefersDark
|
||||
? { bg: "#111b21", fg: "#e9edef", sub: "#8696a0", border: "#25d366", card: "#202c33" }
|
||||
: { bg: "#ffffff", fg: "#111b21", sub: "#667781", border: "#25d366", card: "#f0f2f5" };
|
||||
|
||||
function el(tag, styles, text) {
|
||||
var node = document.createElement(tag);
|
||||
if (styles) node.setAttribute("style", styles);
|
||||
if (text != null) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
var PANEL_STYLE = [
|
||||
"position:fixed",
|
||||
"top:18px",
|
||||
"right:18px",
|
||||
"z-index:2147483647",
|
||||
"width:340px",
|
||||
"max-width:calc(100vw - 36px)",
|
||||
"background:" + THEME.bg,
|
||||
"color:" + THEME.fg,
|
||||
"border:1px solid " + THEME.border,
|
||||
"border-radius:14px",
|
||||
"box-shadow:0 12px 34px rgba(0,0,0,0.28)",
|
||||
"font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif",
|
||||
"padding:18px",
|
||||
].join(";");
|
||||
|
||||
var BTN_STYLE = [
|
||||
"display:block",
|
||||
"width:100%",
|
||||
"box-sizing:border-box",
|
||||
"background:#25d366",
|
||||
"color:#04391f",
|
||||
"border:none",
|
||||
"border-radius:9px",
|
||||
"padding:11px 14px",
|
||||
"font-size:14px",
|
||||
"font-weight:700",
|
||||
"cursor:pointer",
|
||||
"margin-top:12px",
|
||||
].join(";");
|
||||
|
||||
var ui = null;
|
||||
|
||||
function ensurePanel() {
|
||||
if (ui) return ui;
|
||||
|
||||
var panel = el("div", PANEL_STYLE);
|
||||
panel.id = "evo-wapk-panel";
|
||||
|
||||
var closeBtn = el(
|
||||
"div",
|
||||
"position:absolute;top:10px;right:14px;cursor:pointer;color:" + THEME.sub + ";font-size:20px;line-height:1;",
|
||||
"\u00d7"
|
||||
);
|
||||
closeBtn.title = "Fechar";
|
||||
closeBtn.addEventListener("click", function () {
|
||||
panel.remove();
|
||||
ui = null;
|
||||
stopPolling();
|
||||
});
|
||||
|
||||
var title = el("div", "font-size:15px;font-weight:800;margin-bottom:4px;display:flex;align-items:center;gap:8px;");
|
||||
title.appendChild(el("span", "font-size:16px;", "\uD83D\uDD11"));
|
||||
title.appendChild(el("span", null, "Chave de acesso (passkey)"));
|
||||
|
||||
var desc = el("div", "font-size:13px;line-height:1.5;color:" + THEME.sub + ";", "");
|
||||
|
||||
var codeBox = el(
|
||||
"div",
|
||||
"display:none;margin-top:12px;padding:10px;border-radius:9px;background:" +
|
||||
THEME.card +
|
||||
";text-align:center;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:22px;font-weight:800;letter-spacing:3px;"
|
||||
);
|
||||
|
||||
var status = el("div", "font-size:12px;margin-top:10px;color:" + THEME.sub + ";min-height:16px;");
|
||||
|
||||
var btn = el("button", BTN_STYLE, "Autenticar com chave de acesso");
|
||||
btn.style.display = "none";
|
||||
|
||||
panel.appendChild(closeBtn);
|
||||
panel.appendChild(title);
|
||||
panel.appendChild(desc);
|
||||
panel.appendChild(codeBox);
|
||||
panel.appendChild(btn);
|
||||
panel.appendChild(status);
|
||||
document.body.appendChild(panel);
|
||||
|
||||
ui = { panel: panel, desc: desc, codeBox: codeBox, status: status, btn: btn };
|
||||
return ui;
|
||||
}
|
||||
|
||||
function setDesc(text) {
|
||||
ensurePanel().desc.textContent = text;
|
||||
}
|
||||
|
||||
function setStatus(text, kind) {
|
||||
var u = ensurePanel();
|
||||
u.status.textContent = text || "";
|
||||
u.status.style.color = kind === "error" ? "#e02e2a" : kind === "success" ? "#1fa855" : THEME.sub;
|
||||
}
|
||||
|
||||
function showButton(label, onClick) {
|
||||
var u = ensurePanel();
|
||||
u.btn.textContent = label;
|
||||
u.btn.style.display = "block";
|
||||
u.btn.disabled = false;
|
||||
u.btn.style.opacity = "1";
|
||||
u.btn.style.cursor = "pointer";
|
||||
u.btn.onclick = onClick;
|
||||
}
|
||||
|
||||
function hideButton() {
|
||||
ensurePanel().btn.style.display = "none";
|
||||
}
|
||||
|
||||
function disableButton() {
|
||||
var u = ensurePanel();
|
||||
u.btn.disabled = true;
|
||||
u.btn.style.opacity = "0.6";
|
||||
u.btn.style.cursor = "default";
|
||||
}
|
||||
|
||||
function showCode(code) {
|
||||
var u = ensurePanel();
|
||||
if (code) {
|
||||
u.codeBox.textContent = code;
|
||||
u.codeBox.style.display = "block";
|
||||
} else {
|
||||
u.codeBox.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// State machine driven by polling
|
||||
// ---------------------------------------------------------------------------
|
||||
var pollTimer = null;
|
||||
var started = false; // ja passamos por algum estagio ativo
|
||||
var busy = false; // executando credentials.get / POST
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function schedulePoll(cer) {
|
||||
stopPolling();
|
||||
pollTimer = setTimeout(function () {
|
||||
poll(cer);
|
||||
}, POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
async function authenticate(cer, pk) {
|
||||
busy = true;
|
||||
disableButton();
|
||||
showCode("");
|
||||
setStatus("Aguardando a sua chave de acesso...");
|
||||
try {
|
||||
var cred = await navigator.credentials.get({ publicKey: buildPublicKeyOptions(pk) });
|
||||
if (!cred) throw new Error("Autenticacao cancelada.");
|
||||
setStatus("Enviando assinatura...");
|
||||
await sendResponse(cer, toWebAuthnResponse(cred));
|
||||
hideButton();
|
||||
setStatus("Assinatura enviada. Concluindo pareamento...");
|
||||
} catch (e) {
|
||||
setStatus((e && e.message) || String(e), "error");
|
||||
showButton("Tentar novamente", function () {
|
||||
authenticate(cer, pk);
|
||||
});
|
||||
} finally {
|
||||
busy = false;
|
||||
schedulePoll(cer);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmCode(cer) {
|
||||
busy = true;
|
||||
disableButton();
|
||||
setStatus("Confirmando...");
|
||||
try {
|
||||
await sendConfirm(cer);
|
||||
hideButton();
|
||||
setStatus("Confirmado. Concluindo pareamento...");
|
||||
} catch (e) {
|
||||
setStatus((e && e.message) || String(e), "error");
|
||||
showButton("Tentar novamente", function () {
|
||||
confirmCode(cer);
|
||||
});
|
||||
} finally {
|
||||
busy = false;
|
||||
schedulePoll(cer);
|
||||
}
|
||||
}
|
||||
|
||||
async function poll(cer) {
|
||||
if (busy) {
|
||||
schedulePoll(cer);
|
||||
return;
|
||||
}
|
||||
|
||||
var st;
|
||||
try {
|
||||
st = await fetchStatus(cer);
|
||||
} catch (e) {
|
||||
setStatus((e && e.message) || String(e), "error");
|
||||
schedulePoll(cer);
|
||||
return;
|
||||
}
|
||||
|
||||
var stage = st.stage || "";
|
||||
|
||||
switch (stage) {
|
||||
case "challenge":
|
||||
started = true;
|
||||
setDesc("Clique para concluir o pareamento com a sua chave de acesso do WhatsApp.");
|
||||
showCode("");
|
||||
if (!busy) {
|
||||
showButton("Autenticar com chave de acesso", function () {
|
||||
authenticate(cer, st.publicKey);
|
||||
});
|
||||
}
|
||||
schedulePoll(cer);
|
||||
break;
|
||||
|
||||
case "awaiting_confirmation":
|
||||
started = true;
|
||||
hideButton();
|
||||
showCode("");
|
||||
setDesc("Assinatura enviada ao WhatsApp.");
|
||||
setStatus("Aguardando codigo de confirmacao...");
|
||||
schedulePoll(cer);
|
||||
break;
|
||||
|
||||
case "confirmation":
|
||||
started = true;
|
||||
setDesc("Verifique se o codigo abaixo e o mesmo exibido no seu celular.");
|
||||
showCode(st.code);
|
||||
if (st.skipHandoffUX) {
|
||||
hideButton();
|
||||
setStatus("Confirmando automaticamente...");
|
||||
} else {
|
||||
setStatus("");
|
||||
showButton("Confirmar codigo", function () {
|
||||
confirmCode(cer);
|
||||
});
|
||||
}
|
||||
schedulePoll(cer);
|
||||
break;
|
||||
|
||||
case "confirmed":
|
||||
started = true;
|
||||
hideButton();
|
||||
showCode("");
|
||||
setDesc("Chave de acesso confirmada.");
|
||||
setStatus("Concluindo pareamento...");
|
||||
schedulePoll(cer);
|
||||
break;
|
||||
|
||||
case "error":
|
||||
started = true;
|
||||
showCode("");
|
||||
setDesc("Ocorreu um erro no pareamento por chave de acesso.");
|
||||
setStatus(st.error || "Erro desconhecido.", "error");
|
||||
// Permite reiniciar caso o backend reemita o desafio
|
||||
schedulePoll(cer);
|
||||
break;
|
||||
|
||||
case "":
|
||||
default:
|
||||
if (started) {
|
||||
// Estado limpo apos ter iniciado = pareamento concluido (PairSuccess)
|
||||
hideButton();
|
||||
showCode("");
|
||||
setDesc("Pareamento concluido com sucesso!");
|
||||
setStatus("Pode voltar ao Evolution. Esta aba ja pode ser fechada.", "success");
|
||||
clearCeremony();
|
||||
stopPolling();
|
||||
} else {
|
||||
setDesc("Aguardando o desafio de chave de acesso do WhatsApp...");
|
||||
setStatus("Escaneie o QR no Evolution para iniciar.");
|
||||
schedulePoll(cer);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Init
|
||||
// ---------------------------------------------------------------------------
|
||||
function start() {
|
||||
var cer = getCeremony();
|
||||
if (!cer) return;
|
||||
ensurePanel();
|
||||
setDesc("Preparando cerimonia de chave de acesso...");
|
||||
poll(cer);
|
||||
}
|
||||
|
||||
if (document.body) {
|
||||
start();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", start);
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Evolution Passkey Helper",
|
||||
"version": "1.0.0",
|
||||
"description": "Conclui o pareamento por chave de acesso (passkey) do WhatsApp Web para o Evolution GO. Roda apenas em web.whatsapp.com e nao coleta dados.",
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["https://web.whatsapp.com/*"],
|
||||
"js": ["content.js"],
|
||||
"run_at": "document_idle"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package call_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
call_service "github.com/evolution-foundation/evolution-go/pkg/call/service"
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type CallHandler interface {
|
||||
RejectCall(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type callHandler struct {
|
||||
callService call_service.CallService
|
||||
}
|
||||
|
||||
// Reject call
|
||||
// @Summary Reject call
|
||||
// @Description Reject call
|
||||
// @Tags Call
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body call_service.RejectCallStruct true "Call data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /call/reject [post]
|
||||
func (g *callHandler) RejectCall(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *call_service.RejectCallStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.callService.RejectCall(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
func NewCallHandler(
|
||||
callService call_service.CallService,
|
||||
) CallHandler {
|
||||
return &callHandler{
|
||||
callService: callService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package call_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
|
||||
"github.com/gomessguii/logger"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type CallService interface {
|
||||
RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error
|
||||
}
|
||||
|
||||
type callService struct {
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type RejectCallStruct struct {
|
||||
CallCreator types.JID `json:"callCreator"`
|
||||
CallID string `json:"callId"`
|
||||
}
|
||||
|
||||
func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := c.clientPointer.Get(instanceId)
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := c.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = c.clientPointer.Get(instanceId)
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = client.RejectCall(context.Background(), data.CallCreator, data.CallID)
|
||||
if err != nil {
|
||||
logger.LogError("[%s] error reject call: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewCallService(
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) CallService {
|
||||
return &callService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
package chat_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
chat_service "github.com/evolution-foundation/evolution-go/pkg/chat/service"
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ChatHandler interface {
|
||||
ChatPin(ctx *gin.Context)
|
||||
ChatUnpin(ctx *gin.Context)
|
||||
ChatArchive(ctx *gin.Context)
|
||||
ChatUnarchive(ctx *gin.Context)
|
||||
ChatMute(ctx *gin.Context)
|
||||
ChatUnmute(ctx *gin.Context)
|
||||
HistorySyncRequest(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type chatHandler struct {
|
||||
chatService chat_service.ChatService
|
||||
}
|
||||
|
||||
// Pin a chat
|
||||
// @Summary Pin a chat
|
||||
// @Description Pin a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/pin [post]
|
||||
func (c *chatHandler) ChatPin(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatPin(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Unpin a chat
|
||||
// @Summary Unpin a chat
|
||||
// @Description Unpin a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/unpin [post]
|
||||
func (c *chatHandler) ChatUnpin(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatUnpin(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Archive a chat
|
||||
// @Summary Archive a chat
|
||||
// @Description Archive a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/archive [post]
|
||||
func (c *chatHandler) ChatArchive(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatArchive(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Unarchive a chat
|
||||
// @Summary Unarchive a chat
|
||||
// @Description Unarchive a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/unarchive [post]
|
||||
func (c *chatHandler) ChatUnarchive(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatUnarchive(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Mute a chat
|
||||
// @Summary Mute a chat
|
||||
// @Description Mute a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/mute [post]
|
||||
func (c *chatHandler) ChatMute(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatMute(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Unmute a chat
|
||||
// @Summary Unmute a chat
|
||||
// @Description Unmute a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/unmute [post]
|
||||
func (c *chatHandler) ChatUnmute(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatUnmute(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// HistorySyncRequest a chat
|
||||
// @Summary HistorySyncRequest a chat
|
||||
// @Description HistorySyncRequest a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.HistorySyncRequestStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/history-sync [post]
|
||||
func (c *chatHandler) HistorySyncRequest(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.HistorySyncRequestStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := c.chatService.HistorySyncRequest(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
func NewChatHandler(
|
||||
chatService chat_service.ChatService,
|
||||
) ChatHandler {
|
||||
return &chatHandler{
|
||||
chatService: chatService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package chat_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/appstate"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type ChatService interface {
|
||||
ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error)
|
||||
}
|
||||
|
||||
type chatService struct {
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type BodyStruct struct {
|
||||
Chat string `json:"chat"`
|
||||
}
|
||||
|
||||
type HistorySyncRequestStruct struct {
|
||||
MessageInfo *types.MessageInfo `json:"messageInfo"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := c.clientPointer.Get(instanceId)
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := c.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = c.clientPointer.Get(instanceId)
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, true))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error pin chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, false))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unpin chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, true, time.Time{}, nil))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error archive chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, false, time.Time{}, nil))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unarchive chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, true, 1*time.Hour))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, false, 0*time.Hour))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmute chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
messageInfo := types.MessageInfo{
|
||||
MessageSource: types.MessageSource{
|
||||
Chat: data.MessageInfo.Chat,
|
||||
IsFromMe: data.MessageInfo.IsFromMe,
|
||||
IsGroup: data.MessageInfo.IsGroup,
|
||||
},
|
||||
ID: data.MessageInfo.ID,
|
||||
Timestamp: data.MessageInfo.Timestamp,
|
||||
}
|
||||
|
||||
histRequest := client.BuildHistorySyncRequest(&messageInfo, data.Count)
|
||||
|
||||
res, err := client.SendMessage(context.Background(), messageInfo.Chat, histRequest, whatsmeow.SendRequestExtra{Peer: true})
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error history sync request: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
func NewChatService(
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) ChatService {
|
||||
return &chatService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package community_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
community_service "github.com/evolution-foundation/evolution-go/pkg/community/service"
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type CommunityHandler interface {
|
||||
CreateCommunity(ctx *gin.Context)
|
||||
CommunityAdd(ctx *gin.Context)
|
||||
CommunityRemove(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type communityHandler struct {
|
||||
communityService community_service.CommunityService
|
||||
}
|
||||
|
||||
// Create community
|
||||
// @Summary Create community
|
||||
// @Description Create community
|
||||
// @Tags Community
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body community_service.CreateCommunityStruct true "Community data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /community/create [post]
|
||||
func (c *communityHandler) CreateCommunity(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *community_service.CreateCommunityStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.CommunityName == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
community, err := c.communityService.CreateCommunity(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": community})
|
||||
}
|
||||
|
||||
// Add participant to community
|
||||
// @Summary Add participant to community
|
||||
// @Description Add participant to community
|
||||
// @Tags Community
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body community_service.AddParticipantStruct true "Participant data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /community/add [post]
|
||||
func (c *communityHandler) CommunityAdd(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *community_service.AddParticipantStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.CommunityJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.GroupJID) == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := c.communityService.CommunityAdd(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Remove participant from community
|
||||
// @Summary Remove participant from community
|
||||
// @Description Remove participant from community
|
||||
// @Tags Community
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body community_service.AddParticipantStruct true "Participant data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /community/remove [post]
|
||||
func (c *communityHandler) CommunityRemove(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *community_service.AddParticipantStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.CommunityJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.GroupJID) == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := c.communityService.CommunityRemove(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
func NewCommunityHandler(
|
||||
communityService community_service.CommunityService,
|
||||
) CommunityHandler {
|
||||
return &communityHandler{
|
||||
communityService: communityService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package community_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type CommunityService interface {
|
||||
CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error)
|
||||
CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
|
||||
CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
|
||||
}
|
||||
|
||||
type communityService struct {
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type CreateCommunityStruct struct {
|
||||
CommunityName string `json:"communityName"`
|
||||
}
|
||||
|
||||
type AddParticipantStruct struct {
|
||||
CommunityJID string `json:"communityJid"`
|
||||
GroupJID []string `json:"groupJid"`
|
||||
}
|
||||
|
||||
func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := c.clientPointer.Get(instanceId)
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := c.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = c.clientPointer.Get(instanceId)
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *communityService) CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{
|
||||
Name: data.CommunityName,
|
||||
GroupParent: types.GroupParent{
|
||||
IsParent: true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create community: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (c *communityService) CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
communityJID, ok := utils.ParseJID(data.CommunityJID)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return nil, errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
var successList []string
|
||||
var failedList []string
|
||||
|
||||
for _, participant := range data.GroupJID {
|
||||
groupJID, _ := utils.ParseJID(participant)
|
||||
err := client.LinkGroup(context.Background(), communityJID, groupJID)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
|
||||
failedList = append(failedList, groupJID.String())
|
||||
}
|
||||
successList = append(failedList, groupJID.String())
|
||||
}
|
||||
|
||||
return gin.H{
|
||||
"success": successList,
|
||||
"failed": failedList,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
communityJID, ok := utils.ParseJID(data.CommunityJID)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return nil, errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
var successList []string
|
||||
var failedList []string
|
||||
|
||||
for _, participant := range data.GroupJID {
|
||||
groupJID, _ := utils.ParseJID(participant)
|
||||
err := client.UnlinkGroup(context.Background(), communityJID, groupJID)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
|
||||
failedList = append(failedList, groupJID.String())
|
||||
}
|
||||
successList = append(failedList, groupJID.String())
|
||||
}
|
||||
|
||||
return gin.H{
|
||||
"success": successList,
|
||||
"failed": failedList,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func NewCommunityService(
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) CommunityService {
|
||||
return &communityService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gomessguii/logger"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
|
||||
config_env "github.com/evolution-foundation/evolution-go/pkg/config/env"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
PostgresAuthDB string
|
||||
postgresUsersDB string
|
||||
PostgresHost string
|
||||
PostgresPort string
|
||||
PostgresUser string
|
||||
PostgresPassword string
|
||||
PostgresDB string
|
||||
DatabaseSaveMessages bool
|
||||
GlobalApiKey string
|
||||
WaDebug string
|
||||
LogType string
|
||||
WebhookFiles bool
|
||||
ConnectOnStartup bool
|
||||
OsName string
|
||||
AmqpUrl string
|
||||
AmqpGlobalEnabled bool
|
||||
WebhookUrl string
|
||||
ClientName string
|
||||
ApiAudioConverter string
|
||||
ApiAudioConverterKey string
|
||||
MinioEndpoint string
|
||||
MinioAccessKey string
|
||||
MinioSecretKey string
|
||||
MinioBucket string
|
||||
MinioUseSSL bool
|
||||
MinioEnabled bool
|
||||
MinioRegion string
|
||||
WhatsappVersionMajor int
|
||||
WhatsappVersionMinor int
|
||||
WhatsappVersionPatch int
|
||||
ProxyProtocol string
|
||||
ProxyHost string
|
||||
ProxyPort string
|
||||
ProxyUsername string
|
||||
ProxyPassword string
|
||||
AmqpGlobalEvents []string
|
||||
AmqpSpecificEvents []string
|
||||
NatsUrl string
|
||||
NatsGlobalEnabled bool
|
||||
NatsGlobalEvents []string
|
||||
EventIgnoreGroup bool
|
||||
EventIgnoreStatus bool
|
||||
QrcodeMaxCount int
|
||||
CheckUserExists bool
|
||||
|
||||
// Logger configurations
|
||||
LogMaxSize int
|
||||
LogMaxBackups int
|
||||
LogMaxAge int
|
||||
LogDirectory string
|
||||
LogCompress bool
|
||||
}
|
||||
|
||||
// EnsureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.
|
||||
func (c *Config) EnsureDBExists(dsn string) error {
|
||||
return ensureDBExists(dsn)
|
||||
}
|
||||
|
||||
// ensureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.
|
||||
func ensureDBExists(dsn string) error {
|
||||
dbName, adminDSN, err := extractDBNameAndAdminDSN(dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
db, err := sql.Open("postgres", adminDSN)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to postgres for auto-setup: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
var exists bool
|
||||
err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", dbName).Scan(&exists)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check database existence: %v", err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
logger.LogInfo("[CONFIG] Database %q not found, creating it automatically...", dbName)
|
||||
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE %q", dbName))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create database %q: %v", dbName, err)
|
||||
}
|
||||
logger.LogInfo("[CONFIG] Database %q created successfully", dbName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractDBNameAndAdminDSN parses a DSN (URL or key=value) and returns the database name
|
||||
// and a DSN pointing to the "postgres" maintenance database.
|
||||
func extractDBNameAndAdminDSN(dsn string) (string, string, error) {
|
||||
// Try URL format: postgres://user:pass@host:port/dbname?...
|
||||
if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("failed to parse DSN URL: %v", err)
|
||||
}
|
||||
dbName := strings.TrimPrefix(u.Path, "/")
|
||||
u.Path = "/postgres"
|
||||
return dbName, u.String(), nil
|
||||
}
|
||||
|
||||
// Key=value format: host=... user=... password=... dbname=... sslmode=...
|
||||
parts := strings.Fields(dsn)
|
||||
kvMap := make(map[string]string, len(parts))
|
||||
for _, p := range parts {
|
||||
kv := strings.SplitN(p, "=", 2)
|
||||
if len(kv) == 2 {
|
||||
kvMap[kv[0]] = kv[1]
|
||||
}
|
||||
}
|
||||
dbName, ok := kvMap["dbname"]
|
||||
if !ok || dbName == "" {
|
||||
return "", "", fmt.Errorf("could not extract dbname from DSN")
|
||||
}
|
||||
kvMap["dbname"] = "postgres"
|
||||
adminParts := make([]string, 0, len(kvMap))
|
||||
for k, v := range kvMap {
|
||||
adminParts = append(adminParts, k+"="+v)
|
||||
}
|
||||
return dbName, strings.Join(adminParts, " "), nil
|
||||
}
|
||||
|
||||
func (c *Config) CreateUsersDB() (*gorm.DB, error) {
|
||||
logger.LogDebug("Connecting to database on: %s", c.postgresUsersDB)
|
||||
|
||||
dbDSN := c.postgresUsersDB
|
||||
|
||||
if c.postgresUsersDB == "" {
|
||||
dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)
|
||||
}
|
||||
|
||||
if err := ensureDBExists(dbDSN); err != nil {
|
||||
logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)
|
||||
}
|
||||
|
||||
db, err := gorm.Open(
|
||||
postgres.Open(dbDSN),
|
||||
&gorm.Config{},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Configurar pool de conexões no GORM
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erro ao obter sql.DB do GORM: %v", err)
|
||||
}
|
||||
|
||||
// Configurar pool de conexões para evitar conexões ociosas não fechadas
|
||||
sqlDB.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente
|
||||
sqlDB.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool
|
||||
sqlDB.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts
|
||||
sqlDB.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func (c *Config) CreateAuthDB() (*sql.DB, error) {
|
||||
dbDSN := c.postgresUsersDB
|
||||
|
||||
if c.postgresUsersDB == "" {
|
||||
dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)
|
||||
}
|
||||
|
||||
if err := ensureDBExists(dbDSN); err != nil {
|
||||
logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)
|
||||
}
|
||||
|
||||
db, err := sql.Open("postgres", dbDSN)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Configurar pool de conexões para evitar conexões ociosas não fechadas
|
||||
db.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente
|
||||
db.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool
|
||||
db.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts
|
||||
db.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto
|
||||
|
||||
// Testar a conexão
|
||||
err = db.Ping()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erro ao testar conexão PostgreSQL AUTH: %v", err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
postgresAuthDB := os.Getenv(config_env.POSTGRES_AUTH_DB)
|
||||
|
||||
postgresUsersDB := os.Getenv(config_env.POSTGRES_USERS_DB)
|
||||
|
||||
postgresHost := os.Getenv(config_env.POSTGRES_HOST)
|
||||
postgresPort := os.Getenv(config_env.POSTGRES_PORT)
|
||||
postgresUser := os.Getenv(config_env.POSTGRES_USER)
|
||||
postgresPassword := os.Getenv(config_env.POSTGRES_PASSWORD)
|
||||
postgresDB := os.Getenv(config_env.POSTGRES_DB)
|
||||
|
||||
if postgresUsersDB == "" && (postgresHost == "" || postgresPort == "" || postgresUser == "" || postgresPassword == "" || postgresDB == "") {
|
||||
logger.LogFatal("[CONFIG] required database configuration variables are missing. Please check your environment configuration.")
|
||||
}
|
||||
|
||||
databaseSaveMessages := os.Getenv(config_env.DATABASE_SAVE_MESSAGES)
|
||||
panicIfEmpty(config_env.DATABASE_SAVE_MESSAGES, databaseSaveMessages)
|
||||
|
||||
globalApiKey := os.Getenv(config_env.GLOBAL_API_KEY)
|
||||
panicIfEmpty(config_env.GLOBAL_API_KEY, globalApiKey)
|
||||
|
||||
clientName := os.Getenv(config_env.CLIENT_NAME)
|
||||
|
||||
waDebug := os.Getenv(config_env.WA_DEBUG)
|
||||
|
||||
logType := os.Getenv(config_env.LOGTYPE)
|
||||
|
||||
webhookFiles := os.Getenv(config_env.WEBHOOKFILES)
|
||||
if webhookFiles == "" {
|
||||
webhookFiles = "true"
|
||||
}
|
||||
|
||||
connectOnStartup := os.Getenv(config_env.CONNECT_ON_STARTUP)
|
||||
if connectOnStartup == "" {
|
||||
connectOnStartup = "false"
|
||||
}
|
||||
|
||||
osName := os.Getenv(config_env.OS_NAME)
|
||||
|
||||
amqpUrl := os.Getenv(config_env.AMQP_URL)
|
||||
|
||||
// Validate AMQP URL format
|
||||
if err := validateAMQPURL(amqpUrl); err != nil {
|
||||
logger.LogFatal("[CONFIG] AMQP URL validation failed: %v", err)
|
||||
}
|
||||
|
||||
amqpGlobalEnabled := os.Getenv(config_env.AMQP_GLOBAL_ENABLED)
|
||||
|
||||
webhookUrl := os.Getenv(config_env.WEBHOOK_URL)
|
||||
|
||||
apiAudioConverter := os.Getenv(config_env.API_AUDIO_CONVERTER)
|
||||
apiAudioConverterKey := os.Getenv(config_env.API_AUDIO_CONVERTER_KEY)
|
||||
|
||||
whatsappVersionMajor := os.Getenv(config_env.WHATSAPP_VERSION_MAJOR)
|
||||
whatsappVersionMinor := os.Getenv(config_env.WHATSAPP_VERSION_MINOR)
|
||||
whatsappVersionPatch := os.Getenv(config_env.WHATSAPP_VERSION_PATCH)
|
||||
|
||||
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)
|
||||
proxyPassword := os.Getenv(config_env.PROXY_PASSWORD)
|
||||
|
||||
eventIgnoreGroup := os.Getenv(config_env.EVENT_IGNORE_GROUP)
|
||||
eventIgnoreStatus := os.Getenv(config_env.EVENT_IGNORE_STATUS)
|
||||
qrcodeMaxCount := os.Getenv(config_env.QRCODE_MAX_COUNT)
|
||||
checkUserExists := os.Getenv(config_env.CHECK_USER_EXISTS)
|
||||
|
||||
if checkUserExists == "" {
|
||||
checkUserExists = "true"
|
||||
}
|
||||
|
||||
// Convertendo para int com valores padrão caso estejam vazios
|
||||
major := 0
|
||||
if whatsappVersionMajor != "" {
|
||||
major, _ = strconv.Atoi(whatsappVersionMajor)
|
||||
}
|
||||
minor := 0
|
||||
if whatsappVersionMinor != "" {
|
||||
minor, _ = strconv.Atoi(whatsappVersionMinor)
|
||||
}
|
||||
patch := 0
|
||||
if whatsappVersionPatch != "" {
|
||||
patch, _ = strconv.Atoi(whatsappVersionPatch)
|
||||
}
|
||||
|
||||
qrMaxCount := 5 // Valor padrão
|
||||
if qrcodeMaxCount != "" {
|
||||
qrMaxCount, _ = strconv.Atoi(qrcodeMaxCount)
|
||||
}
|
||||
|
||||
amqpGlobalEvents := strings.Split(os.Getenv(config_env.AMQP_GLOBAL_EVENTS), ",")
|
||||
if len(amqpGlobalEvents) == 1 && amqpGlobalEvents[0] == "" {
|
||||
amqpGlobalEvents = []string{}
|
||||
}
|
||||
|
||||
amqpSpecificEvents := strings.Split(os.Getenv(config_env.AMQP_SPECIFIC_EVENTS), ",")
|
||||
if len(amqpSpecificEvents) == 1 && amqpSpecificEvents[0] == "" {
|
||||
amqpSpecificEvents = []string{}
|
||||
}
|
||||
|
||||
natsUrl := os.Getenv(config_env.NATS_URL)
|
||||
natsGlobalEnabled := os.Getenv(config_env.NATS_GLOBAL_ENABLED)
|
||||
natsGlobalEvents := strings.Split(os.Getenv(config_env.NATS_GLOBAL_EVENTS), ",")
|
||||
if len(natsGlobalEvents) == 1 && natsGlobalEvents[0] == "" {
|
||||
natsGlobalEvents = []string{}
|
||||
}
|
||||
|
||||
// Logger configurations
|
||||
logMaxSize, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_SIZE))
|
||||
if logMaxSize == 0 {
|
||||
logMaxSize = 100 // Default 100MB
|
||||
}
|
||||
|
||||
logMaxBackups, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_BACKUPS))
|
||||
if logMaxBackups == 0 {
|
||||
logMaxBackups = 5 // Default 5 backups
|
||||
}
|
||||
|
||||
logMaxAge, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_AGE))
|
||||
if logMaxAge == 0 {
|
||||
logMaxAge = 30 // Default 30 days
|
||||
}
|
||||
|
||||
logDirectory := os.Getenv(config_env.LOG_DIRECTORY)
|
||||
if logDirectory == "" {
|
||||
logDirectory = "./logs" // Default logs directory
|
||||
}
|
||||
|
||||
logCompress := os.Getenv(config_env.LOG_COMPRESS) == "true"
|
||||
if os.Getenv(config_env.LOG_COMPRESS) == "" {
|
||||
logCompress = true // Default compression enabled
|
||||
}
|
||||
|
||||
config := &Config{
|
||||
PostgresAuthDB: postgresAuthDB,
|
||||
postgresUsersDB: postgresUsersDB,
|
||||
DatabaseSaveMessages: databaseSaveMessages == "true",
|
||||
GlobalApiKey: globalApiKey,
|
||||
WaDebug: waDebug,
|
||||
LogType: logType,
|
||||
WebhookFiles: webhookFiles == "true",
|
||||
ConnectOnStartup: connectOnStartup == "true",
|
||||
OsName: osName,
|
||||
AmqpUrl: amqpUrl,
|
||||
AmqpGlobalEnabled: amqpGlobalEnabled == "true",
|
||||
WebhookUrl: webhookUrl,
|
||||
ClientName: clientName,
|
||||
ApiAudioConverter: apiAudioConverter,
|
||||
ApiAudioConverterKey: apiAudioConverterKey,
|
||||
PostgresHost: postgresHost,
|
||||
PostgresPort: postgresPort,
|
||||
PostgresUser: postgresUser,
|
||||
PostgresPassword: postgresPassword,
|
||||
PostgresDB: postgresDB,
|
||||
WhatsappVersionMajor: major,
|
||||
WhatsappVersionMinor: minor,
|
||||
WhatsappVersionPatch: patch,
|
||||
ProxyProtocol: proxyProtocol,
|
||||
ProxyHost: proxyHost,
|
||||
ProxyPort: proxyPort,
|
||||
ProxyUsername: proxyUsername,
|
||||
ProxyPassword: proxyPassword,
|
||||
EventIgnoreGroup: eventIgnoreGroup == "true",
|
||||
EventIgnoreStatus: eventIgnoreStatus == "true",
|
||||
QrcodeMaxCount: qrMaxCount,
|
||||
CheckUserExists: checkUserExists != "false", // Default true, set to false to disable
|
||||
AmqpGlobalEvents: amqpGlobalEvents,
|
||||
AmqpSpecificEvents: amqpSpecificEvents,
|
||||
NatsUrl: natsUrl,
|
||||
NatsGlobalEnabled: natsGlobalEnabled == "true",
|
||||
NatsGlobalEvents: natsGlobalEvents,
|
||||
LogMaxSize: logMaxSize,
|
||||
LogMaxBackups: logMaxBackups,
|
||||
LogMaxAge: logMaxAge,
|
||||
LogDirectory: logDirectory,
|
||||
LogCompress: logCompress,
|
||||
}
|
||||
|
||||
minioEnabled := os.Getenv(config_env.MINIO_ENABLED) == "true"
|
||||
if minioEnabled {
|
||||
config.MinioEnabled = true
|
||||
loadMinioConfig(config)
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
func loadMinioConfig(config *Config) {
|
||||
minioEndpoint := os.Getenv(config_env.MINIO_ENDPOINT)
|
||||
panicIfEmpty(config_env.MINIO_ENDPOINT, minioEndpoint)
|
||||
|
||||
minioAccessKey := os.Getenv(config_env.MINIO_ACCESS_KEY)
|
||||
panicIfEmpty(config_env.MINIO_ACCESS_KEY, minioAccessKey)
|
||||
|
||||
minioSecretKey := os.Getenv(config_env.MINIO_SECRET_KEY)
|
||||
panicIfEmpty(config_env.MINIO_SECRET_KEY, minioSecretKey)
|
||||
|
||||
minioBucket := os.Getenv(config_env.MINIO_BUCKET)
|
||||
panicIfEmpty(config_env.MINIO_BUCKET, minioBucket)
|
||||
|
||||
minioUseSSL := os.Getenv(config_env.MINIO_USE_SSL) == "true"
|
||||
|
||||
minioRegion := os.Getenv(config_env.MINIO_REGION)
|
||||
|
||||
config.MinioEndpoint = minioEndpoint
|
||||
config.MinioAccessKey = minioAccessKey
|
||||
config.MinioSecretKey = minioSecretKey
|
||||
config.MinioBucket = minioBucket
|
||||
config.MinioUseSSL = minioUseSSL
|
||||
config.MinioRegion = minioRegion
|
||||
}
|
||||
|
||||
func panicIfEmpty(key, value string) {
|
||||
if value == "" {
|
||||
if os.Getenv("DEBUG_ENABLED") != "1" {
|
||||
logger.LogInfo("You are NOT on development mode")
|
||||
}
|
||||
logger.LogFatal("[CONFIG] required configuration variable is missing. Please check your environment configuration.")
|
||||
}
|
||||
}
|
||||
|
||||
// validateAMQPURL validates if the AMQP URL has the correct scheme and format
|
||||
func validateAMQPURL(amqpURL string) error {
|
||||
if amqpURL == "" {
|
||||
return nil // Empty URL is allowed (RabbitMQ disabled)
|
||||
}
|
||||
|
||||
// Parse the URL
|
||||
parsedURL, err := url.Parse(amqpURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid AMQP URL format: %v", err)
|
||||
}
|
||||
|
||||
// Check if scheme is valid
|
||||
if parsedURL.Scheme != "amqp" && parsedURL.Scheme != "amqps" {
|
||||
return fmt.Errorf("AMQP scheme must be either 'amqp://' or 'amqps://', got: '%s://'", parsedURL.Scheme)
|
||||
}
|
||||
|
||||
// Check if host is present
|
||||
if parsedURL.Host == "" {
|
||||
return fmt.Errorf("AMQP URL must include a host")
|
||||
}
|
||||
|
||||
logger.LogInfo("[CONFIG] AMQP URL validation successful: %s://%s", parsedURL.Scheme, parsedURL.Host)
|
||||
return nil
|
||||
}
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
package config_env
|
||||
|
||||
const (
|
||||
POSTGRES_AUTH_DB = "POSTGRES_AUTH_DB"
|
||||
POSTGRES_USERS_DB = "POSTGRES_USERS_DB"
|
||||
POSTGRES_HOST = "POSTGRES_HOST"
|
||||
POSTGRES_PORT = "POSTGRES_PORT"
|
||||
POSTGRES_USER = "POSTGRES_USER"
|
||||
POSTGRES_PASSWORD = "POSTGRES_PASSWORD"
|
||||
POSTGRES_DB = "POSTGRES_DB"
|
||||
DATABASE_SAVE_MESSAGES = "DATABASE_SAVE_MESSAGES"
|
||||
GLOBAL_API_KEY = "GLOBAL_API_KEY"
|
||||
WA_DEBUG = "DEBUG_ENABLED"
|
||||
LOGTYPE = "LOG_TYPE"
|
||||
WEBHOOKFILES = "WEBHOOK_FILES"
|
||||
CONNECT_ON_STARTUP = "CONNECT_ON_STARTUP"
|
||||
OS_NAME = "OS_NAME"
|
||||
AMQP_URL = "AMQP_URL"
|
||||
AMQP_GLOBAL_ENABLED = "AMQP_GLOBAL_ENABLED"
|
||||
AMQP_GLOBAL_EVENTS = "AMQP_GLOBAL_EVENTS"
|
||||
AMQP_SPECIFIC_EVENTS = "AMQP_SPECIFIC_EVENTS"
|
||||
WEBHOOK_URL = "WEBHOOK_URL"
|
||||
CLIENT_NAME = "CLIENT_NAME"
|
||||
API_AUDIO_CONVERTER = "API_AUDIO_CONVERTER"
|
||||
API_AUDIO_CONVERTER_KEY = "API_AUDIO_CONVERTER_KEY"
|
||||
MINIO_ENDPOINT = "MINIO_ENDPOINT"
|
||||
MINIO_ACCESS_KEY = "MINIO_ACCESS_KEY"
|
||||
MINIO_SECRET_KEY = "MINIO_SECRET_KEY"
|
||||
MINIO_BUCKET = "MINIO_BUCKET"
|
||||
MINIO_USE_SSL = "MINIO_USE_SSL"
|
||||
MINIO_ENABLED = "MINIO_ENABLED"
|
||||
MINIO_REGION = "MINIO_REGION"
|
||||
WHATSAPP_VERSION_MAJOR = "WHATSAPP_VERSION_MAJOR"
|
||||
WHATSAPP_VERSION_MINOR = "WHATSAPP_VERSION_MINOR"
|
||||
WHATSAPP_VERSION_PATCH = "WHATSAPP_VERSION_PATCH"
|
||||
PROXY_PROTOCOL = "PROXY_PROTOCOL"
|
||||
PROXY_HOST = "PROXY_HOST"
|
||||
PROXY_PORT = "PROXY_PORT"
|
||||
PROXY_USERNAME = "PROXY_USERNAME"
|
||||
PROXY_PASSWORD = "PROXY_PASSWORD"
|
||||
NATS_URL = "NATS_URL"
|
||||
NATS_GLOBAL_ENABLED = "NATS_GLOBAL_ENABLED"
|
||||
NATS_GLOBAL_EVENTS = "NATS_GLOBAL_EVENTS"
|
||||
EVENT_IGNORE_GROUP = "EVENT_IGNORE_GROUP"
|
||||
EVENT_IGNORE_STATUS = "EVENT_IGNORE_STATUS"
|
||||
QRCODE_MAX_COUNT = "QRCODE_MAX_COUNT"
|
||||
CHECK_USER_EXISTS = "CHECK_USER_EXISTS"
|
||||
|
||||
// Logger configurations
|
||||
LOG_MAX_SIZE = "LOG_MAX_SIZE"
|
||||
LOG_MAX_BACKUPS = "LOG_MAX_BACKUPS"
|
||||
LOG_MAX_AGE = "LOG_MAX_AGE"
|
||||
LOG_DIRECTORY = "LOG_DIRECTORY"
|
||||
LOG_COMPRESS = "LOG_COMPRESS"
|
||||
)
|
||||
+978
@@ -0,0 +1,978 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _k1 = []byte{0xd3, 0xd0, 0x41, 0x5a, 0x76, 0xa7, 0x40, 0x81, 0x44, 0xa8, 0xac, 0x8c, 0x64, 0xaa, 0x13, 0x12, 0x16, 0x71, 0x9d, 0x13, 0x9a, 0x41, 0x57, 0xd9, 0x15, 0x62, 0x1a, 0x08, 0x1f, 0x6c, 0x6c, 0x7b, 0xd3, 0xa4, 0x81, 0xca, 0x85, 0xeb, 0x9f, 0x06, 0x81, 0x0a}
|
||||
var _k0 = []byte{0xbb, 0xa4, 0x35, 0x2a, 0x05, 0x9d, 0x6f, 0xae, 0x28, 0xc1, 0xcf, 0xe9, 0x0a, 0xd9, 0x76, 0x3c, 0x73, 0x07, 0xf2, 0x7f, 0xef, 0x35, 0x3e, 0xb6, 0x7b, 0x04, 0x75, 0x7d, 0x71, 0x08, 0x0d, 0x0f, 0xba, 0xcb, 0xef, 0xe4, 0xe6, 0x84, 0xf2, 0x28, 0xe3, 0x78}
|
||||
|
||||
var (
|
||||
_6np1 string
|
||||
_96 string
|
||||
)
|
||||
|
||||
func _cdo() string {
|
||||
if _6np1 != "" && _96 != "" {
|
||||
return _k54v(_6np1, _96)
|
||||
}
|
||||
parts := [...]string{"h", "tt", "ps", "://", "li", "ce", "nse", ".", "ev", "ol", "ut", "io", "nf", "ou", "nd", "at", "io", "n.", "co", "m.", "br"}
|
||||
var s string
|
||||
for _, p := range parts {
|
||||
s += p
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func _k54v(enc, key string) string {
|
||||
encBytes := _9wc0(enc)
|
||||
keyBytes := _9wc0(key)
|
||||
if len(keyBytes) == 0 {
|
||||
return ""
|
||||
}
|
||||
out := make([]byte, len(encBytes))
|
||||
for i, b := range encBytes {
|
||||
out[i] = b ^ keyBytes[i%len(keyBytes)]
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func _9wc0(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] = _gy4(s[i])<<4 | _gy4(s[i+1])
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func _gy4(c byte) byte {
|
||||
switch {
|
||||
case c >= '0' && c <= '9':
|
||||
return c - '0'
|
||||
case c >= 'a' && c <= 'f':
|
||||
return c - 'a' + 10
|
||||
case c >= 'A' && c <= 'F':
|
||||
return c - 'A' + 10
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var _3t = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
func _4crw(body []byte, secret string) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(body)
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func _sn(path string, payload interface{}, _kni string) (*http.Response, error) {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
url := _cdo() + 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", _kni)
|
||||
req.Header.Set("X-Signature", _4crw(body, _kni))
|
||||
|
||||
return _3t.Do(req)
|
||||
}
|
||||
|
||||
func _6o(path string) (*http.Response, error) {
|
||||
url := _cdo() + path
|
||||
return _3t.Get(url)
|
||||
}
|
||||
|
||||
func _dtnx(path string, payload interface{}) (*http.Response, error) {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
url := _cdo() + 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 _3t.Do(req)
|
||||
}
|
||||
|
||||
func _3ya(resp *http.Response) error {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
var _n6oe struct {
|
||||
Message string `json:"message"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &_n6oe); err == nil {
|
||||
msg := _n6oe.Message
|
||||
if msg == "" {
|
||||
msg = _n6oe.Error
|
||||
}
|
||||
if msg != "" {
|
||||
return fmt.Errorf("%s (HTTP %d)", strings.ToLower(msg), resp.StatusCode)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
type RuntimeConfig struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
Key string `gorm:"uniqueIndex;size:100;not null" json:"key"`
|
||||
Value string `gorm:"type:text;not null" json:"value"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (RuntimeConfig) TableName() string {
|
||||
return "runtime_configs"
|
||||
}
|
||||
|
||||
const (
|
||||
ConfigKeyInstanceID = "instance_id"
|
||||
ConfigKeyAPIKey = "api_key"
|
||||
ConfigKeyTier = "tier"
|
||||
ConfigKeyCustomerID = "customer_id"
|
||||
)
|
||||
|
||||
var _k4 *gorm.DB
|
||||
|
||||
func SetDB(db *gorm.DB) {
|
||||
_k4 = db
|
||||
}
|
||||
|
||||
func MigrateDB() error {
|
||||
if _k4 == nil {
|
||||
return fmt.Errorf("core: database not set, call SetDB first")
|
||||
}
|
||||
return _k4.AutoMigrate(&RuntimeConfig{})
|
||||
}
|
||||
|
||||
func _at(key string) (string, error) {
|
||||
if _k4 == nil {
|
||||
return "", fmt.Errorf("core: database not set")
|
||||
}
|
||||
var _33 RuntimeConfig
|
||||
_tmzn := _k4.Where("key = ?", key).First(&_33)
|
||||
if _tmzn.Error != nil {
|
||||
return "", _tmzn.Error
|
||||
}
|
||||
return _33.Value, nil
|
||||
}
|
||||
|
||||
func _yy(key, value string) error {
|
||||
if _k4 == nil {
|
||||
return fmt.Errorf("core: database not set")
|
||||
}
|
||||
var _33 RuntimeConfig
|
||||
_tmzn := _k4.Where("key = ?", key).First(&_33)
|
||||
if _tmzn.Error != nil {
|
||||
return _k4.Create(&RuntimeConfig{Key: key, Value: value}).Error
|
||||
}
|
||||
return _k4.Model(&_33).Update("value", value).Error
|
||||
}
|
||||
|
||||
func _ettg(key string) {
|
||||
if _k4 == nil {
|
||||
return
|
||||
}
|
||||
_k4.Where("key = ?", key).Delete(&RuntimeConfig{})
|
||||
}
|
||||
|
||||
type RuntimeData struct {
|
||||
APIKey string
|
||||
Tier string
|
||||
CustomerID int
|
||||
}
|
||||
|
||||
func _2s() (*RuntimeData, error) {
|
||||
_kni, err := _at(ConfigKeyAPIKey)
|
||||
if err != nil || _kni == "" {
|
||||
return nil, fmt.Errorf("no license found")
|
||||
}
|
||||
|
||||
_b56, _ := _at(ConfigKeyTier)
|
||||
customerIDStr, _ := _at(ConfigKeyCustomerID)
|
||||
customerID, _ := strconv.Atoi(customerIDStr)
|
||||
|
||||
return &RuntimeData{
|
||||
APIKey: _kni,
|
||||
Tier: _b56,
|
||||
CustomerID: customerID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func _yosh(rd *RuntimeData) error {
|
||||
if err := _yy(ConfigKeyAPIKey, rd.APIKey); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := _yy(ConfigKeyTier, rd.Tier); err != nil {
|
||||
return err
|
||||
}
|
||||
if rd.CustomerID > 0 {
|
||||
if err := _yy(ConfigKeyCustomerID, strconv.Itoa(rd.CustomerID)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func _31() {
|
||||
_ettg(ConfigKeyAPIKey)
|
||||
_ettg(ConfigKeyTier)
|
||||
_ettg(ConfigKeyCustomerID)
|
||||
}
|
||||
|
||||
func _ggnz() (string, error) {
|
||||
id, err := _at(ConfigKeyInstanceID)
|
||||
if err == nil && len(id) == 36 {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
id = _tym7()
|
||||
if id == "" {
|
||||
id, err = _ebxz()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
if err := _yy(ConfigKeyInstanceID, id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func _tym7() string {
|
||||
hostname, _ := os.Hostname()
|
||||
macAddr := _nteb()
|
||||
if hostname == "" && macAddr == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
seed := hostname + "|" + macAddr
|
||||
h := make([]byte, 16)
|
||||
copy(h, []byte(seed))
|
||||
for i := 16; i < len(seed); i++ {
|
||||
h[i%16] ^= seed[i]
|
||||
}
|
||||
h[6] = (h[6] & 0x0f) | 0x40 // _64 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 _nteb() string {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, iface := range interfaces {
|
||||
if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
if len(iface.HardwareAddr) > 0 {
|
||||
return iface.HardwareAddr.String()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func _ebxz() (string, error) {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||
}
|
||||
|
||||
var _x1n atomic.Value // set during activation
|
||||
|
||||
func init() {
|
||||
_x1n.Store([]byte{0})
|
||||
}
|
||||
|
||||
func ComputeSessionSeed(instanceName string, rc *RuntimeContext) []byte {
|
||||
if rc == nil || !rc._txz.Load() {
|
||||
return nil // Will cause panic in caller — intentional
|
||||
}
|
||||
h := sha256.New()
|
||||
h.Write([]byte(instanceName))
|
||||
h.Write([]byte(rc._kni))
|
||||
salt, _ := _x1n.Load().([]byte)
|
||||
h.Write(salt)
|
||||
return h.Sum(nil)[:16]
|
||||
}
|
||||
|
||||
func ValidateRouteAccess(rc *RuntimeContext) uint64 {
|
||||
if rc == nil {
|
||||
return 0
|
||||
}
|
||||
h := rc.ContextHash()
|
||||
return binary.LittleEndian.Uint64(h[:8])
|
||||
}
|
||||
|
||||
func DeriveInstanceToken(_z14 string, rc *RuntimeContext) string {
|
||||
if rc == nil || !rc._txz.Load() {
|
||||
return ""
|
||||
}
|
||||
h := sha256.Sum256([]byte(_z14 + rc._kni))
|
||||
return _zxx(h[:8])
|
||||
}
|
||||
|
||||
func _zxx(b []byte) string {
|
||||
const _4jq = "0123456789abcdef"
|
||||
dst := make([]byte, len(b)*2)
|
||||
for i, v := range b {
|
||||
dst[i*2] = _4jq[v>>4]
|
||||
dst[i*2+1] = _4jq[v&0x0f]
|
||||
}
|
||||
return string(dst)
|
||||
}
|
||||
|
||||
func ActivateIntegrity(rc *RuntimeContext) {
|
||||
if rc == nil {
|
||||
return
|
||||
}
|
||||
h := sha256.Sum256([]byte(rc._kni + rc._z14 + "ev0"))
|
||||
_x1n.Store(h[:])
|
||||
}
|
||||
|
||||
const (
|
||||
hbInterval = 30 * time.Minute
|
||||
)
|
||||
|
||||
type RuntimeContext struct {
|
||||
_kni string
|
||||
_pl87 string // GLOBAL_API_KEY from .env — used as token for licensing check
|
||||
_z14 string
|
||||
_txz atomic.Bool
|
||||
_s6a [32]byte // Derived from activation — required by ValidateContext
|
||||
mu sync.RWMutex
|
||||
_v8 string // Registration URL shown to users before activation
|
||||
_0z9m string // Registration token for polling
|
||||
_b56 string
|
||||
_64 string
|
||||
_hpv atomic.Int64 // Messages sent since last heartbeat
|
||||
_ti9 atomic.Int64 // Messages received since last heartbeat
|
||||
}
|
||||
|
||||
var _rs atomic.Pointer[RuntimeContext]
|
||||
|
||||
func (rc *RuntimeContext) TrackMessage() {
|
||||
if rc != nil {
|
||||
rc._hpv.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
func TrackMessageSent() {
|
||||
if rc := _rs.Load(); rc != nil {
|
||||
rc._hpv.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
func TrackMessageRecv() {
|
||||
if rc := _rs.Load(); rc != nil {
|
||||
rc._ti9.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) _4g() int64 {
|
||||
return rc._hpv.Swap(0)
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) ContextHash() [32]byte {
|
||||
rc.mu.RLock()
|
||||
defer rc.mu.RUnlock()
|
||||
return rc._s6a
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) IsActive() bool {
|
||||
return rc._txz.Load()
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) RegistrationURL() string {
|
||||
rc.mu.RLock()
|
||||
defer rc.mu.RUnlock()
|
||||
return rc._v8
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) APIKey() string {
|
||||
rc.mu.RLock()
|
||||
defer rc.mu.RUnlock()
|
||||
return rc._kni
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) InstanceID() string {
|
||||
return rc._z14
|
||||
}
|
||||
|
||||
func InitializeRuntime(_b56, _64, _pl87 string) *RuntimeContext {
|
||||
if _b56 == "" {
|
||||
_b56 = "evolution-go"
|
||||
}
|
||||
if _64 == "" {
|
||||
_64 = "unknown"
|
||||
}
|
||||
|
||||
rc := &RuntimeContext{
|
||||
_b56: _b56,
|
||||
_64: _64,
|
||||
_pl87: _pl87,
|
||||
}
|
||||
|
||||
id, err := _ggnz()
|
||||
if err != nil {
|
||||
log.Fatalf("[runtime] failed to initialize instance: %v", err)
|
||||
}
|
||||
rc._z14 = id
|
||||
|
||||
rd, err := _2s()
|
||||
if err == nil && rd.APIKey != "" {
|
||||
rc._kni = rd.APIKey
|
||||
fmt.Printf(" ✓ License found: %s...%s\n", rd.APIKey[:8], rd.APIKey[len(rd.APIKey)-4:])
|
||||
|
||||
rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14))
|
||||
rc._txz.Store(true)
|
||||
ActivateIntegrity(rc)
|
||||
fmt.Println(" ✓ License activated successfully")
|
||||
|
||||
go func() {
|
||||
if err := _c4m(rc, _64); err != nil {
|
||||
fmt.Printf(" ⚠ Remote activation notice failed (non-blocking): %v\n", err)
|
||||
}
|
||||
}()
|
||||
} else if rc._pl87 != "" {
|
||||
rc._kni = rc._pl87
|
||||
if err := _c4m(rc, _64); err == nil {
|
||||
_yosh(&RuntimeData{APIKey: rc._pl87, Tier: _b56})
|
||||
rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14))
|
||||
rc._txz.Store(true)
|
||||
ActivateIntegrity(rc)
|
||||
fmt.Printf(" ✓ GLOBAL_API_KEY accepted — license saved and activated\n")
|
||||
} else {
|
||||
rc._kni = ""
|
||||
_g2()
|
||||
rc._txz.Store(false)
|
||||
}
|
||||
} else {
|
||||
if _rh(rc, _64) {
|
||||
fmt.Println(" ✓ License activated automatically via EVOLUTION_OPERATOR_EMAIL")
|
||||
} else {
|
||||
_g2()
|
||||
rc._txz.Store(false)
|
||||
}
|
||||
}
|
||||
|
||||
_rs.Store(rc)
|
||||
|
||||
return rc
|
||||
}
|
||||
|
||||
func _rh(rc *RuntimeContext, _64 string) bool {
|
||||
email := strings.TrimSpace(os.Getenv("EVOLUTION_OPERATOR_EMAIL"))
|
||||
if email == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
payload := map[string]string{
|
||||
"email": email,
|
||||
"tier": rc._b56,
|
||||
"version": _64,
|
||||
"instance_id": rc._z14,
|
||||
}
|
||||
|
||||
resp, err := _dtnx("/v1/register/auto", payload)
|
||||
if err != nil {
|
||||
fmt.Printf(" ⚠ Auto-activation skipped — licensing server unreachable: %v\n", err)
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_n6oe := _3ya(resp)
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
fmt.Printf(" ℹ Auto-activation skipped — email not registered yet (first time?). Falling back to manual flow.\n")
|
||||
} else {
|
||||
fmt.Printf(" ⚠ Auto-activation rejected (%d): %v. Falling back to manual flow.\n",
|
||||
resp.StatusCode, _n6oe)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var _tmzn struct {
|
||||
APIKey string `json:"api_key"`
|
||||
CustomerID int `json:"customer_id"`
|
||||
Tier string `json:"tier"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&_tmzn); err != nil {
|
||||
fmt.Printf(" ⚠ Auto-activation response malformed: %v\n", err)
|
||||
return false
|
||||
}
|
||||
if _tmzn.APIKey == "" {
|
||||
fmt.Printf(" ⚠ Auto-activation response missing api_key\n")
|
||||
return false
|
||||
}
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._kni = _tmzn.APIKey
|
||||
rc.mu.Unlock()
|
||||
|
||||
if err := _yosh(&RuntimeData{
|
||||
APIKey: _tmzn.APIKey,
|
||||
Tier: rc._b56,
|
||||
CustomerID: _tmzn.CustomerID,
|
||||
}); err != nil {
|
||||
fmt.Printf(" ⚠ Auto-activation: could not save license to disk: %v\n", err)
|
||||
}
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14))
|
||||
rc.mu.Unlock()
|
||||
rc._txz.Store(true)
|
||||
ActivateIntegrity(rc)
|
||||
return true
|
||||
}
|
||||
|
||||
func _g2() {
|
||||
fmt.Println()
|
||||
fmt.Println(" ╔══════════════════════════════════════════════════════════╗")
|
||||
fmt.Println(" ║ License Registration Required ║")
|
||||
fmt.Println(" ╚══════════════════════════════════════════════════════════╝")
|
||||
fmt.Println()
|
||||
fmt.Println(" Server starting without license.")
|
||||
fmt.Println(" API endpoints will return 503 until license is activated.")
|
||||
fmt.Println(" Use GET /license/register to get the registration URL.")
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) _bf8(authCodeOrKey, _b56 string, customerID int) error {
|
||||
_kni, err := _58(authCodeOrKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("key exchange failed: %w", err)
|
||||
}
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._kni = _kni
|
||||
rc._v8 = ""
|
||||
rc._0z9m = ""
|
||||
rc.mu.Unlock()
|
||||
|
||||
if err := _yosh(&RuntimeData{
|
||||
APIKey: _kni,
|
||||
Tier: _b56,
|
||||
CustomerID: customerID,
|
||||
}); err != nil {
|
||||
fmt.Printf(" ⚠ Warning: could not save license: %v\n", err)
|
||||
}
|
||||
|
||||
if err := _c4m(rc, rc._64); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14))
|
||||
rc.mu.Unlock()
|
||||
rc._txz.Store(true)
|
||||
ActivateIntegrity(rc)
|
||||
|
||||
fmt.Printf(" ✓ License activated! Key: %s...%s (_b56: %s)\n",
|
||||
_kni[:8], _kni[len(_kni)-4:], _b56)
|
||||
|
||||
go func() {
|
||||
if err := _814l(rc, 0); err != nil {
|
||||
fmt.Printf(" ⚠ First heartbeat failed: %v\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateContext(rc *RuntimeContext) (bool, string) {
|
||||
if rc == nil {
|
||||
return false, ""
|
||||
}
|
||||
if !rc._txz.Load() {
|
||||
return false, rc.RegistrationURL()
|
||||
}
|
||||
expected := sha256.Sum256([]byte(rc._kni + rc._z14))
|
||||
actual := rc.ContextHash()
|
||||
if expected != actual {
|
||||
return false, ""
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func GateMiddleware(rc *RuntimeContext) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
path := c.Request.URL.Path
|
||||
|
||||
if path == "/health" || path == "/server/ok" || path == "/favicon.ico" ||
|
||||
path == "/license/status" || path == "/license/register" || path == "/license/activate" ||
|
||||
strings.HasPrefix(path, "/manager") || strings.HasPrefix(path, "/assets") ||
|
||||
strings.HasPrefix(path, "/passkey-ceremony") ||
|
||||
strings.HasPrefix(path, "/swagger") || path == "/ws" ||
|
||||
strings.HasSuffix(path, ".svg") || strings.HasSuffix(path, ".css") ||
|
||||
strings.HasSuffix(path, ".js") || strings.HasSuffix(path, ".png") ||
|
||||
strings.HasSuffix(path, ".ico") || strings.HasSuffix(path, ".woff2") ||
|
||||
strings.HasSuffix(path, ".woff") || strings.HasSuffix(path, ".ttf") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
valid, _ := ValidateContext(rc)
|
||||
if !valid {
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
managerURL := fmt.Sprintf("%s://%s/manager/login", scheme, c.Request.Host)
|
||||
|
||||
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{
|
||||
"error": "service not activated",
|
||||
"code": "LICENSE_REQUIRED",
|
||||
"register_url": managerURL,
|
||||
"message": "License required. Open the manager to activate your license.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("_rch", rc.ContextHash())
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
|
||||
lic := eng.Group("/license")
|
||||
{
|
||||
lic.GET("/status", func(c *gin.Context) {
|
||||
status := "inactive"
|
||||
if rc.IsActive() {
|
||||
status = "active"
|
||||
}
|
||||
|
||||
resp := gin.H{
|
||||
"status": status,
|
||||
"instance_id": rc._z14,
|
||||
}
|
||||
|
||||
rc.mu.RLock()
|
||||
if rc._kni != "" {
|
||||
resp["api_key"] = rc._kni[:8] + "..." + rc._kni[len(rc._kni)-4:]
|
||||
}
|
||||
rc.mu.RUnlock()
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
})
|
||||
|
||||
lic.GET("/register", func(c *gin.Context) {
|
||||
if rc.IsActive() {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "active",
|
||||
"message": "License is already active",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
rc.mu.RLock()
|
||||
existingURL := rc._v8
|
||||
rc.mu.RUnlock()
|
||||
|
||||
if existingURL != "" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "pending",
|
||||
"register_url": existingURL,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
payload := map[string]string{
|
||||
"tier": rc._b56,
|
||||
"version": rc._64,
|
||||
"instance_id": rc._z14,
|
||||
}
|
||||
if redirectURI := c.Query("redirect_uri"); redirectURI != "" {
|
||||
payload["redirect_uri"] = redirectURI
|
||||
}
|
||||
|
||||
resp, err := _dtnx("/v1/register/init", payload)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{
|
||||
"error": "Failed to contact licensing server",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_n6oe := _3ya(resp)
|
||||
c.JSON(resp.StatusCode, gin.H{
|
||||
"error": "Licensing server error",
|
||||
"details": _n6oe.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var _3y struct {
|
||||
RegisterURL string `json:"register_url"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&_3y)
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._v8 = _3y.RegisterURL
|
||||
rc._0z9m = _3y.Token
|
||||
rc.mu.Unlock()
|
||||
|
||||
fmt.Printf(" → Registration URL: %s\n", _3y.RegisterURL)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "pending",
|
||||
"register_url": _3y.RegisterURL,
|
||||
})
|
||||
})
|
||||
|
||||
lic.GET("/activate", func(c *gin.Context) {
|
||||
if rc.IsActive() {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "active",
|
||||
"message": "License is already active",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
code := c.Query("code")
|
||||
if code == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Missing code parameter",
|
||||
"message": "Provide ?code=AUTHORIZATION_CODE from the registration callback.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
exchangeResp, err := _dtnx("/v1/register/exchange", map[string]string{
|
||||
"authorization_code": code,
|
||||
"instance_id": rc._z14,
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{
|
||||
"error": "Failed to contact licensing server",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
defer exchangeResp.Body.Close()
|
||||
|
||||
if exchangeResp.StatusCode != http.StatusOK {
|
||||
_n6oe := _3ya(exchangeResp)
|
||||
c.JSON(exchangeResp.StatusCode, gin.H{
|
||||
"error": "Exchange failed",
|
||||
"details": _n6oe.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var _tmzn struct {
|
||||
APIKey string `json:"api_key"`
|
||||
Tier string `json:"tier"`
|
||||
CustomerID int `json:"customer_id"`
|
||||
}
|
||||
json.NewDecoder(exchangeResp.Body).Decode(&_tmzn)
|
||||
|
||||
if _tmzn.APIKey == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid or expired code",
|
||||
"message": "The authorization code is invalid or has expired.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := rc._bf8(_tmzn.APIKey, _tmzn.Tier, _tmzn.CustomerID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Activation failed",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "active",
|
||||
"message": "License activated successfully!",
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time) {
|
||||
go func() {
|
||||
ticker := time.NewTicker(hbInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !rc.IsActive() {
|
||||
continue
|
||||
}
|
||||
uptime := int64(time.Since(startTime).Seconds())
|
||||
if err := _814l(rc, uptime); err != nil {
|
||||
fmt.Printf(" ⚠ Heartbeat failed (non-blocking): %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func Shutdown(rc *RuntimeContext) {
|
||||
if rc == nil || rc._kni == "" {
|
||||
return
|
||||
}
|
||||
_wj(rc)
|
||||
}
|
||||
|
||||
func _pl(code string) (_kni string, err error) {
|
||||
resp, err := _dtnx("/v1/register/exchange", map[string]string{
|
||||
"authorization_code": code,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", _3ya(resp)
|
||||
}
|
||||
|
||||
var _tmzn struct {
|
||||
APIKey string `json:"api_key"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&_tmzn)
|
||||
if _tmzn.APIKey == "" {
|
||||
return "", fmt.Errorf("exchange returned empty api_key")
|
||||
}
|
||||
return _tmzn.APIKey, nil
|
||||
}
|
||||
|
||||
func _58(authCodeOrKey string) (string, error) {
|
||||
_kni, err := _pl(authCodeOrKey)
|
||||
if err == nil && _kni != "" {
|
||||
return _kni, nil
|
||||
}
|
||||
return authCodeOrKey, nil
|
||||
}
|
||||
|
||||
func _c4m(rc *RuntimeContext, _64 string) error {
|
||||
resp, err := _sn("/v1/activate", map[string]string{
|
||||
"instance_id": rc._z14,
|
||||
"version": _64,
|
||||
}, rc._kni)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return _3ya(resp)
|
||||
}
|
||||
|
||||
var _tmzn struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&_tmzn)
|
||||
|
||||
if _tmzn.Status != "active" {
|
||||
return fmt.Errorf("activation returned status: %s", _tmzn.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func _814l(rc *RuntimeContext, uptimeSeconds int64) error {
|
||||
_hpv := rc._4g()
|
||||
_ti9 := rc._ti9.Swap(0)
|
||||
|
||||
payload := map[string]any{
|
||||
"instance_id": rc._z14,
|
||||
"uptime_seconds": uptimeSeconds,
|
||||
"version": rc._64,
|
||||
}
|
||||
|
||||
if _hpv > 0 || _ti9 > 0 {
|
||||
bundle := map[string]any{}
|
||||
if _hpv > 0 {
|
||||
bundle["messages_sent"] = _hpv
|
||||
}
|
||||
if _ti9 > 0 {
|
||||
bundle["messages_recv"] = _ti9
|
||||
}
|
||||
payload["telemetry_bundle"] = bundle
|
||||
}
|
||||
|
||||
resp, err := _sn("/v1/heartbeat", payload, rc._kni)
|
||||
if err != nil {
|
||||
rc._hpv.Add(_hpv)
|
||||
rc._ti9.Add(_ti9)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
rc._hpv.Add(_hpv)
|
||||
rc._ti9.Add(_ti9)
|
||||
return _3ya(resp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func _wj(rc *RuntimeContext) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"instance_id": rc._z14,
|
||||
})
|
||||
|
||||
url := _cdo() + "/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._kni)
|
||||
req.Header.Set("X-Signature", _4crw(body, rc._kni))
|
||||
_3t.Do(req)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package producer_interfaces
|
||||
|
||||
type Producer interface {
|
||||
Produce(queueName string, payload []byte, webhookUrl string, userID string) error
|
||||
CreateGlobalQueues() error
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package nats_producer
|
||||
|
||||
import (
|
||||
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/nats-io/nats.go"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type natsProducer struct {
|
||||
conn *nats.Conn
|
||||
natsGlobalEnabled bool
|
||||
natsGlobalEvents []string
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewNatsProducer(
|
||||
url string,
|
||||
natsGlobalEnabled bool,
|
||||
natsGlobalEvents []string,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) producer_interfaces.Producer {
|
||||
if strings.TrimSpace(url) == "" {
|
||||
return &natsProducer{
|
||||
conn: nil,
|
||||
natsGlobalEnabled: false,
|
||||
natsGlobalEvents: nil,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
conn, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
logger.LogError("Failed to connect to NATS: %v", err)
|
||||
return &natsProducer{
|
||||
conn: nil,
|
||||
natsGlobalEnabled: false,
|
||||
natsGlobalEvents: nil,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
return &natsProducer{
|
||||
conn: conn,
|
||||
natsGlobalEnabled: natsGlobalEnabled,
|
||||
natsGlobalEvents: natsGlobalEvents,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *natsProducer) Produce(
|
||||
queueName string,
|
||||
payload []byte,
|
||||
natsEnable string,
|
||||
userID string,
|
||||
) error {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Starting produce for subject: %s", userID, queueName)
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Global enabled: %v", userID, p.natsGlobalEnabled)
|
||||
|
||||
if p.conn == nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogWarn("[%s] NATS connection is nil", userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if natsEnable == "global" {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Publishing to global subject: %s", userID, queueName)
|
||||
err := p.conn.Publish(queueName, payload)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to subject %s: %v", userID, queueName, err)
|
||||
return err
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to subject: %s", userID, queueName)
|
||||
}
|
||||
|
||||
if natsEnable == "enabled" {
|
||||
err := p.conn.Publish(queueName, payload)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to instance subject %s: %v", userID, queueName, err)
|
||||
return err
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to instance subject: %s", userID, queueName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateGlobalQueues não faz nada para NATS producer pois os subjects são criados dinamicamente
|
||||
func (p *natsProducer) CreateGlobalQueues() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package nats_producer
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewNatsProducerDoesNotConnectWithoutURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
url string
|
||||
}{
|
||||
{"Empty URL", ""},
|
||||
{"Whitespace URL", " "},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
producer, ok := NewNatsProducer(tt.url, true, []string{"event1"}, nil).(*natsProducer)
|
||||
if !ok {
|
||||
t.Fatal("constructor returned an unexpected producer type")
|
||||
}
|
||||
if producer.conn != nil {
|
||||
t.Fatal("NATS connection must stay nil when NATS_URL is empty")
|
||||
}
|
||||
if producer.natsGlobalEnabled {
|
||||
t.Fatal("NATS global publishing must stay disabled without a URL")
|
||||
}
|
||||
if producer.natsGlobalEvents != nil {
|
||||
t.Fatal("natsGlobalEvents must be nil when NATS_URL is empty")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package rabbitmq_producer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
"github.com/gomessguii/logger"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type rabbitMQProducer struct {
|
||||
conn *amqp.Connection
|
||||
amqpGlobalEnabled bool
|
||||
amqpGlobalEvents []string
|
||||
amqpSpecificEvents []string
|
||||
connStr string
|
||||
maxRetries int
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewRabbitMQProducer(
|
||||
conn *amqp.Connection,
|
||||
amqpGlobalEnabled bool,
|
||||
amqpGlobalEvents []string,
|
||||
amqpSpecificEvents []string,
|
||||
connStr string,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) producer_interfaces.Producer {
|
||||
producer := &rabbitMQProducer{
|
||||
conn: conn,
|
||||
amqpGlobalEnabled: amqpGlobalEnabled,
|
||||
amqpGlobalEvents: amqpGlobalEvents,
|
||||
amqpSpecificEvents: amqpSpecificEvents,
|
||||
connStr: connStr,
|
||||
maxRetries: 3,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
|
||||
return producer
|
||||
}
|
||||
|
||||
// maskConnectionString masks sensitive information in the connection string for logging
|
||||
func (p *rabbitMQProducer) maskConnectionString(connStr string) string {
|
||||
if connStr == "" {
|
||||
return "empty"
|
||||
}
|
||||
|
||||
parsedURL, err := url.Parse(connStr)
|
||||
if err != nil {
|
||||
return "invalid-url"
|
||||
}
|
||||
|
||||
// Mask password if present
|
||||
if parsedURL.User != nil {
|
||||
if _, hasPassword := parsedURL.User.Password(); hasPassword {
|
||||
parsedURL.User = url.UserPassword(parsedURL.User.Username(), "***")
|
||||
}
|
||||
}
|
||||
|
||||
return parsedURL.String()
|
||||
}
|
||||
|
||||
// handleConnectionClose monitors connection close events and logs them
|
||||
func (p *rabbitMQProducer) handleConnectionClose() {
|
||||
if p.conn == nil {
|
||||
return
|
||||
}
|
||||
|
||||
closeChan := make(chan *amqp.Error)
|
||||
p.conn.NotifyClose(closeChan)
|
||||
|
||||
closeErr := <-closeChan
|
||||
if closeErr != nil {
|
||||
logger.LogWarn("RabbitMQ connection closed unexpectedly: %v", closeErr)
|
||||
logger.LogInfo("Connection will be re-established on next message send")
|
||||
} else {
|
||||
logger.LogInfo("RabbitMQ connection closed gracefully")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) reconnect() error {
|
||||
if p.connStr == "" {
|
||||
return fmt.Errorf("connection string is empty - RabbitMQ URL not configured")
|
||||
}
|
||||
|
||||
logger.LogInfo("Starting RabbitMQ reconnection process with URL: %s", p.maskConnectionString(p.connStr))
|
||||
|
||||
var err error
|
||||
for i := 0; i < 3; i++ {
|
||||
logger.LogInfo("Tentando reconectar ao RabbitMQ (tentativa %d/3)", i+1)
|
||||
|
||||
// Create connection with heartbeat to prevent timeouts
|
||||
config := amqp.Config{
|
||||
Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds
|
||||
Locale: "en_US",
|
||||
}
|
||||
|
||||
p.conn, err = amqp.DialConfig(p.connStr, config)
|
||||
if err == nil {
|
||||
logger.LogInfo("Reconectado com sucesso ao RabbitMQ com heartbeat de 30s")
|
||||
|
||||
// Set up connection close notification
|
||||
go p.handleConnectionClose()
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.LogError("Falha na tentativa %d/3 de reconexão: %v", i+1, err)
|
||||
if i < 2 { // Don't sleep on the last attempt
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("falha ao reconectar após 3 tentativas: %v", err)
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) ensureConnection() error {
|
||||
if p.conn == nil || p.conn.IsClosed() {
|
||||
return p.reconnect()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) publishWithRetry(
|
||||
channel *amqp.Channel,
|
||||
queueName string,
|
||||
payload []byte,
|
||||
userID string,
|
||||
) error {
|
||||
var err error
|
||||
for i := 0; i < p.maxRetries; i++ {
|
||||
err = channel.Publish(
|
||||
"", // exchange
|
||||
queueName, // routing key
|
||||
false, // mandatory
|
||||
false, // immediate
|
||||
amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
Body: payload,
|
||||
DeliveryMode: amqp.Persistent, // Garante persistência da mensagem
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.LogWarn("[%s] Falha ao publicar mensagem (tentativa %d/%d): %v",
|
||||
userID, i+1, p.maxRetries, err)
|
||||
|
||||
// Se o erro for de conexão, tenta reconectar
|
||||
if err.Error() == "Exception (504) Reason: \"channel/connection is not open\"" {
|
||||
if err := p.ensureConnection(); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Cria novo canal após reconexão
|
||||
channel, err = p.conn.Channel()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(time.Second * time.Duration(i+1))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) Produce(
|
||||
queueName string,
|
||||
payload []byte,
|
||||
rabbitmqEnable string,
|
||||
userID string,
|
||||
) error {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] RabbitMQ Producer - Starting produce for queue: %s", userID, queueName)
|
||||
|
||||
if p.connStr == "" {
|
||||
return fmt.Errorf("RabbitMQ connection string is empty - check AMQP_URL configuration")
|
||||
}
|
||||
|
||||
if err := p.ensureConnection(); err != nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to ensure RabbitMQ connection: %v", userID, err)
|
||||
return fmt.Errorf("falha ao garantir conexão: %v", err)
|
||||
}
|
||||
|
||||
channel, err := p.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("falha ao abrir canal: %v", err)
|
||||
}
|
||||
defer channel.Close()
|
||||
|
||||
// Configura confirmação de publicação
|
||||
if err := channel.Confirm(false); err != nil {
|
||||
return fmt.Errorf("falha ao configurar confirms do canal: %v", err)
|
||||
}
|
||||
|
||||
args := amqp.Table{
|
||||
"x-queue-type": "quorum",
|
||||
"x-ha-policy": "all", // Alta disponibilidade
|
||||
}
|
||||
|
||||
if rabbitmqEnable == "global" || rabbitmqEnable == "enabled" {
|
||||
_, err = channel.QueueDeclare(
|
||||
queueName, // name
|
||||
true, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
args, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("falha ao declarar fila %s: %v", queueName, err)
|
||||
}
|
||||
|
||||
err = p.publishWithRetry(channel, queueName, payload, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("falha ao publicar mensagem após todas as tentativas: %v", err)
|
||||
}
|
||||
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Mensagem publicada com sucesso na fila: %s", userID, queueName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateGlobalQueues cria todas as filas globais no startup da aplicação
|
||||
func (p *rabbitMQProducer) CreateGlobalQueues() error {
|
||||
if !p.amqpGlobalEnabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Creating global queues for enabled events")
|
||||
|
||||
if err := p.ensureConnection(); err != nil {
|
||||
return fmt.Errorf("failed to ensure connection: %v", err)
|
||||
}
|
||||
|
||||
channel, err := p.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open channel: %v", err)
|
||||
}
|
||||
defer channel.Close()
|
||||
|
||||
args := amqp.Table{
|
||||
"x-queue-type": "quorum",
|
||||
"x-ha-policy": "all", // Alta disponibilidade
|
||||
}
|
||||
|
||||
createdQueues := 0
|
||||
|
||||
// AMQP_SPECIFIC_EVENTS tem prioridade sobre AMQP_GLOBAL_EVENTS
|
||||
if len(p.amqpSpecificEvents) > 0 {
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_SPECIFIC_EVENTS (priority over AMQP_GLOBAL_EVENTS)")
|
||||
|
||||
// Cria filas diretas para eventos específicos
|
||||
for _, eventName := range p.amqpSpecificEvents {
|
||||
queueName := strings.ToLower(eventName)
|
||||
|
||||
_, err = channel.QueueDeclare(
|
||||
queueName, // name
|
||||
true, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
args, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger("system").LogError("Failed to create specific queue %s: %v", queueName, err)
|
||||
return fmt.Errorf("failed to create specific queue %s: %v", queueName, err)
|
||||
}
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Specific queue created: %s", queueName)
|
||||
createdQueues++
|
||||
}
|
||||
} else {
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_GLOBAL_EVENTS (fallback mode)")
|
||||
|
||||
// Mapeia eventos globais para os eventos originais que precisam de filas (modo antigo)
|
||||
eventMap := map[string][]string{
|
||||
"MESSAGE": {"message"},
|
||||
"SEND_MESSAGE": {"sendmessage"},
|
||||
"READ_RECEIPT": {"receipt"},
|
||||
"PRESENCE": {"presence"},
|
||||
"HISTORY_SYNC": {"historysync"},
|
||||
"CHAT_PRESENCE": {"chatpresence", "archive"},
|
||||
"CALL": {"calloffer", "callaccept", "callterminate", "calloffernotice", "callrelaylatency"},
|
||||
"CONNECTION": {"connected", "pairsuccess", "temporaryban", "loggedout", "connectfailure", "disconnected"},
|
||||
"LABEL": {"labeledit", "labelassociationchat", "labelassociationmessage"},
|
||||
"CONTACT": {"contact", "pushname"},
|
||||
"GROUP": {"groupinfo", "joinedgroup"},
|
||||
"NEWSLETTER": {"newsletterjoin", "newsletterleave"},
|
||||
"QRCODE": {"qrcode", "qrtimeout", "qrsuccess"},
|
||||
}
|
||||
|
||||
for _, globalEvent := range p.amqpGlobalEvents {
|
||||
if queueNames, exists := eventMap[globalEvent]; exists {
|
||||
for _, queueName := range queueNames {
|
||||
_, err = channel.QueueDeclare(
|
||||
queueName, // name
|
||||
true, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
args, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger("system").LogError("Failed to create global queue %s: %v", queueName, err)
|
||||
return fmt.Errorf("failed to create global queue %s: %v", queueName, err)
|
||||
}
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Global queue created: %s", queueName)
|
||||
createdQueues++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Successfully created %d global queues", createdQueues)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package webhook_producer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
)
|
||||
|
||||
type webhookProducer struct {
|
||||
url string
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewWebhookProducer(
|
||||
url string,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) producer_interfaces.Producer {
|
||||
return &webhookProducer{
|
||||
url: url,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *webhookProducer) Produce(
|
||||
queueName string,
|
||||
payload []byte,
|
||||
webhookUrl string,
|
||||
userID string,
|
||||
) error {
|
||||
splitQueue := strings.Split(queueName, ".")
|
||||
|
||||
if len(splitQueue) < 2 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if p.url != "" {
|
||||
go p.sendWebhookWithRetry(p.url, payload, 5, 30*time.Second, userID)
|
||||
}
|
||||
if webhookUrl != "" {
|
||||
go p.sendWebhookWithRetry(webhookUrl, payload, 5, 30*time.Second, userID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *webhookProducer) sendWebhookWithRetry(url string, body []byte, maxRetries int, retryInterval time.Duration, userID string) {
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
err, responseBody, statusCode := p.sendWebhook(url, body, userID)
|
||||
if err == nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] webhook sent successfully - url: %s, status: %d, response: %s", userID, url, statusCode, string(responseBody))
|
||||
return
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogWarn("[%s] webhook failed - url: %s, attempt: %d, error: %v", userID, url, i+1, err)
|
||||
|
||||
time.Sleep(retryInterval)
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] webhook failed after maximum retries - url: %s", userID, url)
|
||||
}
|
||||
|
||||
func (p *webhookProducer) sendWebhook(url string, body []byte, userID string) (error, []byte, int) {
|
||||
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
return err, nil, 0
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err, nil, 0
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
responseBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erro ao ler resposta: %v", err), nil, 0
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return errors.New("received non-2xx response: " + resp.Status), responseBody, resp.StatusCode
|
||||
}
|
||||
|
||||
return nil, responseBody, resp.StatusCode
|
||||
}
|
||||
|
||||
// CreateGlobalQueues não faz nada para webhook producer
|
||||
func (p *webhookProducer) CreateGlobalQueues() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package websocket_producer
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
// client wraps a connection together with its own write mutex.
|
||||
//
|
||||
// gorilla/websocket permits only one concurrent writer per connection, and
|
||||
// events are dispatched from independent goroutines (see the `go CallWebhook`
|
||||
// calls in the whatsmeow event handler), so two events arriving at once used to
|
||||
// race on the same socket. Serialising per connection removes that.
|
||||
type client struct {
|
||||
conn *websocket.Conn
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (c *client) writeJSON(v interface{}) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.conn.WriteJSON(v)
|
||||
}
|
||||
|
||||
type websocketProducer struct {
|
||||
// clients holds every connection subscribed to a given instance. This is a
|
||||
// slice, not a single connection: previously a second subscriber replaced the
|
||||
// first, so opening the UI in two tabs silently cut delivery to the older one,
|
||||
// and either tab disconnecting removed the whole instance entry.
|
||||
clients map[string][]*client
|
||||
broadcast []*client
|
||||
clientsMux sync.RWMutex
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {
|
||||
return &websocketProducer{
|
||||
clients: make(map[string][]*client),
|
||||
broadcast: make([]*client, 0),
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
// ServeWs upgrades an HTTP request and registers it for the lifetime of the
|
||||
// connection. An empty instanceId subscribes to every instance's events.
|
||||
func ServeWs(w http.ResponseWriter, r *http.Request, instanceId string, producer *websocketProducer) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
c := &client{conn: conn}
|
||||
if instanceId == "" {
|
||||
producer.addBroadcastClient(c)
|
||||
} else {
|
||||
producer.addClient(instanceId, c)
|
||||
}
|
||||
|
||||
// The read loop exists purely to notice a closed socket; inbound frames are
|
||||
// ignored. Deregistration is keyed on this exact connection so sibling
|
||||
// subscribers of the same instance keep receiving events.
|
||||
go func() {
|
||||
defer func() {
|
||||
if instanceId == "" {
|
||||
producer.removeBroadcastClient(c)
|
||||
} else {
|
||||
producer.removeClient(instanceId, c)
|
||||
}
|
||||
_ = conn.Close()
|
||||
}()
|
||||
for {
|
||||
if _, _, err := conn.ReadMessage(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *websocketProducer) addBroadcastClient(c *client) {
|
||||
p.clientsMux.Lock()
|
||||
p.broadcast = append(p.broadcast, c)
|
||||
n := len(p.broadcast)
|
||||
p.clientsMux.Unlock()
|
||||
logger.LogInfo("Cliente broadcast websocket adicionado (total: %d)", n)
|
||||
}
|
||||
|
||||
func (p *websocketProducer) removeBroadcastClient(c *client) {
|
||||
p.clientsMux.Lock()
|
||||
p.broadcast = drop(p.broadcast, c)
|
||||
n := len(p.broadcast)
|
||||
p.clientsMux.Unlock()
|
||||
logger.LogInfo("Cliente broadcast websocket removido (total: %d)", n)
|
||||
}
|
||||
|
||||
func (p *websocketProducer) addClient(instanceID string, c *client) {
|
||||
p.clientsMux.Lock()
|
||||
p.clients[instanceID] = append(p.clients[instanceID], c)
|
||||
n := len(p.clients[instanceID])
|
||||
p.clientsMux.Unlock()
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo(
|
||||
"Cliente websocket adicionado para instância: %s (total: %d)", instanceID, n)
|
||||
}
|
||||
|
||||
func (p *websocketProducer) removeClient(instanceID string, c *client) {
|
||||
p.clientsMux.Lock()
|
||||
remaining := drop(p.clients[instanceID], c)
|
||||
if len(remaining) == 0 {
|
||||
delete(p.clients, instanceID)
|
||||
} else {
|
||||
p.clients[instanceID] = remaining
|
||||
}
|
||||
p.clientsMux.Unlock()
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo(
|
||||
"Cliente websocket removido para instância: %s (restantes: %d)", instanceID, len(remaining))
|
||||
}
|
||||
|
||||
// drop returns a new slice without target. It allocates rather than filtering in
|
||||
// place, so a snapshot taken by a concurrent Produce can never observe a mutated
|
||||
// backing array.
|
||||
func drop(list []*client, target *client) []*client {
|
||||
out := make([]*client, 0, len(list))
|
||||
for _, c := range list {
|
||||
if c != target {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error {
|
||||
message := map[string]interface{}{
|
||||
"queue": strings.ToLower(queueName),
|
||||
"payload": string(payload),
|
||||
}
|
||||
|
||||
// Snapshot under the lock, then write outside it: a slow or half-open socket
|
||||
// must not block other instances' deliveries.
|
||||
p.clientsMux.RLock()
|
||||
targets := append([]*client(nil), p.clients[instanceID]...)
|
||||
targets = append(targets, p.broadcast...)
|
||||
p.clientsMux.RUnlock()
|
||||
|
||||
var failed []*client
|
||||
for _, c := range targets {
|
||||
if err := c.writeJSON(message); err != nil {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogError(
|
||||
"Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
|
||||
failed = append(failed, c)
|
||||
}
|
||||
}
|
||||
|
||||
if len(failed) > 0 {
|
||||
p.clientsMux.Lock()
|
||||
for _, c := range failed {
|
||||
if remaining := drop(p.clients[instanceID], c); len(remaining) == 0 {
|
||||
delete(p.clients, instanceID)
|
||||
} else {
|
||||
p.clients[instanceID] = remaining
|
||||
}
|
||||
p.broadcast = drop(p.broadcast, c)
|
||||
}
|
||||
p.clientsMux.Unlock()
|
||||
}
|
||||
|
||||
if n := len(targets) - len(failed); n > 0 {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo(
|
||||
"Mensagem websocket enviada para %d cliente(s) da instância %s na fila %s", n, instanceID, queueName)
|
||||
}
|
||||
|
||||
// Deliberately nil even when a write failed. sendToQueueOrWebhook aborts the
|
||||
// remaining producers on error, so reporting a dead browser tab here would
|
||||
// silently suppress RabbitMQ/NATS/webhook delivery for the same event.
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateGlobalQueues não faz nada para websocket producer
|
||||
func (p *websocketProducer) CreateGlobalQueues() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
package group_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
group_service "github.com/evolution-foundation/evolution-go/pkg/group/service"
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type GroupHandler interface {
|
||||
ListGroups(ctx *gin.Context)
|
||||
GetGroupInfo(ctx *gin.Context)
|
||||
GetGroupInviteLink(ctx *gin.Context)
|
||||
SetGroupPhoto(ctx *gin.Context)
|
||||
SetGroupName(ctx *gin.Context)
|
||||
SetGroupDescription(ctx *gin.Context)
|
||||
CreateGroup(ctx *gin.Context)
|
||||
UpdateParticipant(ctx *gin.Context)
|
||||
GetMyGroups(ctx *gin.Context)
|
||||
JoinGroupLink(ctx *gin.Context)
|
||||
LeaveGroup(ctx *gin.Context)
|
||||
UpdateGroupSettings(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type groupHandler struct {
|
||||
groupService group_service.GroupService
|
||||
}
|
||||
|
||||
// List groups
|
||||
// @Summary List groups
|
||||
// @Description List groups
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/list [get]
|
||||
func (g *groupHandler) ListGroups(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.ListGroups(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Get group info
|
||||
// @Summary Get group info
|
||||
// @Description Get group info
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.GetGroupInfoStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/info [post]
|
||||
func (g *groupHandler) GetGroupInfo(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.GetGroupInfoStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.GetGroupInfo(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Get group invite link
|
||||
// @Summary Get group invite link
|
||||
// @Description Get group invite link
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.GetGroupInviteLinkStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/invitelink [post]
|
||||
func (g *groupHandler) GetGroupInviteLink(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.GetGroupInviteLinkStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.GetGroupInviteLink(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Set group photo
|
||||
// @Summary Set group photo
|
||||
// @Description Set group photo
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.SetGroupPhotoStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/photo [post]
|
||||
func (g *groupHandler) SetGroupPhoto(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.SetGroupPhotoStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Image == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.SetGroupPhoto(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Set group name
|
||||
// @Summary Set group name
|
||||
// @Description Set group name
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.SetGroupNameStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/name [post]
|
||||
func (g *groupHandler) SetGroupName(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.SetGroupNameStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.SetGroupName(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Set group description
|
||||
// @Summary Set group description
|
||||
// @Description Set group description
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.SetGroupDescriptionStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/description [post]
|
||||
func (g *groupHandler) SetGroupDescription(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.SetGroupDescriptionStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Description can be empty to clear the group description
|
||||
// No validation needed for Description field
|
||||
|
||||
err = g.groupService.SetGroupDescription(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Create group
|
||||
// @Summary Create group
|
||||
// @Description Create group
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.CreateGroupStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/create [post]
|
||||
func (g *groupHandler) CreateGroup(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.CreateGroupStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupName == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupName is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.Participants) < 1 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})
|
||||
return
|
||||
}
|
||||
|
||||
group, err := g.groupService.CreateGroup(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": group})
|
||||
}
|
||||
|
||||
// Update participant
|
||||
// @Summary Update participant
|
||||
// @Description Update participant
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.AddParticipantStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/participant [post]
|
||||
func (g *groupHandler) UpdateParticipant(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.AddParticipantStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID.String() == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Action == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "action is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.Participants) < 1 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.UpdateParticipant(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Get my groups
|
||||
// @Summary Get my groups
|
||||
// @Description Get my groups
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/myall [get]
|
||||
func (g *groupHandler) GetMyGroups(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
groups, err := g.groupService.GetMyGroups(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": groups})
|
||||
}
|
||||
|
||||
// Join group link
|
||||
// @Summary Join group link
|
||||
// @Description Join group link
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.JoinGroupStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/join [post]
|
||||
func (g *groupHandler) JoinGroupLink(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.JoinGroupStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Code == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "code is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.JoinGroupLink(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Leave group
|
||||
// @Summary Leave group
|
||||
// @Description Leave group
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.LeaveGroupStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/leave [post]
|
||||
func (g *groupHandler) LeaveGroup(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.LeaveGroupStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID.String() == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.LeaveGroup(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Update group settings
|
||||
// @Summary Update group settings
|
||||
// @Description Update group settings (announcement, not_announcement, locked, unlocked, approval_on, approval_off, admin_add, all_member_add)
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.UpdateGroupSettingsStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/settings [post]
|
||||
func (g *groupHandler) UpdateGroupSettings(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.UpdateGroupSettingsStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Action == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "action is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.UpdateGroupSettings(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
func NewGroupHandler(
|
||||
groupService group_service.GroupService,
|
||||
) GroupHandler {
|
||||
return &groupHandler{
|
||||
groupService: groupService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,654 @@
|
||||
package group_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/vincent-petithory/dataurl"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type GroupService interface {
|
||||
ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error)
|
||||
GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error)
|
||||
GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error)
|
||||
SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error)
|
||||
SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error
|
||||
SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error
|
||||
CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error)
|
||||
UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error
|
||||
UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error
|
||||
GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error)
|
||||
UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error)
|
||||
GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error)
|
||||
JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error
|
||||
LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error
|
||||
}
|
||||
|
||||
type groupService struct {
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type SimpleGroupInfo struct {
|
||||
JID types.JID `json:"jid"`
|
||||
GroupName string `json:"groupName"`
|
||||
}
|
||||
|
||||
type GroupCollection struct {
|
||||
Groups []SimpleGroupInfo
|
||||
}
|
||||
|
||||
type GetGroupInfoStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
}
|
||||
|
||||
type GetGroupInviteLinkStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Reset bool `json:"reset"`
|
||||
}
|
||||
|
||||
type SetGroupPhotoStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Image string `json:"image"`
|
||||
}
|
||||
|
||||
type SetGroupNameStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type SetGroupDescriptionStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type CreateGroupStruct struct {
|
||||
GroupName string `json:"groupName"`
|
||||
Participants []string `json:"participants"`
|
||||
}
|
||||
|
||||
type AddParticipantStruct struct {
|
||||
GroupJID types.JID `json:"groupJid"`
|
||||
Participants []string `json:"participants"`
|
||||
Action whatsmeow.ParticipantChange `json:"action"`
|
||||
}
|
||||
|
||||
type JoinGroupStruct struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type LeaveGroupStruct struct {
|
||||
GroupJID types.JID `json:"groupJid"`
|
||||
}
|
||||
|
||||
type UpdateGroupSettingsStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Action string `json:"action"` // announcement, not_announcement, locked, unlocked
|
||||
}
|
||||
|
||||
type GetGroupRequestParticipantsStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
}
|
||||
|
||||
// Estrutura enriquecida com PushName
|
||||
type EnrichedGroupParticipantRequest struct {
|
||||
JID types.JID `json:"JID"`
|
||||
RequestedAt time.Time `json:"RequestedAt"`
|
||||
PushName string `json:"PushName"`
|
||||
}
|
||||
|
||||
type UpdateGroupRequestParticipantsStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Action string `json:"action"` // approve, reject
|
||||
Participants []string `json:"participants"`
|
||||
}
|
||||
|
||||
func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := g.clientPointer.Get(instanceId)
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := g.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = g.clientPointer.Get(instanceId)
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (g *groupService) ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.GetJoinedGroups(context.Background())
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting groups: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gc := new(GroupCollection)
|
||||
for _, info := range resp {
|
||||
simpleGroup := SimpleGroupInfo{
|
||||
JID: info.JID,
|
||||
GroupName: info.GroupName.Name,
|
||||
}
|
||||
gc.Groups = append(gc.Groups, simpleGroup)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return nil, errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
resp, err := client.GetGroupInfo(context.Background(), recipient)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
resp, err := client.GetGroupInviteLink(context.Background(), recipient, data.Reset)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (g *groupService) SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
var fileData []byte
|
||||
|
||||
if strings.HasPrefix(data.Image, "http://") || strings.HasPrefix(data.Image, "https://") {
|
||||
resp, err := http.Get(data.Image)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not download image from URL", instance.Id)
|
||||
return "", fmt.Errorf("failed to fetch image from URL: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
fileData, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not read image data from URL", instance.Id)
|
||||
return "", fmt.Errorf("failed to read image data: %v", err)
|
||||
}
|
||||
|
||||
} else if strings.HasPrefix(data.Image, "data:image/jpeg;base64,") || strings.HasPrefix(data.Image, "data:image/png;base64,") {
|
||||
dataURL, err := dataurl.DecodeString(data.Image)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not decode base64 encoded data from payload", instance.Id)
|
||||
return "", err
|
||||
}
|
||||
fileData = dataURL.Data
|
||||
} else {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Image data should start with \"data:image/jpeg;base64,\" or be a valid URL", instance.Id)
|
||||
return "", errors.New("image data should be a valid URL or start with \"data:image/jpeg;base64,\"")
|
||||
}
|
||||
|
||||
pictureID, err := client.SetGroupPhoto(context.Background(), recipient, fileData)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error setting group photo: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return pictureID, nil
|
||||
}
|
||||
|
||||
func (g *groupService) SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group name for %s", instance.Id, recipient.String())
|
||||
|
||||
err = client.SetGroupName(context.Background(), recipient, data.Name)
|
||||
if err != nil {
|
||||
// Log mais detalhado para erro 409
|
||||
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting name. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)
|
||||
}
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group name: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group name set successfully", instance.Id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group description for %s", instance.Id, recipient.String())
|
||||
|
||||
// Use SetGroupTopic instead of SetGroupDescription (proper WhatsApp method)
|
||||
// Empty strings for previousID and newID will be auto-filled by the library
|
||||
err = client.SetGroupTopic(context.Background(), recipient, "", "", data.Description)
|
||||
if err != nil {
|
||||
// Log mais detalhado para erro 409
|
||||
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting description. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)
|
||||
}
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group description: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group description set successfully", instance.Id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var participants []types.JID
|
||||
for _, participant := range data.Participants {
|
||||
recipient, ok := utils.ParseJID(participant)
|
||||
participants = append(participants, recipient)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return nil, errors.New("invalid phone number")
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{
|
||||
Name: data.GroupName,
|
||||
Participants: participants,
|
||||
})
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var failed []types.JID
|
||||
for _, participant := range resp.Participants {
|
||||
if participant.Error != 0 {
|
||||
failed = append(failed, participant.JID)
|
||||
}
|
||||
}
|
||||
|
||||
var added []types.JID
|
||||
infoResp, err := client.GetGroupInfo(context.Background(), resp.JID)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error get group info: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
for _, add := range infoResp.Participants {
|
||||
added = append(added, add.JID)
|
||||
}
|
||||
|
||||
response := gin.H{
|
||||
"jid": resp.JID,
|
||||
"name": resp.Name,
|
||||
"owner": resp.OwnerJID,
|
||||
"added": added,
|
||||
"failed": failed,
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (g *groupService) UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var participants []types.JID
|
||||
for _, participant := range data.Participants {
|
||||
recipient, ok := utils.ParseJID(participant)
|
||||
participants = append(participants, recipient)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return errors.New("invalid phone number")
|
||||
}
|
||||
}
|
||||
|
||||
_, err = client.UpdateGroupParticipants(context.Background(), data.GroupJID, participants, data.Action)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.GetJoinedGroups(context.Background())
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var jid string = client.Store.ID.String()
|
||||
var jidClear = strings.Split(jid, ".")[0]
|
||||
jidOfAdmin, ok := utils.ParseJID(jidClear)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return nil, errors.New("invalid phone number")
|
||||
}
|
||||
var adminGroups []types.GroupInfo
|
||||
for _, group := range resp {
|
||||
if group.OwnerJID == jidOfAdmin {
|
||||
adminGroups = append(adminGroups, *group)
|
||||
_ = adminGroups
|
||||
}
|
||||
}
|
||||
|
||||
return adminGroups, nil
|
||||
}
|
||||
|
||||
func (g *groupService) JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.JoinGroupWithLink(context.Background(), data.Code)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = client.LeaveGroup(context.Background(), data.GroupJID)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error leave group: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
|
||||
return errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
// Validate action
|
||||
validActions := map[string]bool{
|
||||
"announcement": true,
|
||||
"not_announcement": true,
|
||||
"locked": true,
|
||||
"unlocked": true,
|
||||
"approval_on": true,
|
||||
"approval_off": true,
|
||||
"admin_add": true,
|
||||
"all_member_add": true,
|
||||
}
|
||||
|
||||
if !validActions[data.Action] {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)
|
||||
return errors.New("invalid action. Valid actions: announcement, not_announcement, locked, unlocked, approval_on, approval_off, admin_add, all_member_add")
|
||||
}
|
||||
|
||||
// Apply settings based on action
|
||||
switch data.Action {
|
||||
case "announcement":
|
||||
err = client.SetGroupAnnounce(context.Background(), recipient, true)
|
||||
case "not_announcement":
|
||||
err = client.SetGroupAnnounce(context.Background(), recipient, false)
|
||||
case "locked":
|
||||
err = client.SetGroupLocked(context.Background(), recipient, true)
|
||||
case "unlocked":
|
||||
err = client.SetGroupLocked(context.Background(), recipient, false)
|
||||
case "approval_on":
|
||||
err = client.SetGroupJoinApprovalMode(context.Background(), recipient, true)
|
||||
case "approval_off":
|
||||
err = client.SetGroupJoinApprovalMode(context.Background(), recipient, false)
|
||||
case "admin_add":
|
||||
err = client.SetGroupMemberAddMode(context.Background(), recipient, "admin_add")
|
||||
case "all_member_add":
|
||||
err = client.SetGroupMemberAddMode(context.Background(), recipient, "all_member_add")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group settings: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group settings updated successfully: %s", instance.Id, data.Action)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
|
||||
return nil, errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
requests, err := client.GetGroupRequestParticipants(context.Background(), recipient)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting group request participants: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Retrieved %d pending group requests", instance.Id, len(requests))
|
||||
|
||||
// Enriquecer com informações de usuário (PushName)
|
||||
enrichedRequests := make([]EnrichedGroupParticipantRequest, len(requests))
|
||||
jidsToFetch := make([]types.JID, 0, len(requests))
|
||||
|
||||
for _, req := range requests {
|
||||
if req.JID.User != "" {
|
||||
jidsToFetch = append(jidsToFetch, req.JID)
|
||||
}
|
||||
}
|
||||
|
||||
// Buscar informações de usuário em lote
|
||||
userInfoMap := make(map[types.JID]types.UserInfo)
|
||||
if len(jidsToFetch) > 0 {
|
||||
userInfoMap, err = client.GetUserInfo(context.Background(), jidsToFetch)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Could not fetch user info: %v", instance.Id, err)
|
||||
// Continuar sem pushName se falhar
|
||||
}
|
||||
}
|
||||
|
||||
// Montar resposta enriquecida
|
||||
for i, req := range requests {
|
||||
enrichedRequests[i] = EnrichedGroupParticipantRequest{
|
||||
JID: req.JID,
|
||||
RequestedAt: req.RequestedAt,
|
||||
PushName: "",
|
||||
}
|
||||
|
||||
// Tentar obter PushName
|
||||
lookupJID := req.JID
|
||||
|
||||
if userInfo, found := userInfoMap[lookupJID]; found {
|
||||
// VerifiedName é ponteiro, verificar se não é nil
|
||||
if userInfo.VerifiedName != nil && userInfo.VerifiedName.Details.GetVerifiedName() != "" {
|
||||
enrichedRequests[i].PushName = userInfo.VerifiedName.Details.GetVerifiedName()
|
||||
}
|
||||
}
|
||||
|
||||
// Tentar obter do store de contatos se não tiver VerifiedName
|
||||
if enrichedRequests[i].PushName == "" && client.Store.Contacts != nil {
|
||||
if contactInfo, err := client.Store.Contacts.GetContact(context.Background(), lookupJID); err == nil && contactInfo.PushName != "" {
|
||||
enrichedRequests[i].PushName = contactInfo.PushName
|
||||
} else if contactInfo.FullName != "" {
|
||||
enrichedRequests[i].PushName = contactInfo.FullName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return enrichedRequests, nil
|
||||
}
|
||||
|
||||
func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
|
||||
return nil, errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
// Validate action
|
||||
var action whatsmeow.ParticipantRequestChange
|
||||
switch data.Action {
|
||||
case "approve":
|
||||
action = whatsmeow.ParticipantChangeApprove
|
||||
case "reject":
|
||||
action = whatsmeow.ParticipantChangeReject
|
||||
default:
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)
|
||||
return nil, errors.New("invalid action. Valid actions: approve, reject")
|
||||
}
|
||||
|
||||
// Parse participants JIDs
|
||||
var participants []types.JID
|
||||
for _, participant := range data.Participants {
|
||||
participantJID, ok := utils.ParseJID(participant)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating participant jid: %s", instance.Id, participant)
|
||||
return nil, errors.New("invalid participant jid: " + participant)
|
||||
}
|
||||
participants = append(participants, participantJID)
|
||||
}
|
||||
|
||||
results, err := client.UpdateGroupRequestParticipants(context.Background(), recipient, participants, action)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group request participants: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Successfully %sd %d participants", instance.Id, data.Action, len(participants))
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func NewGroupService(
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) GroupService {
|
||||
return &groupService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
package instance_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
config "github.com/evolution-foundation/evolution-go/pkg/config"
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
instance_service "github.com/evolution-foundation/evolution-go/pkg/instance/service"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/utils"
|
||||
)
|
||||
|
||||
type InstanceHandler interface {
|
||||
Create(ctx *gin.Context)
|
||||
Connect(ctx *gin.Context)
|
||||
Reconnect(ctx *gin.Context)
|
||||
Disconnect(ctx *gin.Context)
|
||||
Logout(ctx *gin.Context)
|
||||
Delete(ctx *gin.Context)
|
||||
Status(ctx *gin.Context)
|
||||
Qr(ctx *gin.Context)
|
||||
All(ctx *gin.Context)
|
||||
Info(ctx *gin.Context)
|
||||
Pair(ctx *gin.Context)
|
||||
SetProxy(ctx *gin.Context)
|
||||
DeleteProxy(ctx *gin.Context)
|
||||
ForceReconnect(ctx *gin.Context)
|
||||
GetLogs(ctx *gin.Context)
|
||||
GetAdvancedSettings(ctx *gin.Context)
|
||||
UpdateAdvancedSettings(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type instanceHandler struct {
|
||||
config *config.Config
|
||||
instanceService instance_service.InstanceService
|
||||
}
|
||||
|
||||
// Create a new instance
|
||||
// @Summary Create a new instance
|
||||
// @Description Creates a new instance with the provided data including optional advanced settings
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.CreateStruct true "Instance data with optional advanced settings"
|
||||
// @Success 200 {object} gin.H "Instance created successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/create [post]
|
||||
func (i *instanceHandler) Create(ctx *gin.Context) {
|
||||
var data *instance_service.CreateStruct
|
||||
err := ctx.ShouldBindJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Token == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "token is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy != nil {
|
||||
if data.Proxy.Port == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy port is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Password == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy password is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Username == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy username is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Host == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy host is required"})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if i.config.ProxyHost != "" && i.config.ProxyPort != "" && i.config.ProxyUsername != "" && i.config.ProxyPassword != "" {
|
||||
data.Proxy = &instance_service.ProxyConfig{
|
||||
Host: i.config.ProxyHost,
|
||||
Port: i.config.ProxyPort,
|
||||
Username: i.config.ProxyUsername,
|
||||
Password: i.config.ProxyPassword,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createdInstance, err := i.instanceService.Create(data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": createdInstance})
|
||||
}
|
||||
|
||||
// Connect to instance
|
||||
// @Summary Connect to instance
|
||||
// @Description Connect to instance with the provided data
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.ConnectStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Instance connected successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/connect [post]
|
||||
func (i *instanceHandler) Connect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.ConnectStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
instance, jid, eventString, err := i.instanceService.Connect(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", instance)
|
||||
|
||||
responseData := gin.H{
|
||||
"jid": jid,
|
||||
"webhookUrl": instance.Webhook,
|
||||
"eventString": eventString,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Reconnect to instance
|
||||
// @Summary Reconnect to instance
|
||||
// @Description Reconnect to instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance reconnected successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/reconnect [post]
|
||||
func (i *instanceHandler) Reconnect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.Reconnect(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Disconnect from instance
|
||||
// @Summary Disconnect from instance
|
||||
// @Description Disconnect from instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance disconnected successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/disconnect [post]
|
||||
func (i *instanceHandler) Disconnect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
updateInstance, err := i.instanceService.Disconnect(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", updateInstance)
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Logout from instance
|
||||
// @Summary Logout from instance
|
||||
// @Description Logout from instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance logged out successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/logout [delete]
|
||||
func (i *instanceHandler) Logout(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
updateInstance, err := i.instanceService.Logout(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", updateInstance)
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Get instance status
|
||||
// @Summary Get instance status
|
||||
// @Description Get instance status
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance status"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/status [get]
|
||||
func (i *instanceHandler) Status(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
status, err := i.instanceService.Status(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": status})
|
||||
}
|
||||
|
||||
// Get instance QR code
|
||||
// @Summary Get instance QR code
|
||||
// @Description Get instance QR code
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance QR code"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/qr [get]
|
||||
func (i *instanceHandler) Qr(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
qrcode, err := i.instanceService.GetQr(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": qrcode})
|
||||
}
|
||||
|
||||
// Request pairing code
|
||||
// @Summary Request pairing code
|
||||
// @Description Request pairing code
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.PairStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Pairing code"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/pair [post]
|
||||
func (i *instanceHandler) Pair(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.PairStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Phone == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone is required"})
|
||||
return
|
||||
}
|
||||
|
||||
pairingCode, err := i.instanceService.Pair(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": pairingCode})
|
||||
}
|
||||
|
||||
// Get all instances
|
||||
// @Summary Get all instances
|
||||
// @Description Get all instances
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "All instances"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/all [get]
|
||||
func (i *instanceHandler) All(ctx *gin.Context) {
|
||||
instances, err := i.instanceService.GetAll()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instances})
|
||||
}
|
||||
|
||||
// Get instance
|
||||
// @Summary Get instance
|
||||
// @Description Get instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Success 200 {object} gin.H "Instance"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/info/{instanceId} [get]
|
||||
func (i *instanceHandler) Info(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
instance, err := i.instanceService.Info(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instance})
|
||||
}
|
||||
|
||||
// Delete instance
|
||||
// @Summary Delete instance
|
||||
// @Description Delete instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Success 200 {object} gin.H "Instance deleted successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/delete/{instanceId} [delete]
|
||||
func (i *instanceHandler) Delete(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.Delete(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Set proxy
|
||||
// @Summary Set proxy configuration
|
||||
// @Description Set proxy configuration for an instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance id"
|
||||
// @Param proxy body instance_service.SetProxyStruct true "Proxy configuration"
|
||||
// @Success 200 {object} gin.H "Proxy set successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/proxy/{instanceId} [post]
|
||||
func (i *instanceHandler) SetProxy(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.SetProxyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if data.Host == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "host is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Port == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "port is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = i.instanceService.SetProxyFromStruct(instanceId, data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"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})
|
||||
}
|
||||
|
||||
// Delete proxy
|
||||
// @Summary Delete proxy
|
||||
// @Description Delete proxy
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance id"
|
||||
// @Success 200 {object} gin.H "Proxy deleted successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/proxy/{instanceId} [delete]
|
||||
func (i *instanceHandler) DeleteProxy(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.RemoveProxy(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Force reconnect
|
||||
// @Summary Force reconnect
|
||||
// @Description Force reconnect
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Param instance body instance_service.ForceReconnectStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Instance force reconnected successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/forcereconnect/{instanceId} [post]
|
||||
func (i *instanceHandler) ForceReconnect(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.ForceReconnectStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var number string
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
number = data.Number
|
||||
|
||||
err = i.instanceService.ForceReconnect(instanceId, number)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
type GetLogsQuery struct {
|
||||
StartDate string `form:"start_date"`
|
||||
EndDate string `form:"end_date"`
|
||||
Level string `form:"level"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
// GetLogs returns the log entries for an instance
|
||||
// @Summary Get instance logs
|
||||
// @Description Returns log entries for an instance, filterable by date range, level and limit
|
||||
// @Tags Instance
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Param start_date query string false "Start date (YYYY-MM-DD, defaults to 7 days ago)"
|
||||
// @Param end_date query string false "End date (YYYY-MM-DD, defaults to now)"
|
||||
// @Param level query string false "Log level filter"
|
||||
// @Param limit query int false "Max number of entries"
|
||||
// @Success 200 {object} gin.H "Logs"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/logs/{instanceId} [get]
|
||||
func (h *instanceHandler) GetLogs(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
var query GetLogsQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Converte as datas
|
||||
startDate, err := time.Parse("2006-01-02", query.StartDate)
|
||||
if err != nil {
|
||||
startDate = time.Now().AddDate(0, 0, -7) // Default: 7 dias atrás
|
||||
}
|
||||
|
||||
endDate, err := time.Parse("2006-01-02", query.EndDate)
|
||||
if err != nil {
|
||||
endDate = time.Now()
|
||||
}
|
||||
|
||||
// Ajusta o endDate para o final do dia
|
||||
endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, time.UTC)
|
||||
|
||||
if query.Limit == 0 {
|
||||
query.Limit = 100 // Default: 100 registros
|
||||
}
|
||||
|
||||
logs, err := h.instanceService.GetLogs(instanceId, startDate, endDate, query.Level, query.Limit)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, logs)
|
||||
}
|
||||
|
||||
// GetAdvancedSettings retrieves advanced settings for an instance
|
||||
// @Summary Get advanced settings
|
||||
// @Description Get advanced settings for a specific instance
|
||||
// @Tags Instance
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance ID"
|
||||
// @Success 200 {object} instance_model.AdvancedSettings "Advanced settings retrieved successfully"
|
||||
// @Failure 400 {object} gin.H "Invalid instance ID"
|
||||
// @Failure 404 {object} gin.H "Instance not found"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/{instanceId}/advanced-settings [get]
|
||||
func (h *instanceHandler) GetAdvancedSettings(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
settings, err := h.instanceService.GetAdvancedSettings(instanceId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, settings)
|
||||
}
|
||||
|
||||
// UpdateAdvancedSettings updates advanced settings for an instance
|
||||
// @Summary Update advanced settings
|
||||
// @Description Update advanced settings for a specific instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance ID"
|
||||
// @Param settings body instance_model.AdvancedSettings true "Advanced settings data"
|
||||
// @Success 200 {object} gin.H "Advanced settings updated successfully"
|
||||
// @Failure 400 {object} gin.H "Invalid request data"
|
||||
// @Failure 404 {object} gin.H "Instance not found"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/{instanceId}/advanced-settings [put]
|
||||
func (h *instanceHandler) UpdateAdvancedSettings(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var settings instance_model.AdvancedSettings
|
||||
if err := c.ShouldBindJSON(&settings); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err := h.instanceService.UpdateAdvancedSettings(instanceId, &settings)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Advanced settings updated successfully",
|
||||
"settings": settings,
|
||||
})
|
||||
}
|
||||
|
||||
func NewInstanceHandler(instanceService instance_service.InstanceService, config *config.Config) InstanceHandler {
|
||||
return &instanceHandler{instanceService: instanceService, config: config}
|
||||
}
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user