release: v0.6.1
This commit is contained in:
commit
877eef7f07
118 files changed
+46315
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,29 @@
|
||||
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
|
||||
|
||||
WADEBUG=DEBUG
|
||||
LOGTYPE=console
|
||||
WEBHOOKFILES=true
|
||||
|
||||
CONNECT_ON_STARTUP=true
|
||||
|
||||
OS_NAME=Evolution GO
|
||||
|
||||
AMQP_URL=amqp://admin:admin@localhost:5672/default
|
||||
AMQP_GLOBAL_ENABLED=false
|
||||
|
||||
WEBHOOK_URL=https://webhook.site/2e6af2fa-6b04-497f-b4a1-13a905728d83
|
||||
|
||||
# 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,55 @@
|
||||
name: Build and Publish Docker Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "*.*.*"
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: evoapicloud/evolution-go
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- 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:
|
||||
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
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
.env
|
||||
logs/*
|
||||
build/
|
||||
*.prof
|
||||
coverage.*
|
||||
.air.toml
|
||||
.idea/
|
||||
.vscode/
|
||||
.DS_Store
|
||||
.cursorrules
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
# Evolution GO - Changelog
|
||||
|
||||
## 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/EvolutionAPI/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.25.0-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 ./
|
||||
|
||||
# Copiar whatsmeow-lib que é uma dependência local
|
||||
COPY whatsmeow-lib/ ./whatsmeow-lib/
|
||||
|
||||
# Agora fazer download das dependências (com replace funcionando)
|
||||
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
|
||||
|
||||
RUN apk update && apk add --no-cache tzdata ffmpeg libjpeg-turbo libwebp
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=build /build/server .
|
||||
COPY --from=build /build/manager/dist ./manager/dist
|
||||
|
||||
ENV TZ=America/Sao_Paulo
|
||||
|
||||
ENTRYPOINT ["/app/server"]
|
||||
@@ -0,0 +1,222 @@
|
||||
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 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
|
||||
(which shall not include communications that are solely written
|
||||
by copyright holders to be excluded from the License).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based upon (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 use, reproduce, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Work, and to
|
||||
permit persons to whom the Work is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Work.
|
||||
|
||||
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 notice 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 Support. You may choose to offer, and to
|
||||
charge a fee for, warranty, support, 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 support.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same page as the copyright notice for easier identification within
|
||||
third-party archives.
|
||||
|
||||
Copyright 2025 Evolution API
|
||||
|
||||
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.
|
||||
|
||||
|
||||
ADDITIONAL CONDITIONS:
|
||||
|
||||
1. LOGO and copyright information: In the process of using Evolution Go API's
|
||||
frontend components, you may not remove or modify the LOGO or copyright
|
||||
information in the Evolution API console or applications. This restriction
|
||||
is inapplicable to uses of Evolution Go API that do not involve its frontend
|
||||
components.
|
||||
|
||||
2. Usage Notification Requirement: If Evolution Go API 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 API 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.
|
||||
@@ -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 grep -om1 "v[0-9].*" CHANGELOG.md)
|
||||
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,224 @@
|
||||
<h1 align="center">Evolution Go</h1>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://hub.docker.com/r/evoapicloud/evolution-go)
|
||||
[](./LICENSE)
|
||||
[](https://golang.org/)
|
||||
[](https://github.com/EvolutionAPI/evolution-go/stargazers)
|
||||
[](https://docs.evolutionfoundation.com.br)
|
||||
|
||||
</div>
|
||||
|
||||
<div align="center"><img src="./public/images/cover.png" width="400"></div>
|
||||
|
||||
## About
|
||||
|
||||
Evolution Go is a high-performance WhatsApp API built in Go, part of the [Evolution](https://evolutionfoundation.com.br/) ecosystem. It provides a robust, lightweight solution for WhatsApp integration using the [whatsmeow](https://github.com/tulir/whatsmeow) library.
|
||||
|
||||
## 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/EvolutionAPI/evolution-go.git
|
||||
cd evolution-go
|
||||
make docker-build
|
||||
make docker-run
|
||||
```
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EvolutionAPI/evolution-go.git
|
||||
cd evolution-go
|
||||
|
||||
# Clone whatsmeow dependency
|
||||
git clone [email protected]:EvolutionAPI/whatsmeow.git whatsmeow-lib
|
||||
|
||||
# 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)
|
||||
├── whatsmeow-lib/ # WhatsApp protocol library
|
||||
├── docs/ # Swagger documentation
|
||||
├── Dockerfile
|
||||
├── Makefile
|
||||
└── VERSION
|
||||
```
|
||||
|
||||
## Technology 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 & Support
|
||||
|
||||
| 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) |
|
||||
| WhatsApp Support | [+55 31 7503-8350](https://wa.me/553175038350) |
|
||||
| GitHub Issues | [evolution-go/issues](https://github.com/EvolutionAPI/evolution-go/issues) |
|
||||
|
||||
## Hosting
|
||||
|
||||
Deploy Evolution Go with optimized infrastructure:
|
||||
|
||||
| Product | Link |
|
||||
|---------|------|
|
||||
| Evolution Go VPS | [Hostgator - Evo Go](https://www.hostgator.com.br/52579-144-3-55.html) |
|
||||
| Evolution API VPS | [Hostgator - Evo API](https://www.hostgator.com.br/servidor-vps/hospedagem-evo-api/lp-afiliado) |
|
||||
|
||||
## Contributing
|
||||
|
||||
1. Fork the repository
|
||||
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
||||
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
|
||||
4. Push to the branch (`git push origin feature/amazing-feature`)
|
||||
5. Open a Pull Request
|
||||
|
||||
## Security
|
||||
|
||||
For security concerns, please email: contato@evolution-api.com
|
||||
|
||||
## License
|
||||
|
||||
Evolution Go is licensed under the Apache License 2.0, with the following additional conditions:
|
||||
|
||||
1. **Logo and copyright**: You may not remove or modify the logo or copyright information in the Evolution console or applications when using frontend components.
|
||||
|
||||
2. **Usage notification**: If Evolution Go is used as part of any project (including closed-source), a clear notification that Evolution Go is being utilized must be visible to system administrators.
|
||||
|
||||
Please contact contato@evolution-api.com for licensing inquiries. Full license details at [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
- [whatsmeow](https://github.com/tulir/whatsmeow) by [tulir](https://github.com/tulir)
|
||||
- [Evolution API](https://github.com/EvolutionAPI/evolution-api)
|
||||
|
||||
## Telemetry
|
||||
|
||||
Evolution Go collects anonymous telemetry data (routes used, API version) to improve the service. No sensitive or personal data is collected.
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**Evolution Go** — High-Performance WhatsApp API
|
||||
|
||||
Made with ❤️ by the [Evolution Team](https://evolutionfoundation.com.br/)
|
||||
|
||||
© 2025 Evolution Foundation
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,443 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"path/filepath"
|
||||
"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/EvolutionAPI/evolution-go/pkg/call/handler"
|
||||
call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service"
|
||||
chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler"
|
||||
chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service"
|
||||
community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler"
|
||||
community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service"
|
||||
config "github.com/EvolutionAPI/evolution-go/pkg/config"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/core"
|
||||
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
|
||||
nats_producer "github.com/EvolutionAPI/evolution-go/pkg/events/nats"
|
||||
rabbitmq_producer "github.com/EvolutionAPI/evolution-go/pkg/events/rabbitmq"
|
||||
webhook_producer "github.com/EvolutionAPI/evolution-go/pkg/events/webhook"
|
||||
websocket_producer "github.com/EvolutionAPI/evolution-go/pkg/events/websocket"
|
||||
group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler"
|
||||
group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service"
|
||||
instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"
|
||||
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
|
||||
label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler"
|
||||
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
|
||||
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
|
||||
label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler"
|
||||
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
|
||||
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
|
||||
message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service"
|
||||
auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware"
|
||||
newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler"
|
||||
newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service"
|
||||
poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler"
|
||||
routes "github.com/EvolutionAPI/evolution-go/pkg/routes"
|
||||
send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler"
|
||||
send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service"
|
||||
server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler"
|
||||
storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"
|
||||
minio_storage "github.com/EvolutionAPI/evolution-go/pkg/storage/minio"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/telemetry"
|
||||
user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler"
|
||||
user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
var devMode = flag.Bool("dev", false, "Enable development mode")
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func init() {
|
||||
if version == "dev" {
|
||||
if v, err := os.ReadFile("VERSION"); err == nil {
|
||||
version = strings.TrimSpace(string(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 := make(map[string](chan bool))
|
||||
clientPointer := make(map[string]*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)
|
||||
|
||||
telemetry := telemetry.NewTelemetryService()
|
||||
|
||||
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(telemetry.TelemetryMiddleware())
|
||||
|
||||
r.Use(core.GateMiddleware(runtimeCtx))
|
||||
|
||||
// License routes (always accessible, even without license)
|
||||
core.LicenseRoutes(r, runtimeCtx)
|
||||
|
||||
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(),
|
||||
).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
|
||||
WEBHOOKFILES=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"
|
||||
WEBHOOKFILES: "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"
|
||||
WEBHOOKFILES: "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"
|
||||
WEBHOOKFILES: "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;
|
||||
+3299
File diff suppressed because it is too large.
Load diff
+3273
File diff suppressed because it is too large.
Load diff
+2134
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"
|
||||
WEBHOOKFILES: "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"
|
||||
WEBHOOKFILES: "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
|
||||
WEBHOOKFILES=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.
|
||||
|
||||
### WEBHOOKFILES
|
||||
|
||||
Envia URLs de mídia nos payloads de webhook.
|
||||
|
||||
- **Tipo**: Boolean
|
||||
- **Padrão**: `true`
|
||||
|
||||
```env
|
||||
WEBHOOKFILES=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
|
||||
WEBHOOKFILES=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
|
||||
WEBHOOKFILES=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/EvolutionAPI/evolution-go](https://github.com/EvolutionAPI/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,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": "[email protected]"
|
||||
}
|
||||
```
|
||||
|
||||
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,755 @@
|
||||
# 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": {
|
||||
"[email protected]": {
|
||||
"VerifiedName": {
|
||||
"Certificate": {...},
|
||||
"Details": {
|
||||
"Serial": 123,
|
||||
"Issuer": "WhatsApp",
|
||||
"VerifiedName": "Empresa Verificada LTDA"
|
||||
}
|
||||
},
|
||||
"Status": "Olá! Estou usando WhatsApp.",
|
||||
"PictureID": "abc123",
|
||||
"Devices": ["5511999999999.0:[email protected]"],
|
||||
"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": "[email protected]",
|
||||
"RemoteJID": "[email protected]",
|
||||
"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": "[email protected]",
|
||||
"Found": true,
|
||||
"FirstName": "João",
|
||||
"FullName": "João Silva",
|
||||
"PushName": "João",
|
||||
"BusinessName": ""
|
||||
},
|
||||
{
|
||||
"Jid": "[email protected]",
|
||||
"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": {
|
||||
"DHash": "abc123",
|
||||
"PrevDHash": "def456",
|
||||
"Modifications": [
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"Action": "block"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**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": {
|
||||
"DHash": "abc123",
|
||||
"PrevDHash": "def456",
|
||||
"Modifications": [
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"Action": "unblock"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**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": {
|
||||
"DHash": "abc123",
|
||||
"Modifications": [
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"Action": "block"
|
||||
},
|
||||
{
|
||||
"JID": "[email protected]",
|
||||
"Action": "block"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**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": "[email protected]",
|
||||
"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**
|
||||
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 |
|
||||
| `WEBHOOKFILES` | `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
|
||||
WEBHOOKFILES=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**
|
||||
@@ -0,0 +1,103 @@
|
||||
module github.com/EvolutionAPI/evolution-go
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/EvolutionAPI/evo-gate v0.1.2
|
||||
github.com/chai2010/webp v1.1.1
|
||||
github.com/gabriel-vasile/mimetype v1.4.5
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
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-00010101000000-000000000000
|
||||
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410
|
||||
golang.org/x/net v0.50.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
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.1.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.14 // 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-20260113132338-7c7de50cc741 // 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.34.0 // 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.1 // indirect
|
||||
go.mau.fi/util v0.9.6 // indirect
|
||||
golang.org/x/arch v0.10.0 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
golang.org/x/tools v0.42.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
|
||||
)
|
||||
|
||||
replace go.mau.fi/whatsmeow => ./whatsmeow-lib
|
||||
@@ -0,0 +1,283 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/EvolutionAPI/evo-gate v0.1.2 h1:ZPQ9SZ7OlajNU1pbtYqbMg1U/ZiUSKmlrYk0GHWOXkc=
|
||||
github.com/EvolutionAPI/evo-gate v0.1.2/go.mod h1:48tcAgZ0yVojqLdmLpOSyWDGqPODBYXYRSEs2yIUI/w=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
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.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
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/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
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/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.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
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.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
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.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=
|
||||
github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
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-20260113132338-7c7de50cc741 h1:KPpdlQLZcHfTMQRi6bFQ7ogNO0ltFT4PmtwTLW4W+14=
|
||||
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
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.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
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.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0=
|
||||
go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU=
|
||||
go.mau.fi/util v0.9.6 h1:2nsvxm49KhI3wrFltr0+wSUBlnQ4CMtykuELjpIU+ts=
|
||||
go.mau.fi/util v0.9.6/go.mod h1:sIJpRH7Iy5Ad1SBuxQoatxtIeErgzxCtjd/2hCMkYMI=
|
||||
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.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a h1:ovFr6Z0MNmU7nH8VaX5xqw+05ST2uO1exVfZPVqRC5o=
|
||||
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
|
||||
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.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
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.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
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.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
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.0.0-20220811171246-fbc7d0a398ab/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.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
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.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
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.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/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
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
var iC=Object.defineProperty;var lC=(t,n,r)=>n in t?iC(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r;var tb=(t,n,r)=>lC(t,typeof n!="symbol"?n+"":n,r);function cC(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 ix(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var om={exports:{}},Pi={};/**
|
||||
* @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 nb;function uC(){if(nb)return Pi;nb=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 Pi.Fragment=n,Pi.jsx=r,Pi.jsxs=r,Pi}var ab;function dC(){return ab||(ab=1,om.exports=uC()),om.exports}var p=dC(),im={exports:{}},Pe={};/**
|
||||
* @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 rb;function fC(){if(rb)return Pe;rb=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"),h=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),w=Symbol.iterator;function N(T){return T===null||typeof T!="object"?null:(T=w&&T[w]||T["@@iterator"],typeof T=="function"?T:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,C={};function A(T,Y,D){this.props=T,this.context=Y,this.refs=C,this.updater=D||E}A.prototype.isReactComponent={},A.prototype.setState=function(T,Y){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,Y,"setState")},A.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function O(){}O.prototype=A.prototype;function R(T,Y,D){this.props=T,this.context=Y,this.refs=C,this.updater=D||E}var L=R.prototype=new O;L.constructor=R,S(L,A.prototype),L.isPureReactComponent=!0;var I=Array.isArray;function ee(){}var U={H:null,A:null,T:null,S:null},Q=Object.prototype.hasOwnProperty;function le(T,Y,D){var V=D.ref;return{$$typeof:t,type:T,key:Y,ref:V!==void 0?V:null,props:D}}function ue(T,Y){return le(T.type,Y,T.props)}function me(T){return typeof T=="object"&&T!==null&&T.$$typeof===t}function re(T){var Y={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(D){return Y[D]})}var X=/\/+/g;function he(T,Y){return typeof T=="object"&&T!==null&&T.key!=null?re(""+T.key):Y.toString(36)}function be(T){switch(T.status){case"fulfilled":return T.value;case"rejected":throw T.reason;default:switch(typeof T.status=="string"?T.then(ee,ee):(T.status="pending",T.then(function(Y){T.status==="pending"&&(T.status="fulfilled",T.value=Y)},function(Y){T.status==="pending"&&(T.status="rejected",T.reason=Y)})),T.status){case"fulfilled":return T.value;case"rejected":throw T.reason}}throw T}function j(T,Y,D,V,te){var fe=typeof T;(fe==="undefined"||fe==="boolean")&&(T=null);var oe=!1;if(T===null)oe=!0;else switch(fe){case"bigint":case"string":case"number":oe=!0;break;case"object":switch(T.$$typeof){case t:case n:oe=!0;break;case v:return oe=T._init,j(oe(T._payload),Y,D,V,te)}}if(oe)return te=te(T),oe=V===""?"."+he(T,0):V,I(te)?(D="",oe!=null&&(D=oe.replace(X,"$&/")+"/"),j(te,Y,D,"",function(_e){return _e})):te!=null&&(me(te)&&(te=ue(te,D+(te.key==null||T&&T.key===te.key?"":(""+te.key).replace(X,"$&/")+"/")+oe)),Y.push(te)),1;oe=0;var K=V===""?".":V+":";if(I(T))for(var de=0;de<T.length;de++)V=T[de],fe=K+he(V,de),oe+=j(V,Y,D,fe,te);else if(de=N(T),typeof de=="function")for(T=de.call(T),de=0;!(V=T.next()).done;)V=V.value,fe=K+he(V,de++),oe+=j(V,Y,D,fe,te);else if(fe==="object"){if(typeof T.then=="function")return j(be(T),Y,D,V,te);throw Y=String(T),Error("Objects are not valid as a React child (found: "+(Y==="[object Object]"?"object with keys {"+Object.keys(T).join(", ")+"}":Y)+"). If you meant to render a collection of children, use an array instead.")}return oe}function Z(T,Y,D){if(T==null)return T;var V=[],te=0;return j(T,V,"","",function(fe){return Y.call(D,fe,te++)}),V}function P(T){if(T._status===-1){var Y=T._result;Y=Y(),Y.then(function(D){(T._status===0||T._status===-1)&&(T._status=1,T._result=D)},function(D){(T._status===0||T._status===-1)&&(T._status=2,T._result=D)}),T._status===-1&&(T._status=0,T._result=Y)}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 Y=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(Y))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",T);return}console.error(T)},we={map:Z,forEach:function(T,Y,D){Z(T,function(){Y.apply(this,arguments)},D)},count:function(T){var Y=0;return Z(T,function(){Y++}),Y},toArray:function(T){return Z(T,function(Y){return Y})||[]},only:function(T){if(!me(T))throw Error("React.Children.only expected to receive a single React element child.");return T}};return Pe.Activity=y,Pe.Children=we,Pe.Component=A,Pe.Fragment=r,Pe.Profiler=i,Pe.PureComponent=R,Pe.StrictMode=s,Pe.Suspense=g,Pe.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=U,Pe.__COMPILER_RUNTIME={__proto__:null,c:function(T){return U.H.useMemoCache(T)}},Pe.cache=function(T){return function(){return T.apply(null,arguments)}},Pe.cacheSignal=function(){return null},Pe.cloneElement=function(T,Y,D){if(T==null)throw Error("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 ob;function mC(){return ob||(ob=1,(function(t){function n(j,Z){var P=j.length;j.push(Z);e:for(;0<P;){var se=P-1>>>1,we=j[se];if(0<i(we,Z))j[se]=Z,j[P]=we,P=se;else break e}}function r(j){return j.length===0?null:j[0]}function s(j){if(j.length===0)return null;var Z=j[0],P=j.pop();if(P!==Z){j[0]=P;e:for(var se=0,we=j.length,T=we>>>1;se<T;){var Y=2*(se+1)-1,D=j[Y],V=Y+1,te=j[V];if(0>i(D,P))V<we&&0>i(te,D)?(j[se]=te,j[V]=P,se=V):(j[se]=D,j[Y]=P,se=Y);else if(V<we&&0>i(te,P))j[se]=te,j[V]=P,se=V;else break e}}return Z}function i(j,Z){var P=j.sortIndex-Z.sortIndex;return P!==0?P:j.id-Z.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=[],h=[],v=1,y=null,w=3,N=!1,E=!1,S=!1,C=!1,A=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function L(j){for(var Z=r(h);Z!==null;){if(Z.callback===null)s(h);else if(Z.startTime<=j)s(h),Z.sortIndex=Z.expirationTime,n(g,Z);else break;Z=r(h)}}function I(j){if(S=!1,L(j),!E)if(r(g)!==null)E=!0,ee||(ee=!0,re());else{var Z=r(h);Z!==null&&be(I,Z.startTime-j)}}var ee=!1,U=-1,Q=5,le=-1;function ue(){return C?!0:!(t.unstable_now()-le<Q)}function me(){if(C=!1,ee){var j=t.unstable_now();le=j;var Z=!0;try{e:{E=!1,S&&(S=!1,O(U),U=-1),N=!0;var P=w;try{t:{for(L(j),y=r(g);y!==null&&!(y.expirationTime>j&&ue());){var se=y.callback;if(typeof se=="function"){y.callback=null,w=y.priorityLevel;var we=se(y.expirationTime<=j);if(j=t.unstable_now(),typeof we=="function"){y.callback=we,L(j),Z=!0;break t}y===r(g)&&s(g),L(j)}else s(g);y=r(g)}if(y!==null)Z=!0;else{var T=r(h);T!==null&&be(I,T.startTime-j),Z=!1}}break e}finally{y=null,w=P,N=!1}Z=void 0}}finally{Z?re():ee=!1}}}var re;if(typeof R=="function")re=function(){R(me)};else if(typeof MessageChannel<"u"){var X=new MessageChannel,he=X.port2;X.port1.onmessage=me,re=function(){he.postMessage(null)}}else re=function(){A(me,0)};function be(j,Z){U=A(function(){j(t.unstable_now())},Z)}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"):Q=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 Z=3;break;default:Z=w}var P=w;w=Z;try{return j()}finally{w=P}},t.unstable_requestPaint=function(){C=!0},t.unstable_runWithPriority=function(j,Z){switch(j){case 1:case 2:case 3:case 4:case 5:break;default:j=3}var P=w;w=j;try{return Z()}finally{w=P}},t.unstable_scheduleCallback=function(j,Z,P){var se=t.unstable_now();switch(typeof P=="object"&&P!==null?(P=P.delay,P=typeof P=="number"&&0<P?se+P:se):P=se,j){case 1:var we=-1;break;case 2:we=250;break;case 5:we=1073741823;break;case 4:we=1e4;break;default:we=5e3}return we=P+we,j={id:v++,callback:Z,priorityLevel:j,startTime:P,expirationTime:we,sortIndex:-1},P>se?(j.sortIndex=P,n(h,j),r(g)===null&&j===r(h)&&(S?(O(U),U=-1):S=!0,be(I,P-se))):(j.sortIndex=we,n(g,j),E||N||(E=!0,ee||(ee=!0,re()))),j},t.unstable_shouldYield=ue,t.unstable_wrapCallback=function(j){var Z=w;return function(){var P=w;w=Z;try{return j.apply(this,arguments)}finally{w=P}}}})(um)),um}var ib;function hC(){return ib||(ib=1,cm.exports=mC()),cm.exports}var dm={exports:{}},cn={};/**
|
||||
* @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 lb;function pC(){if(lb)return cn;lb=1;var t=mh();function n(g){var h="https://react.dev/errors/"+g;if(1<arguments.length){h+="?args[]="+encodeURIComponent(arguments[1]);for(var v=2;v<arguments.length;v++)h+="&args[]="+encodeURIComponent(arguments[v])}return"Minified React error #"+g+"; visit "+h+" 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,h,v){var y=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:y==null?null:""+y,children:g,containerInfo:h,implementation:v}}var u=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function f(g,h){if(g==="font")return"";if(typeof h=="string")return h==="use-credentials"?h:""}return cn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,cn.createPortal=function(g,h){var v=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)throw Error(n(299));return c(g,h,null,v)},cn.flushSync=function(g){var h=u.T,v=s.p;try{if(u.T=null,s.p=2,g)return g()}finally{u.T=h,s.p=v,s.d.f()}},cn.preconnect=function(g,h){typeof g=="string"&&(h?(h=h.crossOrigin,h=typeof h=="string"?h==="use-credentials"?h:"":void 0):h=null,s.d.C(g,h))},cn.prefetchDNS=function(g){typeof g=="string"&&s.d.D(g)},cn.preinit=function(g,h){if(typeof g=="string"&&h&&typeof h.as=="string"){var v=h.as,y=f(v,h.crossOrigin),w=typeof h.integrity=="string"?h.integrity:void 0,N=typeof h.fetchPriority=="string"?h.fetchPriority:void 0;v==="style"?s.d.S(g,typeof h.precedence=="string"?h.precedence:void 0,{crossOrigin:y,integrity:w,fetchPriority:N}):v==="script"&&s.d.X(g,{crossOrigin:y,integrity:w,fetchPriority:N,nonce:typeof h.nonce=="string"?h.nonce:void 0})}},cn.preinitModule=function(g,h){if(typeof g=="string")if(typeof h=="object"&&h!==null){if(h.as==null||h.as==="script"){var v=f(h.as,h.crossOrigin);s.d.M(g,{crossOrigin:v,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0})}}else h==null&&s.d.M(g)},cn.preload=function(g,h){if(typeof g=="string"&&typeof h=="object"&&h!==null&&typeof h.as=="string"){var v=h.as,y=f(v,h.crossOrigin);s.d.L(g,v,{crossOrigin:y,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0,type:typeof h.type=="string"?h.type:void 0,fetchPriority:typeof h.fetchPriority=="string"?h.fetchPriority:void 0,referrerPolicy:typeof h.referrerPolicy=="string"?h.referrerPolicy:void 0,imageSrcSet:typeof h.imageSrcSet=="string"?h.imageSrcSet:void 0,imageSizes:typeof h.imageSizes=="string"?h.imageSizes:void 0,media:typeof h.media=="string"?h.media:void 0})}},cn.preloadModule=function(g,h){if(typeof g=="string")if(h){var v=f(h.as,h.crossOrigin);s.d.m(g,{as:typeof h.as=="string"&&h.as!=="script"?h.as:void 0,crossOrigin:v,integrity:typeof h.integrity=="string"?h.integrity:void 0})}else s.d.m(g)},cn.requestFormReset=function(g){s.d.r(g)},cn.unstable_batchedUpdates=function(g,h){return g(h)},cn.useFormState=function(g,h,v){return u.H.useFormState(g,h,v)},cn.useFormStatus=function(){return u.H.useHostTransitionStatus()},cn.version="19.2.0",cn}var cb;function lx(){if(cb)return dm.exports;cb=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(),dm.exports=pC(),dm.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 ub;function gC(){if(ub)return Hi;ub=1;var t=hC(),n=mh(),r=lx();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 h(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 m=d.alternate;if(m===null){if(l=d.return,l!==null){o=l;continue}break}if(d.child===m.child){for(m=d.child;m;){if(m===o)return g(d),e;if(m===l)return g(d),a;m=m.sibling}throw Error(s(188))}if(o.return!==l.return)o=d,l=m;else{for(var x=!1,_=d.child;_;){if(_===o){x=!0,o=d,l=m;break}if(_===l){x=!0,l=d,o=m;break}_=_.sibling}if(!x){for(_=m.child;_;){if(_===o){x=!0,o=m,l=d;break}if(_===l){x=!0,l=m,o=d;break}_=_.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"),N=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),C=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),O=Symbol.for("react.consumer"),R=Symbol.for("react.context"),L=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),ee=Symbol.for("react.suspense_list"),U=Symbol.for("react.memo"),Q=Symbol.for("react.lazy"),le=Symbol.for("react.activity"),ue=Symbol.for("react.memo_cache_sentinel"),me=Symbol.iterator;function re(e){return e===null||typeof e!="object"?null:(e=me&&e[me]||e["@@iterator"],typeof e=="function"?e:null)}var X=Symbol.for("react.client.reference");function he(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===X?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case S:return"Fragment";case A:return"Profiler";case C:return"StrictMode";case I:return"Suspense";case ee:return"SuspenseList";case le:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case E:return"Portal";case R:return e.displayName||"Context";case O:return(e._context.displayName||"Context")+".Consumer";case L: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:he(e.type)||"Memo";case Q:a=e._payload,e=e._init;try{return he(e(a))}catch{}}return null}var be=Array.isArray,j=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Z=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,P={pending:!1,data:null,method:null,action:null},se=[],we=-1;function T(e){return{current:e}}function Y(e){0>we||(e.current=se[we],se[we]=null,we--)}function D(e,a){we++,se[we]=e.current,e.current=a}var V=T(null),te=T(null),fe=T(null),oe=T(null);function K(e,a){switch(D(fe,a),D(te,e),D(V,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?_v(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=_v(a),e=Cv(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Y(V),D(V,e)}function de(){Y(V),Y(te),Y(fe)}function _e(e){e.memoizedState!==null&&D(oe,e);var a=V.current,o=Cv(a,e.type);a!==o&&(D(te,e),D(V,o))}function rt(e){te.current===e&&(Y(V),Y(te)),oe.current===e&&(Y(oe),zi._currentValue=P)}var De,Le;function xe(e){if(De===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);De=a&&a[1]||"",Le=-1<o.stack.indexOf(`
|
||||
at`)?" (<anonymous>)":-1<o.stack.indexOf("@")?"@unknown:0:0":""}return`
|
||||
`+De+e+Le}var je=!1;function at(e,a){if(!e||je)return"";je=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(a){var ce=function(){throw Error()};if(Object.defineProperty(ce.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ce,[])}catch(J){var G=J}Reflect.construct(e,[],ce)}else{try{ce.call()}catch(J){G=J}e.call(ce.prototype)}}else{try{throw Error()}catch(J){G=J}(ce=e())&&typeof ce.catch=="function"&&ce.catch(function(){})}}catch(J){if(J&&G&&typeof J.stack=="string")return[J.stack,G.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 m=l.DetermineComponentFrameRoot(),x=m[0],_=m[1];if(x&&_){var M=x.split(`
|
||||
`),F=_.split(`
|
||||
`);for(d=l=0;l<M.length&&!M[l].includes("DetermineComponentFrameRoot");)l++;for(;d<F.length&&!F[d].includes("DetermineComponentFrameRoot");)d++;if(l===M.length||d===F.length)for(l=M.length-1,d=F.length-1;1<=l&&0<=d&&M[l]!==F[d];)d--;for(;1<=l&&0<=d;l--,d--)if(M[l]!==F[d]){if(l!==1||d!==1)do if(l--,d--,0>d||M[l]!==F[d]){var ne=`
|
||||
`+M[l].replace(" at new "," at ");return e.displayName&&ne.includes("<anonymous>")&&(ne=ne.replace("<anonymous>",e.displayName)),ne}while(1<=l&&0<=d);break}}}finally{je=!1,Error.prepareStackTrace=o}return(o=e?e.displayName||e.name:"")?xe(o):""}function pt(e,a){switch(e.tag){case 26:case 27:case 5:return xe(e.type);case 16:return xe("Lazy");case 13:return e.child!==a&&a!==null?xe("Suspense Fallback"):xe("Suspense");case 19:return xe("SuspenseList");case 0:case 15:return at(e.type,!1);case 11:return at(e.type.render,!1);case 1:return at(e.type,!0);case 31:return xe("Activity");default:return""}}function Je(e){try{var a="",o=null;do a+=pt(e,o),o=e,e=e.return;while(e);return a}catch(l){return`
|
||||
Error generating stack: `+l.message+`
|
||||
`+l.stack}}var Ue=Object.prototype.hasOwnProperty,k=t.unstable_scheduleCallback,H=t.unstable_cancelCallback,$=t.unstable_shouldYield,ye=t.unstable_requestPaint,pe=t.unstable_now,ge=t.unstable_getCurrentPriorityLevel,Se=t.unstable_ImmediatePriority,qe=t.unstable_UserBlockingPriority,Xe=t.unstable_NormalPriority,Ot=t.unstable_LowPriority,on=t.unstable_IdlePriority,dn=t.log,Fn=t.unstable_setDisableYieldValue,Ft=null,Nt=null;function fn(e){if(typeof dn=="function"&&Fn(e),Nt&&typeof Nt.setStrictMode=="function")try{Nt.setStrictMode(Ft,e)}catch{}}var $t=Math.clz32?Math.clz32:ya,Xo=Math.log,cr=Math.LN2;function ya(e){return e>>>=0,e===0?32:31-(Xo(e)/cr|0)|0}var As=256,Rs=262144,Xr=4194304;function va(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 Be(e,a,o){var l=e.pendingLanes;if(l===0)return 0;var d=0,m=e.suspendedLanes,x=e.pingedLanes;e=e.warmLanes;var _=l&134217727;return _!==0?(l=_&~m,l!==0?d=va(l):(x&=_,x!==0?d=va(x):o||(o=_&~e,o!==0&&(d=va(o))))):(_=l&~m,_!==0?d=va(_):x!==0?d=va(x):o||(o=l&~e,o!==0&&(d=va(o)))),d===0?0:a!==0&&a!==d&&(a&m)===0&&(m=d&-d,o=a&-a,m>=o||m===32&&(o&4194048)!==0)?a:d}function Et(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function Kt(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 ln(){var e=Xr;return Xr<<=1,(Xr&62914560)===0&&(Xr=4194304),e}function ur(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 gn(e,a,o,l,d,m){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 _=e.entanglements,M=e.expirationTimes,F=e.hiddenUpdates;for(o=x&~o;0<o;){var ne=31-$t(o),ce=1<<ne;_[ne]=0,M[ne]=-1;var G=F[ne];if(G!==null)for(F[ne]=null,ne=0;ne<G.length;ne++){var J=G[ne];J!==null&&(J.lane&=-536870913)}o&=~ce}l!==0&&Kr(e,l,0),m!==0&&d===0&&e.tag!==0&&(e.suspendedLanes|=m&~(x&~a))}function Kr(e,a,o){e.pendingLanes|=a,e.suspendedLanes&=~a;var l=31-$t(a);e.entangledLanes|=a,e.entanglements[l]=e.entanglements[l]|1073741824|o&261930}function yn(e,a){var o=e.entangledLanes|=a;for(e=e.entanglements;o;){var l=31-$t(o),d=1<<l;d&a|e[l]&a&&(e[l]|=a),o&=~d}}function vn(e,a){var o=a&-a;return o=(o&42)!==0?1:Ts(o),(o&(e.suspendedLanes|a))!==0?0:o}function Ts(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 sa(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Xu(){var e=Z.p;return e!==0?e:(e=window.event,e===void 0?32:Zv(e.type))}function up(e,a){var o=Z.p;try{return Z.p=e,a()}finally{Z.p=o}}var dr=Math.random().toString(36).slice(2),en="__reactFiber$"+dr,bn="__reactProps$"+dr,js="__reactContainer$"+dr,Ku="__reactEvents$"+dr,KS="__reactListeners$"+dr,QS="__reactHandles$"+dr,dp="__reactResources$"+dr,Ko="__reactMarker$"+dr;function Qu(e){delete e[en],delete e[bn],delete e[Ku],delete e[KS],delete e[QS]}function Os(e){var a=e[en];if(a)return a;for(var o=e.parentNode;o;){if(a=o[js]||o[en]){if(o=a.alternate,a.child!==null||o!==null&&o.child!==null)for(e=kv(e);e!==null;){if(o=e[en])return o;e=kv(e)}return a}e=o,o=e.parentNode}return null}function ks(e){if(e=e[en]||e[js]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function Qo(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(s(33))}function Ms(e){var a=e[dp];return a||(a=e[dp]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function Qt(e){e[Ko]=!0}var fp=new Set,mp={};function Qr(e,a){Ds(e,a),Ds(e+"Capture",a)}function Ds(e,a){for(mp[e]=a,e=0;e<a.length;e++)fp.add(a[e])}var WS=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2
Line truncated
|
||||
`).replace(T_,"")}function Sv(e,a){return a=wv(a),wv(e)===a}function yt(e,a,o,l,d,m){switch(o){case"children":typeof l=="string"?a==="body"||a==="textarea"&&l===""||Ls(e,l):(typeof l=="number"||typeof l=="bigint")&&a!=="body"&&Ls(e,""+l);break;case"className":bl(e,"class",l);break;case"tabIndex":bl(e,"tabindex",l);break;case"dir":case"role":case"viewBox":case"width":case"height":bl(e,o,l);break;case"style":Sp(e,l,m);break;case"data":if(a!=="object"){bl(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=wl(""+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 m=="function"&&(o==="formAction"?(a!=="input"&&yt(e,a,"name",d.name,d,null),yt(e,a,"formEncType",d.formEncType,d,null),yt(e,a,"formMethod",d.formMethod,d,null),yt(e,a,"formTarget",d.formTarget,d,null)):(yt(e,a,"encType",d.encType,d,null),yt(e,a,"method",d.method,d,null),yt(e,a,"target",d.target,d,null)));if(l==null||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=wl(""+l),e.setAttribute(o,l);break;case"onClick":l!=null&&(e.onclick=La);break;case"onScroll":l!=null&&Qe("scroll",e);break;case"onScrollEnd":l!=null&&Qe("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=wl(""+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":Qe("beforetoggle",e),Qe("toggle",e),vl(e,"popover",l);break;case"xlinkActuate":za(e,"http://www.w3.org/1999/xlink","xlink:actuate",l);break;case"xlinkArcrole":za(e,"http://www.w3.org/1999/xlink","xlink:arcrole",l);break;case"xlinkRole":za(e,"http://www.w3.org/1999/xlink","xlink:role",l);break;case"xlinkShow":za(e,"http://www.w3.org/1999/xlink","xlink:show",l);break;case"xlinkTitle":za(e,"http://www.w3.org/1999/xlink","xlink:title",l);break;case"xlinkType":za(e,"http://www.w3.org/1999/xlink","xlink:type",l);break;case"xmlBase":za(e,"http://www.w3.org/XML/1998/namespace","xml:base",l);break;case"xmlLang":za(e,"http://www.w3.org/XML/1998/namespace","xml:lang",l);break;case"xmlSpace":za(e,"http://www.w3.org/XML/1998/namespace","xml:space",l);break;case"is":vl(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=aE.get(o)||o,vl(e,o,l))}}function If(e,a,o,l,d,m){switch(o){case"style":Sp(e,l,m);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"?Ls(e,l):(typeof l=="number"||typeof l=="bigint")&&Ls(e,""+l);break;case"onScroll":l!=null&&Qe("scroll",e);break;case"onScrollEnd":l!=null&&Qe("scrollend",e);break;case"onClick":l!=null&&(e.onclick=La);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne
Line truncated
|
||||
* react-router v7.9.5
|
||||
*
|
||||
* 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 fb="popstate";function bC(t={}){function n(s,i){let{pathname:c,search:u,hash:f}=s.location;return Um("",{pathname:c,search:u,hash:f},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function r(s,i){return typeof i=="string"?i:Wi(i)}return wC(n,r,null,t)}function Ct(t,n){if(t===!1||t===null||typeof t>"u")throw new Error(n)}function da(t,n){if(!t){typeof console<"u"&&console.warn(n);try{throw new Error(n)}catch{}}}function xC(){return Math.random().toString(36).substring(2,10)}function mb(t,n){return{usr:t.state,key:t.key,idx:n}}function Um(t,n,r=null,s){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof n=="string"?Bo(n):n,state:r,key:n&&n.key||s||xC()}}function Wi({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 Bo(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 wC(t,n,r,s={}){let{window:i=document.defaultView,v5Compat:c=!1}=s,u=i.history,f="POP",g=null,h=v();h==null&&(h=0,u.replaceState({...u.state,idx:h},""));function v(){return(u.state||{idx:null}).idx}function y(){f="POP";let C=v(),A=C==null?null:C-h;h=C,g&&g({action:f,location:S.location,delta:A})}function w(C,A){f="PUSH";let O=Um(S.location,C,A);h=v()+1;let R=mb(O,h),L=S.createHref(O);try{u.pushState(R,"",L)}catch(I){if(I instanceof DOMException&&I.name==="DataCloneError")throw I;i.location.assign(L)}c&&g&&g({action:f,location:S.location,delta:1})}function N(C,A){f="REPLACE";let O=Um(S.location,C,A);h=v();let R=mb(O,h),L=S.createHref(O);u.replaceState(R,"",L),c&&g&&g({action:f,location:S.location,delta:0})}function E(C){return SC(C)}let S={get action(){return f},get location(){return t(i,u)},listen(C){if(g)throw new Error("A history only accepts one active listener");return i.addEventListener(fb,y),g=C,()=>{i.removeEventListener(fb,y),g=null}},createHref(C){return n(i,C)},createURL:E,encodeLocation(C){let A=E(C);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:w,replace:N,go(C){return u.go(C)}};return S}function SC(t,n=!1){let r="http://localhost";typeof window<"u"&&(r=window.location.origin!=="null"?window.location.origin:window.location.href),Ct(r,"No window.location.(origin|href) available to create URL");let s=typeof t=="string"?t:Wi(t);return s=s.replace(/ $/,"%20"),!n&&s.startsWith("//")&&(s=r+s),new URL(s,r)}function cx(t,n,r="/"){return EC(t,n,r,!1)}function EC(t,n,r,s){let i=typeof n=="string"?Bo(n):n,c=ar(i.pathname||"/",r);if(c==null)return null;let u=ux(t);_C(u);let f=null;for(let g=0;f==null&&g<u.length;++g){let h=zC(c);f=MC(u[g],h,s)}return f}function ux(t,n=[],r=[],s="",i=!1){let c=(u,f,g=i,h)=>{let v={relativePath:h===void 0?u.path||"":h,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(v.relativePath.startsWith("/")){if(!v.relativePath.startsWith(s)&&g)return;Ct(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=nr([s,v.relativePath]),w=r.concat(v);u.children&&u.children.length>0&&(Ct(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${y}".`),ux(u.children,n,w,y,g)),!(u.path==null&&!u.index)&&n.push({path:y,score:OC(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 h of dx(u.path))c(u,f,!0,h)}),n}function dx(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=dx(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 _C(t){t.sort((n,r)=>n.score!==r.score?r.score-n.score:kC(n.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}var CC=/^:[\w-]+$/,NC=3,AC=2,RC=1,TC=10,jC=-2,hb=t=>t==="*";function OC(t,n){let r=t.split("/"),s=r.length;return r.some(hb)&&(s+=jC),n&&(s+=AC),r.filter(i=>!hb(i)).reduce((i,c)=>i+(CC.test(c)?NC:c===""?RC:TC),s)}function kC(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 MC(t,n,r=!1){let{routesMeta:s}=t,i={},c="/",u=[];for(let f=0;f<s.length;++f){let g=s[f],h=f===s.length-1,v=c==="/"?n:n.slice(c.length)||"/",y=Wc({path:g.relativePath,caseSensitive:g.caseSensitive,end:h},v),w=g.route;if(!y&&h&&r&&!s[s.length-1].route.index&&(y=Wc({path:g.relativePath,caseSensitive:g.caseSensitive,end:!1},v)),!y)return null;Object.assign(i,y.params),u.push({params:i,pathname:nr([c,y.pathname]),pathnameBase:PC(nr([c,y.pathnameBase])),route:w}),y.pathnameBase!=="/"&&(c=nr([c,y.pathnameBase]))}return u}function Wc(t,n){typeof t=="string"&&(t={path
Line truncated
|
||||
|
||||
Please change the parent <Route path="${R}"> to <Route path="${R==="/"?"*":`${R}/*`}">.`)}let w=Yr(),N;if(n){let R=typeof n=="string"?Bo(n):n;Ct(v==="/"||((O=R.pathname)==null?void 0:O.startsWith(v)),`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 "${v}" but pathname "${R.pathname}" was given in the \`location\` prop.`),N=R}else N=w;let E=N.pathname||"/",S=E;if(v!=="/"){let R=v.replace(/^\//,"").split("/");S="/"+E.replace(/^\//,"").split("/").slice(R.length).join("/")}let C=cx(t,{pathname:S});da(y||C!=null,`No routes matched location "${N.pathname}${N.search}${N.hash}" `),da(C==null||C[C.length-1].route.element!==void 0||C[C.length-1].route.Component!==void 0||C[C.length-1].route.lazy!==void 0,`Matched leaf route at location "${N.pathname}${N.search}${N.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 A=n2(C&&C.map(R=>Object.assign({},R,{params:Object.assign({},g,R.params),pathname:nr([v,c.encodeLocation?c.encodeLocation(R.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?v:nr([v,c.encodeLocation?c.encodeLocation(R.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathnameBase])})),u,r,s,i);return n&&A?b.createElement(il.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...N},navigationType:"POP"}},A):A}function WC(){let t=i2(),n=IC(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 JC=b.createElement(WC,null),e2=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.unstable_onError?this.props.unstable_onError(t,n):console.error("React Router caught the following error during render",t)}render(){return this.state.error!==void 0?b.createElement(aa.Provider,{value:this.props.routeContext},b.createElement(gh.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function t2({routeContext:t,match:n,children:r}){let s=b.useContext(Po);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),b.createElement(aa.Provider,{value:t},r)}function n2(t,n=[],r=null,s=null,i=null){if(t==null){if(!r)return null;if(r.errors)t=r.matches;else if(n.length===0&&!r.initialized&&r.matches.length>0)t=r.matches;else return null}let c=t,u=r==null?void 0:r.errors;if(u!=null){let h=c.findIndex(v=>v.route.id&&(u==null?void 0:u[v.route.id])!==void 0);Ct(h>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(u).join(",")}`),c=c.slice(0,Math.min(c.length,h+1))}let f=!1,g=-1;if(r)for(let h=0;h<c.length;h++){let v=c[h];if((v.route.HydrateFallback||v.route.hydrateFallbackElement)&&(g=h),v.route.id){let{loaderData:y,errors:w}=r,N=v.route.loader&&!y.hasOwnProperty(v.route.id)&&(!w||w[v.route.id]===void 0);if(v.route.lazy||N){f=!0,g>=0?c=c.slice(0,g+1):c=[c[0]];break}}}return c.reduceRight((h,v,y)=>{let w,N=!1,E=null,S=null;r&&(w=u&&v.route.id?u[v.route.id]:void 0,E=v.route.errorElement||JC,f&&(g<0&&y===0?(yx("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),N=!0,S=null):g===y&&(N=!0,S=v.route.hydrateFallbackElement||null)));let C=n.concat(c.slice(0,y+1)),A=()=>{let O;return w?O=E:N?O=S:v.route.Component?O=b.createElement(v.route.Component,null):v.route.element?O=v.route.element:O=h,b.createElement(t2,{match:v,routeContext:{outlet:h,matches:C,isDataRoute:r!=null},children:O})};return r&&(v.route.ErrorBoundary||v.route.errorElement||y===0)?b.createElement(e2,{location:r.loLine 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 yN=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),vN=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),bb=t=>{const n=vN(t);return n.charAt(0).toUpperCase()+n.slice(1)},Nx=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),bN=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 xN={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 wN=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,...xN,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:Nx("lucide",i),...!c&&!bN(f)&&{"aria-hidden":"true"},...f},[...u.map(([h,v])=>b.createElement(h,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 ot=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(wN,{ref:c,iconNode:n,className:Nx(`lucide-${yN(bb(t))}`,`lucide-${t}`,s),...i}));return r.displayName=bb(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 SN=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],xb=ot("arrow-left",SN);/**
|
||||
* @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 EN=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],_N=ot("arrow-right",EN);/**
|
||||
* @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 CN=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Hm=ot("chevron-down",CN);/**
|
||||
* @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 NN=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],wb=ot("chevron-right",NN);/**
|
||||
* @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 AN=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],RN=ot("chevron-up",AN);/**
|
||||
* @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 TN=[["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"}]],jN=ot("circle-alert",TN);/**
|
||||
* @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 ON=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Sb=ot("circle-check",ON);/**
|
||||
* @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 kN=[["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"}]],MN=ot("ellipsis-vertical",kN);/**
|
||||
* @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 DN=[["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"}]],zN=ot("eye-off",DN);/**
|
||||
* @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 LN=[["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"}]],UN=ot("eye",LN);/**
|
||||
* @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 BN=[["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"}]],PN=ot("funnel",BN);/**
|
||||
* @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 HN=[["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"}]],VN=ot("globe",HN);/**
|
||||
* @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 IN=[["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"}]],qN=ot("layers",IN);/**
|
||||
* @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 FN=[["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"}]],$N=ot("layout-dashboard",FN);/**
|
||||
* @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 GN=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],YN=ot("loader-circle",GN);/**
|
||||
* @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 ZN=[["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"}]],XN=ot("log-out",ZN);/**
|
||||
* @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 KN=[["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"}]],QN=ot("message-square",KN);/**
|
||||
* @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 WN=[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]],JN=ot("moon",WN);/**
|
||||
* @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=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Vm=ot("plus",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:"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"}]],nA=ot("power-off",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:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],Ax=ot("power",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=[["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"}]],Eb=ot("qr-code",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:"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"}]],_b=ot("refresh-cw",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:"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"}]],Cb=ot("save",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 iA=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],lA=ot("search",iA);/**
|
||||
* @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 cA=[["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"}]],uA=ot("settings",cA);/**
|
||||
* @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 dA=[["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"}]],fA=ot("shield",dA);/**
|
||||
* @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 mA=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],hA=ot("smartphone",mA);/**
|
||||
* @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 pA=[["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"}]],gA=ot("sun",pA);/**
|
||||
* @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 yA=[["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"}]],Sh=ot("trash-2",yA);/**
|
||||
* @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:"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"}]],bA=ot("triangle-alert",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 xA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ji=ot("x",xA);/**
|
||||
* @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:"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"}]],SA=ot("zap",wA);class EA extends b.Component{constructor(r){super(r);tb(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:p.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-50 px-4",children:p.jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-8 shadow-lg",children:[p.jsx("div",{className:"mb-4 flex items-center justify-center",children:p.jsx("div",{className:"rounded-full bg-red-100 p-3",children:p.jsx(bA,{className:"h-8 w-8 text-red-600"})})}),p.jsx("h1",{className:"mb-2 text-center text-2xl font-bold text-gray-900",children:"Algo deu errado"}),p.jsx("p",{className:"mb-6 text-center text-gray-600",children:"Ocorreu um erro inesperado na aplicação."}),this.state.error&&p.jsxs("div",{className:"mb-6 rounded-md bg-red-50 p-4",children:[p.jsx("p",{className:"text-sm font-medium text-red-800",children:this.state.error.message}),!1]}),p.jsxs("div",{className:"flex gap-3",children:[p.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"}),p.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 Rx(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=Rx(t[n]))&&(s&&(s+=" "),s+=r)}else for(r in t)t[r]&&(s&&(s+=" "),s+=r);return s}function Eh(){for(var t,n,r=0,s="",i=arguments.length;r<i;r++)(t=arguments[r])&&(n=Rx(t))&&(s&&(s+=" "),s+=n);return s}const _A=(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},CA=(t,n)=>({classGroupId:t,validator:n}),Tx=(t=new Map,n=null,r)=>({nextPart:t,validators:n,classGroupId:r}),Jc="-",Nb=[],NA="arbitrary..",AA=t=>{const n=TA(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=t;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return RA(u);const f=u.split(Jc),g=f[0]===""&&f.length>1?1:0;return jx(f,g,n)},getConflictingClassGroupIds:(u,f)=>{if(f){const g=s[u],h=r[u];return g?h?_A(h,g):g:h||Nb}return r[u]||Nb}}},jx=(t,n,r)=>{if(t.length-n===0)return r.classGroupId;const i=t[n],c=r.nextPart.get(i);if(c){const h=jx(t,n+1,c);if(h)return h}const u=r.validators;if(u===null)return;const f=n===0?t.join(Jc):t.slice(n).join(Jc),g=u.length;for(let h=0;h<g;h++){const v=u[h];if(v.validator(f))return v.classGroupId}},RA=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?NA+s:void 0})(),TA=t=>{const{theme:n,classGroups:r}=t;return jA(r,n)},jA=(t,n)=>{const r=Tx();for(const s in t){const i=t[s];_h(i,r,s,n)}return r},_h=(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"){kA(t,n,r);return}if(typeof t=="function"){MA(t,n,r,s);return}DA(t,n,r,s)},kA=(t,n,r)=>{const s=t===""?n:Ox(n,t);s.classGroupId=r},MA=(t,n,r,s)=>{if(zA(t)){_h(t(s),n,r,s);return}n.validators===null&&(n.validators=[]),n.validators.push(CA(r,t))},DA=(t,n,r,s)=>{const i=Object.entries(t),c=i.length;for(let u=0;u<c;u++){const[f,g]=i[u];_h(g,Ox(n,f),r,s)}},Ox=(t,n)=>{let r=t;const s=n.split(Jc),i=s.length;for(let c=0;c<i;c++){const u=s[c];let f=r.nextPart.get(u);f||(f=Tx(),r.nextPart.set(u,f)),r=f}return r},zA=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,LA=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)}}},Im="!",Ab=":",UA=[],Rb=(t,n,r,s,i)=>({modifiers:t,hasImportantModifier:n,baseClassName:r,maybePostfixModifierPosition:s,isExternal:i}),BA=t=>{const{prefix:n,experimentalParseClassName:r}=t;let s=i=>{const c=[];let u=0,f=0,g=0,h;const v=i.length;for(let S=0;S<v;S++){const C=i[S];if(u===0&&f===0){if(C===Ab){c.push(i.slice(g,S)),g=S+1;continue}if(C==="/"){h=S;continue}}C==="["?u++:C==="]"?u--:C==="("?f++:C===")"&&f--}const y=c.length===0?i:i.slice(g);let w=y,N=!1;y.endsWith(ILine truncated
|
||||
`).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),s=u.substring(i+1).trim(),!(!r||n[r]&&wT[r])&&(r==="set-cookie"?n[r]?n[r].push(s):n[r]=[s]:n[r]=n[r]?n[r]+", "+s:s)}),n},Lb=Symbol("internals");function qi(t){return t&&String(t).trim().toLowerCase()}function Yc(t){return t===!1||t==null?t:W.isArray(t)?t.map(Yc):String(t)}function ET(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 _T=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ym(t,n,r,s,i){if(W.isFunction(s))return s.call(this,n,r);if(i&&(n=r),!!W.isString(n)){if(W.isString(s))return n.indexOf(s)!==-1;if(W.isRegExp(s))return s.test(n)}}function CT(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(n,r,s)=>r.toUpperCase()+s)}function NT(t,n){const r=W.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 Tn=class{constructor(n){n&&this.set(n)}set(n,r,s){const i=this;function c(f,g,h){const v=qi(g);if(!v)throw new Error("header name must be a non-empty string");const y=W.findKey(i,v);(!y||i[y]===void 0||h===!0||h===void 0&&i[y]!==!1)&&(i[y||g]=Yc(f))}const u=(f,g)=>W.forEach(f,(h,v)=>c(h,v,g));if(W.isPlainObject(n)||n instanceof this.constructor)u(n,r);else if(W.isString(n)&&(n=n.trim())&&!_T(n))u(ST(n),r);else if(W.isObject(n)&&W.isIterable(n)){let f={},g,h;for(const v of n){if(!W.isArray(v))throw TypeError("Object iterator must return a key-value pair");f[h=v[0]]=(g=f[h])?W.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=qi(n),n){const s=W.findKey(this,n);if(s){const i=this[s];if(!r)return i;if(r===!0)return ET(i);if(W.isFunction(r))return r.call(this,i,s);if(W.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(n,r){if(n=qi(n),n){const s=W.findKey(this,n);return!!(s&&this[s]!==void 0&&(!r||ym(this,this[s],s,r)))}return!1}delete(n,r){const s=this;let i=!1;function c(u){if(u=qi(u),u){const f=W.findKey(s,u);f&&(!r||ym(s,s[f],f,r))&&(delete s[f],i=!0)}}return W.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||ym(this,this[c],c,n,!0))&&(delete this[c],i=!0)}return i}normalize(n){const r=this,s={};return W.forEach(this,(i,c)=>{const u=W.findKey(s,c);if(u){r[u]=Yc(i),delete r[c];return}const f=n?CT(c):String(c).trim();f!==c&&delete r[c],r[f]=Yc(i),s[f]=!0}),this}concat(...n){return this.constructor.concat(this,...n)}toJSON(n){const r=Object.create(null);return W.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=n&&W.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[Lb]=this[Lb]={accessors:{}}).accessors,i=this.prototype;function c(u){const f=qi(u);s[f]||(NT(i,u),s[f]=!0)}return W.isArray(n)?n.forEach(c):c(n),this}};Tn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);W.reduceDescriptors(Tn.prototype,({value:t},n)=>{let r=n[0].toUpperCase()+n.slice(1);return{get:()=>t,set(s){this[r]=s}}});W.freezeMethods(Tn);function vm(t,n){const r=this||fl,s=n||r,i=Tn.from(s.headers);let c=s.data;return W.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__)}function $o(t,n,r){$e.call(this,t??"canceled",$e.ERR_CANCELED,n,r),this.name="CanceledError"}W.inherits($o,$e,{__CANCEL__:!0});function s1(t,n,r){const s=r.config.validateStatus;!r.status||!s||s(r.status)?t(r):n(new $e("Request failed with status code "+r.status,[$e.ERR_BAD_REQUEST,$e.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function AT(t){const n=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return n&&n[1]||""}function RT(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 h=Date.now(),v=s[c];u||(u=h),r[i]=g,s[i]=h;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),h-u<n)return;const N=v&&h-v;return N?Math.round(w*1e3/N):void 0}}function TT(t,n){let r=0,s=1e3/n,i,c;const u=(h,v=Date.now())=>{r=v,i=null,c&&(clearTimeout(c),c=null),t(...h)};return[(...h)=>{const v=Date.now(),y=v-r;y>=s?u(h,v):(i=h,c||(c=setTimeout(()=>{c=null,u(i)},s-y)))},()=>i&&u(i)]}const eu=(t,n,r=3)=>{let s=0;const i=RT(50,250);return TT(c=>{const u=c.loaded,f=c.lengthComputable?c.total:void 0,g=u-s,h=i(g),v=u<=f;s=u;const y={loaded:u,total:f,progress:f?u/f:void 0,bytes:g,rate:h||void 0,estimated:h&&f&&v?(f-u)/h:void 0,event:c,lengthComputable:f!=null,[n?"download":"upload"]:!0};t(y)},r)},Ub=(t,n)=>{const r=t!=null;return[s=>n[0]({lengthComputable:r,total:t,loaded:s}),n[1]]},Bb=t=>(...n)=>W.asap(()=>t(...n)),jT=un.hasStandardBrowserEnv?((t,n)=>r=>(r=new URL(r,un.origin),t.protocol===r.protocol&&t.host===r.host&&(n||t.port===r.port)))(new URL(un.origin),un.navigator&&/(msie|trident)/i.test(un.navigator.userAgent)):()=>!0,OT=un.hasStandardBrowserEnv?{write(t,n,r,s,i,c,u){if(typeof document>"u")return;const f=[`${t}=${encodeURIComponent(n)}`];W.isNumber(r)&&f.push(`expires=${new Date(r).toUTCString()}`),W.isString(s)&&f.push(`path=${s}`),W.isString(i)&&f.push(`domain=${i}`),c===!0&&f.push("secure"),W.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 kT(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function MT(t,n){return n?t.replace(/\/?\/$/,"")+"/"+n.replace(/^\/+/,""):t}function o1(t,n,r){let s=!kT(n);return t&&(s||r==!1)?MT(t,n):n}const Pb=t=>t instanceof Tn?{...t}:t;function bs(t,n){n=n||{};const r={};function s(h,v,y,w){return W.isPlainObject(h)&&W.isPlainObject(v)?W.merge.call({caseless:w},h,v):W.isPlainObject(v)?W.merge({},v):W.isArray(v)?v.slice():v}function i(h,v,y,w){if(W.isUndefined(v)){if(!W.isUndefined(h))return s(void 0,h,y,w)}else return s(h,v,y,w)}function c(h,v){if(!W.isUndefined(v))return s(void 0,v)}function u(h,v){if(W.isUndefined(v)){if(!W.isUndefined(h))return s(void 0,h)}else return s(void 0,v)}function f(h,v,y){if(y in n)return s(h,v);if(y in t)return s(void 0,h)}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:(h,v,y)=>i(Pb(h),Pb(v),y,!0)};return W.forEach(Object.keys({...t,...n}),function(v){const y=g[v]||i,w=y(t[v],n[v],v);W.isUndefined(w)&&y!==f||(r[v]=w)}),r}const i1=t=>{const n=bs({},t);let{data:r,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:c,headers:u,auth:f}=n;if(n.headers=u=Tn.from(u),n.url=t1(o1(n.baseURL,n.url,n.allowAbsoluteUrls),t.params,t.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):""))),W.isFormData(r)){if(un.hasStandardBrowserEnv||un.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if(W.isFunction(r.getHeaders)){const g=r.getHeaders(),h=["content-type","content-length"];Object.entries(g).forEach(([v,y])=>{h.inclu
Line truncated
|
||||
`+u.map($b).join(`
|
||||
`):" "+$b(u[0]):"as no adapter specified";throw new $e("There is no suitable adapter to dispatch the request "+f,"ERR_NOT_SUPPORT")}return i}const c1={getAdapter:FT,adapters:Rh};function bm(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new $o(null,t)}function Gb(t){return bm(t),t.headers=Tn.from(t.headers),t.data=vm.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),c1.getAdapter(t.adapter||fl.adapter,t)(t).then(function(s){return bm(t),s.data=vm.call(t,t.transformResponse,s),s.headers=Tn.from(s.headers),s},function(s){return r1(s)||(bm(t),s&&s.response&&(s.response.data=vm.call(t,t.transformResponse,s.response),s.response.headers=Tn.from(s.response.headers))),Promise.reject(s)})}const u1="1.13.2",Ou={};["object","boolean","number","function","string","symbol"].forEach((t,n)=>{Ou[t]=function(s){return typeof s===t||"a"+(n<1?"n ":" ")+t}});const Yb={};Ou.transitional=function(n,r,s){function i(c,u){return"[Axios v"+u1+"] Transitional option '"+c+"'"+u+(s?". "+s:"")}return(c,u,f)=>{if(n===!1)throw new $e(i(u," has been removed"+(r?" in "+r:"")),$e.ERR_DEPRECATED);return r&&!Yb[u]&&(Yb[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}};Ou.spelling=function(n){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${n}`),!0)};function $T(t,n,r){if(typeof t!="object")throw new $e("options must be an object",$e.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 $e("option "+c+" must be "+g,$e.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new $e("Unknown option "+c,$e.ERR_BAD_OPTION)}}const Zc={assertOptions:$T,validators:Ou},_a=Zc.validators;let vs=class{constructor(n){this.defaults=n||{},this.interceptors={request:new zb,response:new zb}}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=bs(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:c}=r;s!==void 0&&Zc.assertOptions(s,{silentJSONParsing:_a.transitional(_a.boolean),forcedJSONParsing:_a.transitional(_a.boolean),clarifyTimeoutError:_a.transitional(_a.boolean)},!1),i!=null&&(W.isFunction(i)?r.paramsSerializer={serialize:i}:Zc.assertOptions(i,{encode:_a.function,serialize:_a.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Zc.assertOptions(r,{baseUrl:_a.spelling("baseURL"),withXsrfToken:_a.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let u=c&&W.merge(c.common,c[r.method]);c&&W.forEach(["delete","get","head","post","put","patch","common"],E=>{delete c[E]}),r.headers=Tn.concat(u,c);const f=[];let g=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(r)===!1||(g=g&&S.synchronous,f.unshift(S.fulfilled,S.rejected))});const h=[];this.interceptors.response.forEach(function(S){h.push(S.fulfilled,S.rejected)});let v,y=0,w;if(!g){const E=[Gb.bind(this),void 0];for(E.unshift(...f),E.push(...h),w=E.length,v=Promise.resolve(r);y<w;)v=v.then(E[y++],E[y++]);return v}w=f.length;let N=r;for(;y<w;){const E=f[y++],S=f[y++];try{N=E(N)}catch(C){S.call(this,C);break}}try{v=Gb.call(this,N)}catch(E){return Promise.reject(E)}for(y=0,w=h.length;y<w;)v=v.then(h[y++],h[y++]);return v}getUri(n){n=bs(this.defaults,n);const r=o1(n.baseURL,n.url,n.allowAbsoluteUrls);return t1(r,n.params,n.paramsSerializer)}};W.forEach(["delete","get","head","options"],function(n){vs.prototype[n]=function(r,s){return this.request(bs(s||{},{method:n,url:r,data:(s||{}).data}))}});W.forEach(["post","put","patch"],function(n){function r(s){return function(c,u,f){return this.request(bs(f||{},{method:n,headers:s?{"Content-Type":"multipart/form-data"}:{},url:c,data:u}))}}vs.prototype[n]=r(),vs.prototype[n+"Form"]=r(!0)});let GT=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 $o(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 YT(t){return function(r){return t.apply(null,r)}}function ZT(t){return W.isObject(t)&&t.isAxiosError===!0}const Zm={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(Zm).forEach(([t,n])=>{Zm[n]=t});function f1(t){const n=new vs(t),r=qx(vs.prototype.request,n);return W.extend(r,vs.prototype,n,{allOwnKeys:!0}),W.extend(r,n,null,{allOwnKeys:!0}),r.create=function(i){return f1(bs(t,i))},r}const zt=f1(fl);zt.Axios=vs;zt.CanceledError=$o;zt.CancelToken=GT;zt.isCancel=r1;zt.VERSION=u1;zt.toFormData=ju;zt.AxiosError=$e;zt.Cancel=zt.CanceledError;zt.all=function(n){return Promise.all(n)};zt.spread=YT;zt.isAxiosError=ZT;zt.mergeConfig=bs;zt.AxiosH
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 Ej=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_j=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),Kb=t=>{const n=_j(t);return n.charAt(0).toUpperCase()+n.slice(1)},y1=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),Cj=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 Nj={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 Aj=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,...Nj,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:y1("lucide",i),...!c&&!Cj(f)&&{"aria-hidden":"true"},...f},[...u.map(([h,v])=>b.createElement(h,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 Rj=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(Aj,{ref:c,iconNode:n,className:y1(`lucide-${Ej(Kb(t))}`,`lucide-${t}`,s),...i}));return r.displayName=Kb(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 Tj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],jj=Rj("x",Tj),Qb=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Wb=Eh,Oh=(t,n)=>r=>{var s;if((n==null?void 0:n.variants)==null)return Wb(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:c}=n,u=Object.keys(i).map(h=>{const v=r==null?void 0:r[h],y=c==null?void 0:c[h];if(v===null)return null;const w=Qb(v)||Qb(y);return i[h][w]}),f=r&&Object.entries(r).reduce((h,v)=>{let[y,w]=v;return w===void 0||(h[y]=w),h},{}),g=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((h,v)=>{let{class:y,className:w,...N}=v;return Object.entries(N).every(E=>{let[S,C]=E;return Array.isArray(C)?C.includes({...c,...f}[S]):{...c,...f}[S]===C})?[...h,y,w]:h},[]);return Wb(t,u,g,r==null?void 0:r.class,r==null?void 0:r.className)};function rr(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 Oj(t,n=globalThis==null?void 0:globalThis.document){const r=rr(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 kj="DismissableLayer",Xm="dismissableLayer.update",Mj="dismissableLayer.pointerDownOutside",Dj="dismissableLayer.focusOutside",Jb,v1=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),ku=b.forwardRef((t,n)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:c,onInteractOutside:u,onDismiss:f,...g}=t,h=b.useContext(v1),[v,y]=b.useState(null),w=(v==null?void 0:v.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,N]=b.useState({}),E=Zt(n,U=>y(U)),S=Array.from(h.layers),[C]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),A=S.indexOf(C),O=v?S.indexOf(v):-1,R=h.layersWithOutsidePointerEventsDisabled.size>0,L=O>=A,I=Uj(U=>{const Q=U.target,le=[...h.branches].some(ue=>ue.contains(Q));!L||le||(i==null||i(U),u==null||u(U),U.defaultPrevented||f==null||f())},w),ee=Bj(U=>{const Q=U.target;[...h.branches].some(ue=>ue.contains(Q))||(c==null||c(U),u==null||u(U),U.defaultPrevented||f==null||f())},w);return Oj(U=>{O===h.layers.size-1&&(s==null||s(U),!U.defaultPrevented&&f&&(U.preventDefault(),f()))},w),b.useEffect(()=>{if(v)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(Jb=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(v)),h.layers.add(v),e0(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=Jb)}},[v,w,r,h]),b.useEffect(()=>()=>{v&&(h.layers.delete(v),h.layersWithOutsidePointerEventsDisabled.delete(v),e0())},[v,h]),b.useEffect(()=>{const U=()=>N({});return document.addEventListener(Xm,U),()=>document.removeEventListener(Xm,U)},[]),p.jsx(jt.div,{...g,ref:E,style:{pointerEvents:R?L?"auto":"none":void 0,...t.style},onFocusCapture:Ve(t.onFocusCapture,ee.onFocusCapture),onBlurCapture:Ve(t.onBlurCapture,ee.onBlurCapture),onPointerDownCapture:Ve(t.onPointerDownCapture,I.onPointerDownCapture)})});ku.displayName=kj;var zj="DismissableLayerBranch",Lj=b.forwardRef((t,n)=>{const r=b.useContext(v1),s=b.useRef(null),i=Zt(n,s);return b.useEffect(()=>{const c=s.current;if(c)return r.branches.add(c),()=>{r.branches.delete(c)}},[r.branches]),p.jsx(jt.div,{...t,ref:i})});Lj.displayName=zj;function Uj(t,n=globalThis==null?void 0:globalThis.document){const r=rr(t),s=b.useRef(!1),i=b.useRef(()=>{});return b.useEffect(()=>{const c=f=>{if(f.target&&!s.current){let g=function(){b1(Mj,r,h,{discrete:!0})};const h={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 Bj(t,n=globalThis==null?void 0:globalThis.document){const r=rr(t),s=b.useRef(!1);return b.useEffect(()=>{const i=c=>{c.target&&!s.current&&b1(Dj,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 e0(){const t=new CustomEvent(Xm);document.dispatchEvent(t)}function b1(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?p1(i,c):i.dispatchEvent(c)}var xm="focusScope.autoFocusOnMount",wm="focusScope.autoFocusOnUnmount",t0={bubbles:!1,cancelable:!0},Pj="FocusScope",Mu=b.forwardRef((t,n)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:i,onUnmountAutoFocus:c,...u}=t,[f,g]=b.useState(null),h=rr(i),v=rr(c),y=b.useRef(null),w=Zt(n,S=>Line truncated
|
||||
.`.concat(Zj,` {
|
||||
overflow: hidden `).concat(s,`;
|
||||
padding-right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
body[`).concat(No,`] {
|
||||
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(Xc,` {
|
||||
right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(Kc,` {
|
||||
margin-right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(Xc," .").concat(Xc,` {
|
||||
right: 0 `).concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(Kc," .").concat(Kc,` {
|
||||
margin-right: 0 `).concat(s,`;
|
||||
}
|
||||
|
||||
body[`).concat(No,`] {
|
||||
`).concat(Xj,": ").concat(f,`px;
|
||||
}
|
||||
`)},i0=function(){var t=parseInt(document.body.getAttribute(No)||"0",10);return isFinite(t)?t:0},hO=function(){b.useEffect(function(){return document.body.setAttribute(No,(i0()+1).toString()),function(){var t=i0()-1;t<=0?document.body.removeAttribute(No):document.body.setAttribute(No,t.toString())}},[])},pO=function(t){var n=t.noRelative,r=t.noImportant,s=t.gapMode,i=s===void 0?"margin":s;hO();var c=b.useMemo(function(){return dO(i)},[i]);return b.createElement(fO,{styles:mO(c,!n,i,r?"":"!important")})},Km=!1;if(typeof window<"u")try{var Lc=Object.defineProperty({},"passive",{get:function(){return Km=!0,!0}});window.addEventListener("test",Lc,Lc),window.removeEventListener("test",Lc,Lc)}catch{Km=!1}var go=Km?{passive:!1}:!1,gO=function(t){return t.tagName==="TEXTAREA"},C1=function(t,n){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[n]!=="hidden"&&!(r.overflowY===r.overflowX&&!gO(t)&&r[n]==="visible")},yO=function(t){return C1(t,"overflowY")},vO=function(t){return C1(t,"overflowX")},l0=function(t,n){var r=n.ownerDocument,s=n;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var i=N1(t,s);if(i){var c=A1(t,s),u=c[1],f=c[2];if(u>f)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},bO=function(t){var n=t.scrollTop,r=t.scrollHeight,s=t.clientHeight;return[n,r,s]},xO=function(t){var n=t.scrollLeft,r=t.scrollWidth,s=t.clientWidth;return[n,r,s]},N1=function(t,n){return t==="v"?yO(n):vO(n)},A1=function(t,n){return t==="v"?bO(n):xO(n)},wO=function(t,n){return t==="h"&&n==="rtl"?-1:1},SO=function(t,n,r,s,i){var c=wO(t,window.getComputedStyle(n).direction),u=c*s,f=r.target,g=n.contains(f),h=!1,v=u>0,y=0,w=0;do{if(!f)break;var N=A1(t,f),E=N[0],S=N[1],C=N[2],A=S-C-c*E;(E||A)&&N1(t,f)&&(y+=A,w+=E);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)&&(h=!0),h},Uc=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},c0=function(t){return[t.deltaX,t.deltaY]},u0=function(t){return t&&"current"in t?t.current:t},EO=function(t,n){return t[0]===n[0]&&t[1]===n[1]},_O=function(t){return`
|
||||
.block-interactivity-`.concat(t,` {pointer-events: none;}
|
||||
.allow-interactivity-`).concat(t,` {pointer-events: all;}
|
||||
`)},CO=0,yo=[];function NO(t){var n=b.useRef([]),r=b.useRef([0,0]),s=b.useRef(),i=b.useState(CO++)[0],c=b.useState(_1)[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 S=Yj([t.lockRef.current],(t.shards||[]).map(u0),!0).filter(Boolean);return S.forEach(function(C){return C.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var f=b.useCallback(function(S,C){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var A=Uc(S),O=r.current,R="deltaX"in S?S.deltaX:O[0]-A[0],L="deltaY"in S?S.deltaY:O[1]-A[1],I,ee=S.target,U=Math.abs(R)>Math.abs(L)?"h":"v";if("touches"in S&&U==="h"&&ee.type==="range")return!1;var Q=l0(U,ee);if(!Q)return!0;if(Q?I=U:(I=U==="v"?"h":"v",Q=l0(U,ee)),!Q)return!1;if(!s.current&&"changedTouches"in S&&(R||L)&&(s.current=I),!I)return!0;var le=s.current||I;return SO(le,C,S,le==="h"?R:L)},[]),g=b.useCallback(function(S){var C=S;if(!(!yo.length||yo[yo.length-1]!==c)){var A="deltaY"in C?c0(C):Uc(C),O=n.current.filter(function(I){return I.name===C.type&&(I.target===C.target||C.target===I.shadowParent)&&EO(I.delta,A)})[0];if(O&&O.should){C.cancelable&&C.preventDefault();return}if(!O){var R=(u.current.shards||[]).map(u0).filter(Boolean).filter(function(I){return I.contains(C.target)}),L=R.length>0?f(C,R[0]):!u.current.noIsolation;L&&C.cancelable&&C.preventDefault()}}},[]),h=b.useCallback(function(S,C,A,O){var R={name:S,delta:C,target:A,should:O,shadowParent:AO(A)};n.current.push(R),setTimeout(function(){n.current=n.current.filter(function(L){return L!==R})},1)},[]),v=b.useCallback(function(S){r.current=Uc(S),s.current=void 0},[]),y=b.useCallback(function(S){h(S.type,c0(S),S.target,f(S,t.lockRef.current))},[]),w=b.useCallback(function(S){h(S.type,Uc(S),S.target,f(S,t.lockRef.current))},[]);b.useEffect(function(){return yo.push(c),t.setCallbacks({onScrollCapture:y,onWheelCapture:y,onTouchMoveCapture:w}),document.addEventListener("wheel",g,go),document.addEventListener("touchmove",g,go),document.addEventListener("touchstart",v,go),function(){yo=yo.filter(function(S){return S!==c}),document.removeEventListener("wheel",g,go),document.removeEventListener("touchmove",g,go),document.removeEventListener("touchstart",v,go)}},[]);var N=t.removeScrollBar,E=t.inert;return b.createElement(b.Fragment,null,E?b.createElement(c,{styles:_O(i)}):null,N?b.createElement(pO,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function AO(t){for(var n=null;t!==null;)t instanceof ShadowRoot&&(n=t.host,t=t.host),t=t.parentNode;return n}const RO=nO(E1,NO);var Lu=b.forwardRef(function(t,n){return b.createElement(zu,Aa({},t,{ref:n,sideCar:RO}))});Lu.classNames=zu.classNames;var TO=function(t){if(typeof document>"u")return null;var n=Array.isArray(t)?t[0]:t;return n.ownerDocument.body},vo=new WeakMap,Bc=new WeakMap,Pc={},Nm=0,R1=function(t){return t&&(t.host||R1(t.parentNode))},jO=function(t,n){return n.map(function(r){if(t.contains(r))return r;var s=R1(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})},OO=function(t,n,r,s){var i=jO(n,Array.isArray(t)?t:[t]);Pc[r]||(Pc[r]=new WeakMap);var c=Pc[r],u=[],f=new Set,g=new Set(i),h=function(y){!y||f.has(y)||(f.add(y),h(y.parentNode))};i.forEach(h);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 N=w.getAttribute(s),E=N!==null&&N!=="false",S=(vo.get(w)||0)+1,C=(c.get(w)||0)+1;vo.set(w,S),c.set(w,C),u.push(w),S===1&&E&&Bc.set(w,!0),C===1&&w.setAttribute(r,"true"),E||w.setAttribute(s,"true")}catch(A){console.error("aria-hidden: cannot operate on ",w,A)}})};return v(n),f.clear(),Nm++,function(){u.forEach(function(y){var w=vo.get(y)-1,N=c.get(y)-1;vo.set(y,w),c.set(y,N),w||(Bc.has(y)||y.removeAttribute(s),Bc.delete(y)),N||y.removeAttribute(r)}),Nm--,Nm||(vo=new WeakMap,vo=new WeakMap,Bc=new WeakMap,Pc={})}},Mh=function(t,n,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(t)?t:[t]),i=TO(t);return i?(s.push.apply(s,Array.from(i.querySelectorAll("[aria-live], script"))),OO(s,i,r,"aria-hidden")):function(){return null}};function kO(t){const n=MO(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(zO);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function MO(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=UO(i),f=LO(c,i.props);return i.type!==b.
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},GO="DialogDescriptionWarning",YO=({contentRef:t,descriptionId:n})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${q1(GO).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},ZO=j1,XO=M1,F1=D1,$1=z1,KO=U1,QO=P1,WO=V1,JO=Symbol.for("react.lazy"),nu=_u[" use ".trim().toString()];function ek(t){return typeof t=="object"&&t!==null&&"then"in t}function G1(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===JO&&"_payload"in t&&ek(t._payload)}function Y1(t){const n=tk(t),r=b.forwardRef((s,i)=>{let{children:c,...u}=s;G1(c)&&typeof nu=="function"&&(c=nu(c._payload));const f=b.Children.toArray(c),g=f.find(ak);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}var Z1=Y1("Slot");function tk(t){const n=b.forwardRef((r,s)=>{let{children:i,...c}=r;if(G1(i)&&typeof nu=="function"&&(i=nu(i._payload)),b.isValidElement(i)){const u=sk(i),f=rk(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(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 nk=Symbol("radix.slottable");function ak(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===nk}function rk(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 sk(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)}function ok(t){const[n,r]=b.useState(void 0);return Ir(()=>{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,h=Array.isArray(g)?g[0]:g;u=h.inlineSize,f=h.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 ik=["top","right","bottom","left"],qr=Math.min,Bn=Math.max,au=Math.round,Hc=Math.floor,ja=t=>({x:t,y:t}),lk={left:"right",right:"left",bottom:"top",top:"bottom"},ck={start:"end",end:"start"};function Qm(t,n,r){return Bn(t,qr(n,r))}function sr(t,n){return typeof t=="function"?t(n):t}function or(t){return t.split("-")[0]}function Go(t){return t.split("-")[1]}function Uh(t){return t==="x"?"y":"x"}function Bh(t){return t==="y"?"height":"width"}const uk=new Set(["top","bottom"]);function Ta(t){return uk.has(or(t))?"y":"x"}function Ph(t){return Uh(Ta(t))}function dk(t,n,r){r===void 0&&(r=!1);const s=Go(t),i=Ph(t),c=Bh(i);let u=i==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return n.reference[c]>n.floating[c]&&(u=ru(u)),[u,ru(u)]}function fk(t){const n=ru(t);return[Wm(t),n,Wm(n)]}function Wm(t){return t.replace(/start|end/g,n=>ck[n])}const d0=["left","right"],f0=["right","left"],mk=["top","bottom"],hk=["bottom","top"];function pk(t,n,r){switch(t){case"top":case"bottom":return r?n?f0:d0:n?d0:f0;case"left":case"right":return n?mk:hk;default:return[]}}function gk(t,n,r,s){const i=Go(t);let c=pk(or(t),r==="start",s);return i&&(c=c.map(u=>u+"-"+i),n&&(c=c.concat(c.map(Wm)))),c}function ru(t){return t.replace(/left|right|bottom|top/g,n=>lk[n])}function yk(t){return{top:0,right:0,bottom:0,left:0,...t}}function X1(t){return typeof t!="number"?yk(t):{top:t,right:t,bottom:t,left:t}}function su(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 m0(t,n,r){let{reference:s,floating:i}=t;const c=Ta(n),u=Ph(n),f=Bh(u),g=or(n),h=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 N;switch(g){case"top":N={x:v,y:s.y-i.height};break;case"bottom":N={x:v,y:s.y+s.height};break;case"right":N={x:s.x+s.width,y};break;case"left":N={x:s.x-i.width,y};break;default:N={x:s.x,y:s.y}}switch(Go(n)){case"start":N[u]-=w*(r&&h?-1:1);break;case"end":N[u]+=w*(r&&h?-1:1);break}return N}const vk=async(t,n,r)=>{const{placement:s="bottom",strategy:i="absolute",middleware:c=[],platform:u}=r,f=c.filter(Boolean),g=await(u.isRTL==null?void 0:u.isRTL(n));let h=await u.getElementRects({reference:t,floating:n,st
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 zD(t,n){typeof t=="function"?t(n):t!=null&&(t.current=n)}function LD(...t){return n=>t.forEach(r=>zD(r,n))}function Yw(...t){return b.useCallback(LD(...t),t)}const E0=t=>{switch(t){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return t}};function jm(t,n){if(!t)return()=>{};const r=t.style.cssText;return Object.assign(t.style,n),()=>{t.style.cssText=r}}function UD(...t){return(...n)=>{for(const r of t)typeof r=="function"&&r(...n)}}const Om={DURATION:.5,EASE:[.32,.72,0,1]},BD=8,PD=26,HD=()=>()=>{};function VD(){const{direction:t,isOpen:n,shouldScaleBackground:r,setBackgroundColorOnScale:s,noBodyStyles:i}=$u(),c=ae.useRef(null),u=b.useMemo(()=>document.body.style.backgroundColor,[]);function f(){return(window.innerWidth-PD)/window.innerWidth}ae.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;UD(s&&!i?jm(document.body,{background:"black"}):HD,jm(g,{transformOrigin:E0(t)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Om.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Om.EASE.join(",")})`}));const h=jm(g,{borderRadius:`${BD}px`,overflow:"hidden",...E0(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()=>{h(),c.current=window.setTimeout(()=>{u?document.body.style.background=u:document.body.style.removeProperty("background")},Om.DURATION*1e3)}}},[n,r,u])}const ID=ae.forwardRef(function({...t},n){const{overlayRef:r,snapPoints:s,onRelease:i,shouldFade:c,isOpen:u,modal:f,shouldAnimate:g}=$u(),h=Yw(n,r),v=s&&s.length>0;if(!f)return null;const y=ae.useCallback(w=>i(w),[i]);return ae.createElement(F1,{onMouseUp:y,ref:h,"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})});ID.displayName="Drawer.Overlay";const qD=ae.forwardRef(function({onPointerDownOutside:t,style:n,onOpenAutoFocus:r,...s},i){const{drawerRef:c,onPress:u,onRelease:f,onDrag:g,keyboardIsOpen:h,snapPointsOffset:v,activeSnapPointIndex:y,modal:w,isOpen:N,direction:E,snapPoints:S,container:C,handleOnly:A,shouldAnimate:O,autoFocus:R}=$u(),[L,I]=ae.useState(!1),ee=Yw(i,c),U=ae.useRef(null),Q=ae.useRef(null),le=ae.useRef(!1),ue=S&&S.length>0;VD();const me=(X,he,be=0)=>{if(le.current)return!0;const j=Math.abs(X.y),Z=Math.abs(X.x),P=Z>j,se=["bottom","right"].includes(he)?1:-1;if(he==="left"||he==="right"){if(!(X.x*se<0)&&Z>=0&&Z<=be)return P}else if(!(X.y*se<0)&&j>=0&&j<=be)return!P;return le.current=!0,!0};ae.useEffect(()=>{ue&&window.requestAnimationFrame(()=>{I(!0)})},[]);function re(X){U.current=null,le.current=!1,f(X)}return ae.createElement($1,{"data-vaul-drawer-direction":E,"data-vaul-drawer":"","data-vaul-delayed-snap-points":L?"true":"false","data-vaul-snap-points":N&&ue?"true":"false","data-vaul-custom-container":C?"true":"false","data-vaul-animate":O!=null&&O.current?"true":"false",...s,ref:ee,style:v&&v.length>0?{"--snap-point-height":`${v[y??0]}px`,...n}:n,onPointerDown:X=>{A||(s.onPointerDown==null||s.onPointerDown.call(s,X),U.current={x:X.pageX,y:X.pageY},u(X))},onOpenAutoFocus:X=>{r==null||r(X),R||X.preventDefault()},onPointerDownOutside:X=>{if
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;
|
||||
}
|
||||
}`;function cz(t){const n=uz(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(fz);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function uz(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=hz(i),f=mz(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(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 dz=Symbol("radix.slottable");function fz(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===dz}function mz(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 hz(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 mS="Popover",[hS]=_s(mS,[Iu]),Zu=Iu(),[tL,Zr]=hS(mS),pS="PopoverAnchor",pz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Zr(pS,r),c=Zu(r),{onCustomAnchorAdd:u,onCustomAnchorRemove:f}=i;return b.useEffect(()=>(u(),()=>f()),[u,f]),p.jsx($h,{...c,...s,ref:n})});pz.displayName=pS;var gS="PopoverTrigger",gz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Zr(gS,r),c=Zu(r),u=Zt(n,i.triggerRef),f=p.jsx(jt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":wS(i.open),...s,ref:u,onClick:Ve(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?f:p.jsx($h,{asChild:!0,...c,children:f})});gz.displayName=gS;var sp="PopoverPortal",[yz,vz]=hS(sp,{forceMount:void 0}),yS=t=>{const{__scopePopover:n,forceMount:r,children:s,container:i}=t,c=Zr(sp,n);return p.jsx(yz,{scope:n,forceMount:r,children:p.jsx(Ma,{present:r||c.open,children:p.jsx(Du,{asChild:!0,container:i,children:s})})})};yS.displayName=sp;var ko="PopoverContent",vS=b.forwardRef((t,n)=>{const r=vz(ko,t.__scopePopover),{forceMount:s=r.forceMount,...i}=t,c=Zr(ko,t.__scopePopover);return p.jsx(Ma,{present:s||c.open,children:c.modal?p.jsx(xz,{...i,ref:n}):p.jsx(wz,{...i,ref:n})})});vS.displayName=ko;var bz=cz("PopoverContent.RemoveScroll"),xz=b.forwardRef((t,n)=>{const r=Zr(ko,t.__scopePopover),s=b.useRef(null),i=Zt(n,s),c=b.useRef(!1);return b.useEffect(()=>{const u=s.current;if(u)return Mh(u)},[]),p.jsx(Lu,{as:bz,allowPinchZoom:!0,children:p.jsx(bS,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ve(t.onCloseAutoFocus,u=>{var f;u.preventDefault(),c.current||(f=r.triggerRef.current)==null||f.focus()}),onPointerDownOutside:Ve(t.onPointerDownOutside,u=>{const f=u.detail.originalEvent,g=f.button===0&&f.ctrlKey===!0,h=f.button===2||g;c.current=h},{checkForDefaultPrevented:!1}),onFocusOutside:Ve(t.onFocusOutside,u=>u.preventDefault(),{checkForDefaultPrevented:!1})})})}),wz=b.forwardRef((t,n)=>{const r=Zr(ko,t.__scopePopover),s=b.useRef(!1),i=b.useRef(!1);return p.jsx(bS,{...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,h;(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;((h=r.triggerRef.current)==null?void 0:h.contains(u))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&i.current&&c.preventDefault()}})}),bS=b.forwardRef((t,n)=>{const{__scopePopover:r,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:c,disableOutsidePointerEvents:u,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:h,onInteractOutside:v,...y}=t,w=Zr(ko,r),N=Zu(r);return kh(),p.jsx(Mu,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:i,onUnmountAutoFocus:c,children:p.jsx(ku,{asChild:!0,disableOutsidePointerEvents:u,onInteractOutside:v,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:h,onDismiss:()=>w.onOpenChange(!1),children:p.jsx(gw,{"data-state":wS(w.open),role:"dialog",id:w.contentId,...N,...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-popp
Line truncated
|
||||
+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
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
var EC=Object.defineProperty;var _C=(t,n,r)=>n in t?EC(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r;var cb=(t,n,r)=>_C(t,typeof n!="symbol"?n+"":n,r);function CC(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 v0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var um={exports:{}},Hi={};/**
|
||||
* @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 ub;function NC(){if(ub)return Hi;ub=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 Hi.Fragment=n,Hi.jsx=r,Hi.jsxs=r,Hi}var db;function RC(){return db||(db=1,um.exports=NC()),um.exports}var h=RC(),dm={exports:{}},Ve={};/**
|
||||
* @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 fb;function AC(){if(fb)return Ve;fb=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"),y=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),w=Symbol.iterator;function C(j){return j===null||typeof j!="object"?null:(j=w&&j[w]||j["@@iterator"],typeof j=="function"?j:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,E={};function R(j,X,L){this.props=j,this.context=X,this.refs=E,this.updater=L||S}R.prototype.isReactComponent={},R.prototype.setState=function(j,X){if(typeof j!="object"&&typeof j!="function"&&j!=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,j,X,"setState")},R.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function k(){}k.prototype=R.prototype;function A(j,X,L){this.props=j,this.context=X,this.refs=E,this.updater=L||S}var D=A.prototype=new k;D.constructor=A,_(D,R.prototype),D.isPureReactComponent=!0;var H=Array.isArray;function $(){}var U={H:null,A:null,T:null,S:null},F=Object.prototype.hasOwnProperty;function de(j,X,L){var Y=L.ref;return{$$typeof:t,type:j,key:X,ref:Y!==void 0?Y:null,props:L}}function fe(j,X){return de(j.type,X,j.props)}function me(j){return typeof j=="object"&&j!==null&&j.$$typeof===t}function se(j){var X={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(L){return X[L]})}var G=/\/+/g;function he(j,X){return typeof j=="object"&&j!==null&&j.key!=null?se(""+j.key):X.toString(36)}function ve(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then($,$):(j.status="pending",j.then(function(X){j.status==="pending"&&(j.status="fulfilled",j.value=X)},function(X){j.status==="pending"&&(j.status="rejected",j.reason=X)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function T(j,X,L,Y,J){var ie=typeof j;(ie==="undefined"||ie==="boolean")&&(j=null);var pe=!1;if(j===null)pe=!0;else switch(ie){case"bigint":case"string":case"number":pe=!0;break;case"object":switch(j.$$typeof){case t:case n:pe=!0;break;case y:return pe=j._init,T(pe(j._payload),X,L,Y,J)}}if(pe)return J=J(j),pe=Y===""?"."+he(j,0):Y,H(J)?(L="",pe!=null&&(L=pe.replace(G,"$&/")+"/"),T(J,X,L,"",function(Re){return Re})):J!=null&&(me(J)&&(J=fe(J,L+(J.key==null||j&&j.key===J.key?"":(""+J.key).replace(G,"$&/")+"/")+pe)),X.push(J)),1;pe=0;var Q=Y===""?".":Y+":";if(H(j))for(var oe=0;oe<j.length;oe++)Y=j[oe],ie=Q+he(Y,oe),pe+=T(Y,X,L,ie,J);else if(oe=C(j),typeof oe=="function")for(j=oe.call(j),oe=0;!(Y=j.next()).done;)Y=Y.value,ie=Q+he(Y,oe++),pe+=T(Y,X,L,ie,J);else if(ie==="object"){if(typeof j.then=="function")return T(ve(j),X,L,Y,J);throw X=String(j),Error("Objects are not valid as a React child (found: "+(X==="[object Object]"?"object with keys {"+Object.keys(j).join(", ")+"}":X)+"). If you meant to render a collection of children, use an array instead.")}return pe}function K(j,X,L){if(j==null)return j;var Y=[],J=0;return T(j,Y,"","",function(ie){return X.call(L,ie,J++)}),Y}function te(j){if(j._status===-1){var X=j._result;X=X(),X.then(function(L){(j._status===0||j._status===-1)&&(j._status=1,j._result=L)},function(L){(j._status===0||j._status===-1)&&(j._status=2,j._result=L)}),j._status===-1&&(j._status=0,j._result=X)}if(j._status===1)return j._result.default;throw j._result}var le=typeof reportError=="function"?reportError:function(j){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var X=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof j=="object"&&j!==null&&typeof j.message=="string"?String(j.message):String(j),error:j});if(!window.dispatchEvent(X))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",j);return}console.error(j)},ne={map:K,forEach:function(j,X,L){K(j,function(){X.apply(this,arguments)},L)},count:function(j){var X=0;return K(j,function(){X++}),X},toArray:function(j){return K(j,function(X){return X})||[]},only:function(j){if(!me(j))throw Error("React.Children.only expected to receive a single React element child.");return j}};return Ve.Activity=v,Ve.Children=ne,Ve.Component=R,Ve.Fragment=r,Ve.Profiler=i,Ve.PureComponent=A,Ve.StrictMode=s,Ve.Suspense=g,Ve.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=U,Ve.__COMPILER_RUNTIME={__proto__:null,c:function(j){return U.H.useMemoCache(j)}},Ve.cache=function(j){return function(){return j.apply(null,arguments)}},Ve.cacheSignal=function(){return null},Ve.cloneElement=function(j,X,L){if(j==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 hb;function TC(){return hb||(hb=1,(function(t){function n(T,K){var te=T.length;T.push(K);e:for(;0<te;){var le=te-1>>>1,ne=T[le];if(0<i(ne,K))T[le]=K,T[te]=ne,te=le;else break e}}function r(T){return T.length===0?null:T[0]}function s(T){if(T.length===0)return null;var K=T[0],te=T.pop();if(te!==K){T[0]=te;e:for(var le=0,ne=T.length,j=ne>>>1;le<j;){var X=2*(le+1)-1,L=T[X],Y=X+1,J=T[Y];if(0>i(L,te))Y<ne&&0>i(J,L)?(T[le]=J,T[Y]=te,le=Y):(T[le]=L,T[X]=te,le=X);else if(Y<ne&&0>i(J,te))T[le]=J,T[Y]=te,le=Y;else break e}}return K}function i(T,K){var te=T.sortIndex-K.sortIndex;return te!==0?te:T.id-K.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=[],y=1,v=null,w=3,C=!1,S=!1,_=!1,E=!1,R=typeof setTimeout=="function"?setTimeout:null,k=typeof clearTimeout=="function"?clearTimeout:null,A=typeof setImmediate<"u"?setImmediate:null;function D(T){for(var K=r(p);K!==null;){if(K.callback===null)s(p);else if(K.startTime<=T)s(p),K.sortIndex=K.expirationTime,n(g,K);else break;K=r(p)}}function H(T){if(_=!1,D(T),!S)if(r(g)!==null)S=!0,$||($=!0,se());else{var K=r(p);K!==null&&ve(H,K.startTime-T)}}var $=!1,U=-1,F=5,de=-1;function fe(){return E?!0:!(t.unstable_now()-de<F)}function me(){if(E=!1,$){var T=t.unstable_now();de=T;var K=!0;try{e:{S=!1,_&&(_=!1,k(U),U=-1),C=!0;var te=w;try{t:{for(D(T),v=r(g);v!==null&&!(v.expirationTime>T&&fe());){var le=v.callback;if(typeof le=="function"){v.callback=null,w=v.priorityLevel;var ne=le(v.expirationTime<=T);if(T=t.unstable_now(),typeof ne=="function"){v.callback=ne,D(T),K=!0;break t}v===r(g)&&s(g),D(T)}else s(g);v=r(g)}if(v!==null)K=!0;else{var j=r(p);j!==null&&ve(H,j.startTime-T),K=!1}}break e}finally{v=null,w=te,C=!1}K=void 0}}finally{K?se():$=!1}}}var se;if(typeof A=="function")se=function(){A(me)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,he=G.port2;G.port1.onmessage=me,se=function(){he.postMessage(null)}}else se=function(){R(me,0)};function ve(T,K){U=R(function(){T(t.unstable_now())},K)}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(T){T.callback=null},t.unstable_forceFrameRate=function(T){0>T||125<T?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):F=0<T?Math.floor(1e3/T):5},t.unstable_getCurrentPriorityLevel=function(){return w},t.unstable_next=function(T){switch(w){case 1:case 2:case 3:var K=3;break;default:K=w}var te=w;w=K;try{return T()}finally{w=te}},t.unstable_requestPaint=function(){E=!0},t.unstable_runWithPriority=function(T,K){switch(T){case 1:case 2:case 3:case 4:case 5:break;default:T=3}var te=w;w=T;try{return K()}finally{w=te}},t.unstable_scheduleCallback=function(T,K,te){var le=t.unstable_now();switch(typeof te=="object"&&te!==null?(te=te.delay,te=typeof te=="number"&&0<te?le+te:le):te=le,T){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,T={id:y++,callback:K,priorityLevel:T,startTime:te,expirationTime:ne,sortIndex:-1},te>le?(T.sortIndex=te,n(p,T),r(g)===null&&T===r(p)&&(_?(k(U),U=-1):_=!0,ve(H,te-le))):(T.sortIndex=ne,n(g,T),S||C||(S=!0,$||($=!0,se()))),T},t.unstable_shouldYield=fe,t.unstable_wrapCallback=function(T){var K=w;return function(){var te=w;w=K;try{return T.apply(this,arguments)}finally{w=te}}}})(hm)),hm}var pb;function OC(){return pb||(pb=1,mm.exports=TC()),mm.exports}var pm={exports:{}},fn={};/**
|
||||
* @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 gb;function jC(){if(gb)return fn;gb=1;var t=wh();function n(g){var p="https://react.dev/errors/"+g;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var y=2;y<arguments.length;y++)p+="&args[]="+encodeURIComponent(arguments[y])}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,y){var v=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:v==null?null:""+v,children:g,containerInfo:p,implementation:y}}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 fn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,fn.createPortal=function(g,p){var y=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,y)},fn.flushSync=function(g){var p=u.T,y=s.p;try{if(u.T=null,s.p=2,g)return g()}finally{u.T=p,s.p=y,s.d.f()}},fn.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))},fn.prefetchDNS=function(g){typeof g=="string"&&s.d.D(g)},fn.preinit=function(g,p){if(typeof g=="string"&&p&&typeof p.as=="string"){var y=p.as,v=f(y,p.crossOrigin),w=typeof p.integrity=="string"?p.integrity:void 0,C=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;y==="style"?s.d.S(g,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:v,integrity:w,fetchPriority:C}):y==="script"&&s.d.X(g,{crossOrigin:v,integrity:w,fetchPriority:C,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},fn.preinitModule=function(g,p){if(typeof g=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var y=f(p.as,p.crossOrigin);s.d.M(g,{crossOrigin:y,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)},fn.preload=function(g,p){if(typeof g=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var y=p.as,v=f(y,p.crossOrigin);s.d.L(g,y,{crossOrigin:v,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})}},fn.preloadModule=function(g,p){if(typeof g=="string")if(p){var y=f(p.as,p.crossOrigin);s.d.m(g,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else s.d.m(g)},fn.requestFormReset=function(g){s.d.r(g)},fn.unstable_batchedUpdates=function(g,p){return g(p)},fn.useFormState=function(g,p,y){return u.H.useFormState(g,p,y)},fn.useFormStatus=function(){return u.H.useHostTransitionStatus()},fn.version="19.2.4",fn}var vb;function y0(){if(vb)return pm.exports;vb=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(),pm.exports=jC(),pm.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 yb;function kC(){if(yb)return Vi;yb=1;var t=OC(),n=wh(),r=y0();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 m=d.alternate;if(m===null){if(l=d.return,l!==null){o=l;continue}break}if(d.child===m.child){for(m=d.child;m;){if(m===o)return g(d),e;if(m===l)return g(d),a;m=m.sibling}throw Error(s(188))}if(o.return!==l.return)o=d,l=m;else{for(var x=!1,N=d.child;N;){if(N===o){x=!0,o=d,l=m;break}if(N===l){x=!0,l=d,o=m;break}N=N.sibling}if(!x){for(N=m.child;N;){if(N===o){x=!0,o=m,l=d;break}if(N===l){x=!0,l=m,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 y(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e;for(e=e.child;e!==null;){if(a=y(e),a!==null)return a;e=e.sibling}return null}var v=Object.assign,w=Symbol.for("react.element"),C=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),_=Symbol.for("react.fragment"),E=Symbol.for("react.strict_mode"),R=Symbol.for("react.profiler"),k=Symbol.for("react.consumer"),A=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),H=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),U=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),de=Symbol.for("react.activity"),fe=Symbol.for("react.memo_cache_sentinel"),me=Symbol.iterator;function se(e){return e===null||typeof e!="object"?null:(e=me&&e[me]||e["@@iterator"],typeof e=="function"?e:null)}var G=Symbol.for("react.client.reference");function he(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===G?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case _:return"Fragment";case R:return"Profiler";case E:return"StrictMode";case H:return"Suspense";case $:return"SuspenseList";case de:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case S:return"Portal";case A:return e.displayName||"Context";case k: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:he(e.type)||"Memo";case F:a=e._payload,e=e._init;try{return he(e(a))}catch{}}return null}var ve=Array.isArray,T=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te={pending:!1,data:null,method:null,action:null},le=[],ne=-1;function j(e){return{current:e}}function X(e){0>ne||(e.current=le[ne],le[ne]=null,ne--)}function L(e,a){ne++,le[ne]=e.current,e.current=a}var Y=j(null),J=j(null),ie=j(null),pe=j(null);function Q(e,a){switch(L(ie,a),L(J,e),L(Y,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?ky(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=ky(a),e=My(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}X(Y),L(Y,e)}function oe(){X(Y),X(J),X(ie)}function Re(e){e.memoizedState!==null&&L(pe,e);var a=Y.current,o=My(a,e.type);a!==o&&(L(J,e),L(Y,o))}function et(e){J.current===e&&(X(Y),X(J)),pe.current===e&&(X(pe),Li._currentValue=te)}var Me,ze;function be(e){if(Me===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);Me=a&&a[1]||"",ze=-1<o.stack.indexOf(`
|
||||
at`)?" (<anonymous>)":-1<o.stack.indexOf("@")?"@unknown:0:0":""}return`
|
||||
`+Me+e+ze}var je=!1;function at(e,a){if(!e||je)return"";je=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(a){var ue=function(){throw Error()};if(Object.defineProperty(ue.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ue,[])}catch(ee){var Z=ee}Reflect.construct(e,[],ue)}else{try{ue.call()}catch(ee){Z=ee}e.call(ue.prototype)}}else{try{throw Error()}catch(ee){Z=ee}(ue=e())&&typeof ue.catch=="function"&&ue.catch(function(){})}}catch(ee){if(ee&&Z&&typeof ee.stack=="string")return[ee.stack,Z.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 m=l.DetermineComponentFrameRoot(),x=m[0],N=m[1];if(x&&N){var M=x.split(`
|
||||
`),q=N.split(`
|
||||
`);for(d=l=0;l<M.length&&!M[l].includes("DetermineComponentFrameRoot");)l++;for(;d<q.length&&!q[d].includes("DetermineComponentFrameRoot");)d++;if(l===M.length||d===q.length)for(l=M.length-1,d=q.length-1;1<=l&&0<=d&&M[l]!==q[d];)d--;for(;1<=l&&0<=d;l--,d--)if(M[l]!==q[d]){if(l!==1||d!==1)do if(l--,d--,0>d||M[l]!==q[d]){var re=`
|
||||
`+M[l].replace(" at new "," at ");return e.displayName&&re.includes("<anonymous>")&&(re=re.replace("<anonymous>",e.displayName)),re}while(1<=l&&0<=d);break}}}finally{je=!1,Error.prepareStackTrace=o}return(o=e?e.displayName||e.name:"")?be(o):""}function ht(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 at(e.type,!1);case 11:return at(e.type.render,!1);case 1:return at(e.type,!0);case 31:return be("Activity");default:return""}}function Qe(e){try{var a="",o=null;do a+=ht(e,o),o=e,e=e.return;while(e);return a}catch(l){return`
|
||||
Error generating stack: `+l.message+`
|
||||
`+l.stack}}var Pe=Object.prototype.hasOwnProperty,Tt=t.unstable_scheduleCallback,Zt=t.unstable_cancelCallback,O=t.unstable_shouldYield,B=t.unstable_requestPaint,V=t.unstable_now,we=t.unstable_getCurrentPriorityLevel,ge=t.unstable_ImmediatePriority,ye=t.unstable_UserBlockingPriority,Se=t.unstable_NormalPriority,Ue=t.unstable_LowPriority,Ge=t.unstable_IdlePriority,Pt=t.log,Mt=t.unstable_setDisableYieldValue,mt=null,Dt=null;function an(e){if(typeof Pt=="function"&&Mt(e),Dt&&typeof Dt.setStrictMode=="function")try{Dt.setStrictMode(mt,e)}catch{}}var Ht=Math.clz32?Math.clz32:Yn,Ko=Math.log,ur=Math.LN2;function Yn(e){return e>>>=0,e===0?32:31-(Ko(e)/ur|0)|0}var Ua=256,ks=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 He(e,a,o){var l=e.pendingLanes;if(l===0)return 0;var d=0,m=e.suspendedLanes,x=e.pingedLanes;e=e.warmLanes;var N=l&134217727;return N!==0?(l=N&~m,l!==0?d=xa(l):(x&=N,x!==0?d=xa(x):o||(o=N&~e,o!==0&&(d=xa(o))))):(N=l&~m,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&m)===0&&(m=d&-d,o=a&-a,m>=o||m===32&&(o&4194048)!==0)?a:d}function _t(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function en(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 dn(){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 Rt(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function bn(e,a,o,l,d,m){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,q=e.hiddenUpdates;for(o=x&~o;0<o;){var re=31-Ht(o),ue=1<<re;N[re]=0,M[re]=-1;var Z=q[re];if(Z!==null)for(q[re]=null,re=0;re<Z.length;re++){var ee=Z[re];ee!==null&&(ee.lane&=-536870913)}o&=~ue}l!==0&&Jr(e,l,0),m!==0&&d===0&&e.tag!==0&&(e.suspendedLanes|=m&~(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:Ms(o),(o&(e.suspendedLanes|a))!==0?0:o}function Ms(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 Ju(){var e=K.p;return e!==0?e:(e=window.event,e===void 0?32:nb(e.type))}function yp(e,a){var o=K.p;try{return K.p=e,a()}finally{K.p=o}}var fr=Math.random().toString(36).slice(2),rn="__reactFiber$"+fr,Sn="__reactProps$"+fr,Ds="__reactContainer$"+fr,ed="__reactEvents$"+fr,fE="__reactListeners$"+fr,mE="__reactHandles$"+fr,bp="__reactResources$"+fr,Qo="__reactMarker$"+fr;function td(e){delete e[rn],delete e[Sn],delete e[ed],delete e[fE],delete e[mE]}function zs(e){var a=e[rn];if(a)return a;for(var o=e.parentNode;o;){if(a=o[Ds]||o[rn]){if(o=a.alternate,a.child!==null||o!==null&&o.child!==null)for(e=Hy(e);e!==null;){if(o=e[rn])return o;e=Hy(e)}return a}e=o,o=e.parentNode}return null}function Ls(e){if(e=e[rn]||e[Ds]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function Wo(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(s(33))}function Us(e){var a=e[bp];return a||(a=e[bp]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function tn(e){e[Qo]=!0}var xp=new Set,wp={};function es(e,a){Bs(e,a),Bs(e+"Capture",a)}function Bs(e,a){for(wp[e]=a,e=0;e<a.length;e++)xp.add(a[e])}var hE=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\
Line truncated
|
||||
`).replace($_,"")}function Oy(e,a){return a=Ty(a),Ty(e)===a}function yt(e,a,o,l,d,m){switch(o){case"children":typeof l=="string"?a==="body"||a==="textarea"&&l===""||Hs(e,l):(typeof l=="number"||typeof l=="bigint")&&a!=="body"&&Hs(e,""+l);break;case"className":wl(e,"class",l);break;case"tabIndex":wl(e,"tabindex",l);break;case"dir":case"role":case"viewBox":case"width":case"height":wl(e,o,l);break;case"style":Op(e,l,m);break;case"data":if(a!=="object"){wl(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=El(""+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 m=="function"&&(o==="formAction"?(a!=="input"&&yt(e,a,"name",d.name,d,null),yt(e,a,"formEncType",d.formEncType,d,null),yt(e,a,"formMethod",d.formMethod,d,null),yt(e,a,"formTarget",d.formTarget,d,null)):(yt(e,a,"encType",d.encType,d,null),yt(e,a,"method",d.method,d,null),yt(e,a,"target",d.target,d,null)));if(l==null||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=El(""+l),e.setAttribute(o,l);break;case"onClick":l!=null&&(e.onclick=Pa);break;case"onScroll":l!=null&&Je("scroll",e);break;case"onScrollEnd":l!=null&&Je("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=El(""+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":Je("beforetoggle",e),Je("toggle",e),xl(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":xl(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=bE.get(o)||o,xl(e,o,l))}}function Gf(e,a,o,l,d,m){switch(o){case"style":Op(e,l,m);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"?Hs(e,l):(typeof l=="number"||typeof l=="bigint")&&Hs(e,""+l);break;case"onScroll":l!=null&&Je("scroll",e);break;case"onScrollEnd":l!=null&&Je("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 xb="popstate";function wb(t){return typeof t=="object"&&t!=null&&"pathname"in t&&"search"in t&&"hash"in t&&"state"in t&&"key"in t}function zC(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 Fm("",{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:Ji(i)}return UC(n,r,null,t)}function Nt(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 LC(){return Math.random().toString(36).substring(2,10)}function Sb(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 Fm(t,n,r=null,s,i){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof n=="string"?qo(n):n,state:r,key:n&&n.key||s||LC(),unstable_mask:i}}function Ji({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 qo(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 UC(t,n,r,s={}){let{window:i=document.defaultView,v5Compat:c=!1}=s,u=i.history,f="POP",g=null,p=y();p==null&&(p=0,u.replaceState({...u.state,idx:p},""));function y(){return(u.state||{idx:null}).idx}function v(){f="POP";let E=y(),R=E==null?null:E-p;p=E,g&&g({action:f,location:_.location,delta:R})}function w(E,R){f="PUSH";let k=wb(E)?E:Fm(_.location,E,R);p=y()+1;let A=Sb(k,p),D=_.createHref(k.unstable_mask||k);try{u.pushState(A,"",D)}catch(H){if(H instanceof DOMException&&H.name==="DataCloneError")throw H;i.location.assign(D)}c&&g&&g({action:f,location:_.location,delta:1})}function C(E,R){f="REPLACE";let k=wb(E)?E:Fm(_.location,E,R);p=y();let A=Sb(k,p),D=_.createHref(k.unstable_mask||k);u.replaceState(A,"",D),c&&g&&g({action:f,location:_.location,delta:0})}function S(E){return BC(E)}let _={get action(){return f},get location(){return t(i,u)},listen(E){if(g)throw new Error("A history only accepts one active listener");return i.addEventListener(xb,v),g=E,()=>{i.removeEventListener(xb,v),g=null}},createHref(E){return n(i,E)},createURL:S,encodeLocation(E){let R=S(E);return{pathname:R.pathname,search:R.search,hash:R.hash}},push:w,replace:C,go(E){return u.go(E)}};return _}function BC(t,n=!1){let r="http://localhost";typeof window<"u"&&(r=window.location.origin!=="null"?window.location.origin:window.location.href),Nt(r,"No window.location.(origin|href) available to create URL");let s=typeof t=="string"?t:Ji(t);return s=s.replace(/ $/,"%20"),!n&&s.startsWith("//")&&(s=r+s),new URL(s,r)}function b0(t,n,r="/"){return PC(t,n,r,!1)}function PC(t,n,r,s){let i=typeof n=="string"?qo(n):n,c=rr(i.pathname||"/",r);if(c==null)return null;let u=x0(t);HC(u);let f=null;for(let g=0;f==null&&g<u.length;++g){let p=QC(c);f=XC(u[g],p,s)}return f}function x0(t,n=[],r=[],s="",i=!1){let c=(u,f,g=i,p)=>{let y={relativePath:p===void 0?u.path||"":p,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(y.relativePath.startsWith("/")){if(!y.relativePath.startsWith(s)&&g)return;Nt(y.relativePath.startsWith(s),`Absolute route path "${y.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),y.relativePath=y.relativePath.slice(s.length)}let v=ja([s,y.relativePath]),w=r.concat(y);u.children&&u.children.length>0&&(Nt(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${v}".`),x0(u.children,n,w,v,g)),!(u.path==null&&!u.index)&&n.push({path:v,score:YC(v,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 w0(u.path))c(u,f,!0,p)}),n}function w0(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=w0(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 HC(t){t.sort((n,r)=>n.score!==r.score?r.score-n.score:ZC(n.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}var VC=/^:[\w-]+$/,IC=3,qC=2,FC=1,$C=10,GC=-2,Eb=t=>t==="*";function YC(t,n){let r=t.split("/"),s=r.length;return r.some(Eb)&&(s+=GC),n&&(s+=qC),r.filter(i=>!Eb(i)).reduce((i,c)=>i+(VC.test(c)?IC:c===""?FC:$C),s)}function ZC(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 XC(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,y=c==="/"?n:n.slice(c.length)||"/",v=eu({path:g.relativePath,cas
Line truncated
|
||||
|
||||
Please change the parent <Route path="${R}"> to <Route path="${R==="/"?"*":`${R}/*`}">.`)}let y=Da(),v;if(n){let R=typeof n=="string"?qo(n):n;Nt(g==="/"||((E=R.pathname)==null?void 0:E.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.`),v=R}else v=y;let w=v.pathname||"/",C=w;if(g!=="/"){let R=g.replace(/^\//,"").split("/");C="/"+w.replace(/^\//,"").split("/").slice(R.length).join("/")}let S=b0(t,{pathname:C});oa(p||S!=null,`No routes matched location "${v.pathname}${v.search}${v.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 "${v.pathname}${v.search}${v.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 _=CN(S&&S.map(R=>Object.assign({},R,{params:Object.assign({},u,R.params),pathname:ja([g,s.encodeLocation?s.encodeLocation(R.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?g:ja([g,s.encodeLocation?s.encodeLocation(R.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathnameBase])})),i,r);return n&&_?b.createElement(il.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...v},navigationType:"POP"}},_):_}function wN(){let t=ON(),n=sN(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 SN=b.createElement(wN,null),O0=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=hN(t.digest);r&&(t=r)}let n=t!==void 0?b.createElement(ia.Provider,{value:this.props.routeContext},b.createElement(Eh.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?b.createElement(EN,{error:t},n):n}};O0.contextType=lN;var vm=new WeakMap;function EN({children:t,error:n}){let{basename:r}=b.useContext(Gn);if(typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){let s=mN(n.digest);if(s){let i=vm.get(n);if(i)throw i;let c=E0(s.location,r);if(S0&&!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 _N({routeContext:t,match:n,children:r}){let s=b.useContext(Fo);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 CN(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 y=i.findIndex(v=>v.route.id&&(c==null?void 0:c[v.route.id])!==void 0);Nt(y>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(c).join(",")}`),i=i.slice(0,Math.min(i.length,y+1))}let u=!1,f=-1;if(r&&s){u=s.renderFallback;for(let y=0;y<i.length;y++){let v=i[y];if((v.route.HydrateFallback||v.route.hydrateFallbackElement)&&(f=y),v.route.id){let{loaderData:w,errors:C}=s,S=vLine 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(),F2=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),Tb=t=>{const n=F2(t);return n.charAt(0).toUpperCase()+n.slice(1)},P0=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),$2=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 G2={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 Y2=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,...G2,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:P0("lucide",i),...!c&&!$2(f)&&{"aria-hidden":"true"},...f},[...u.map(([p,y])=>b.createElement(p,y)),...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 st=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(Y2,{ref:c,iconNode:n,className:P0(`lucide-${q2(Tb(t))}`,`lucide-${t}`,s),...i}));return r.displayName=Tb(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 Z2=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ob=st("arrow-left",Z2);/**
|
||||
* @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 X2=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],K2=st("arrow-right",X2);/**
|
||||
* @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=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Zm=st("chevron-down",Q2);/**
|
||||
* @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 W2=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],jb=st("chevron-right",W2);/**
|
||||
* @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 J2=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],eR=st("chevron-up",J2);/**
|
||||
* @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=[["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"}]],nR=st("circle-alert",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 aR=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],rR=st("circle-check-big",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=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],kb=st("circle-check",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 oR=[["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"}]],iR=st("circle-x",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 lR=[["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"}]],cR=st("ellipsis-vertical",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:"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"}]],dR=st("eye-off",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 fR=[["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"}]],mR=st("eye",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 hR=[["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"}]],pR=st("funnel",hR);/**
|
||||
* @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:"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"}]],vR=st("globe",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 yR=[["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=st("layers",yR);/**
|
||||
* @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=[["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"}]],wR=st("layout-dashboard",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=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],H0=st("loader-circle",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 ER=[["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"}]],_R=st("log-out",ER);/**
|
||||
* @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:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]],NR=st("message-square",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 RR=[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]],AR=st("moon",RR);/**
|
||||
* @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:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Xm=st("plus",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 OR=[["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"}]],jR=st("power-off",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 kR=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],V0=st("power",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 MR=[["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"}]],Mb=st("qr-code",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 DR=[["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"}]],Db=st("refresh-cw",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 zR=[["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"}]],zb=st("save",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 LR=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],UR=st("search",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 BR=[["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"}]],PR=st("settings",BR);/**
|
||||
* @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 HR=[["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"}]],VR=st("shield",HR);/**
|
||||
* @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=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],qR=st("smartphone",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=[["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"}]],$R=st("sun",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:"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"}]],Th=st("trash-2",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 YR=[["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"}]],ZR=st("triangle-alert",YR);/**
|
||||
* @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 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],el=st("x",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 KR=[["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"}]],QR=st("zap",KR);class WR extends b.Component{constructor(r){super(r);cb(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:h.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-50 px-4",children:h.jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-8 shadow-lg",children:[h.jsx("div",{className:"mb-4 flex items-center justify-center",children:h.jsx("div",{className:"rounded-full bg-red-100 p-3",children:h.jsx(ZR,{className:"h-8 w-8 text-red-600"})})}),h.jsx("h1",{className:"mb-2 text-center text-2xl font-bold text-gray-900",children:"Algo deu errado"}),h.jsx("p",{className:"mb-6 text-center text-gray-600",children:"Ocorreu um erro inesperado na aplicação."}),this.state.error&&h.jsxs("div",{className:"mb-6 rounded-md bg-red-50 p-4",children:[h.jsx("p",{className:"text-sm font-medium text-red-800",children:this.state.error.message}),!1]}),h.jsxs("div",{className:"flex gap-3",children:[h.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"}),h.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 I0(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=I0(t[n]))&&(s&&(s+=" "),s+=r)}else for(r in t)t[r]&&(s&&(s+=" "),s+=r);return s}function Oh(){for(var t,n,r=0,s="",i=arguments.length;r<i;r++)(t=arguments[r])&&(n=I0(t))&&(s&&(s+=" "),s+=n);return s}const JR=(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},eA=(t,n)=>({classGroupId:t,validator:n}),q0=(t=new Map,n=null,r)=>({nextPart:t,validators:n,classGroupId:r}),tu="-",Lb=[],tA="arbitrary..",nA=t=>{const n=rA(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=t;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return aA(u);const f=u.split(tu),g=f[0]===""&&f.length>1?1:0;return F0(f,g,n)},getConflictingClassGroupIds:(u,f)=>{if(f){const g=s[u],p=r[u];return g?p?JR(p,g):g:p||Lb}return r[u]||Lb}}},F0=(t,n,r)=>{if(t.length-n===0)return r.classGroupId;const i=t[n],c=r.nextPart.get(i);if(c){const p=F0(t,n+1,c);if(p)return p}const u=r.validators;if(u===null)return;const f=n===0?t.join(tu):t.slice(n).join(tu),g=u.length;for(let p=0;p<g;p++){const y=u[p];if(y.validator(f))return y.classGroupId}},aA=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?tA+s:void 0})(),rA=t=>{const{theme:n,classGroups:r}=t;return sA(r,n)},sA=(t,n)=>{const r=q0();for(const s in t){const i=t[s];jh(i,r,s,n)}return r},jh=(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"){iA(t,n,r);return}if(typeof t=="function"){lA(t,n,r,s);return}cA(t,n,r,s)},iA=(t,n,r)=>{const s=t===""?n:$0(n,t);s.classGroupId=r},lA=(t,n,r,s)=>{if(uA(t)){jh(t(s),n,r,s);return}n.validators===null&&(n.validators=[]),n.validators.push(eA(r,t))},cA=(t,n,r,s)=>{const i=Object.entries(t),c=i.length;for(let u=0;u<c;u++){const[f,g]=i[u];jh(g,$0(n,f),r,s)}},$0=(t,n)=>{let r=t;const s=n.split(tu),i=s.length;for(let c=0;c<i;c++){const u=s[c];let f=r.nextPart.get(u);f||(f=q0(),r.nextPart.set(u,f)),r=f}return r},uA=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,dA=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)}}},Km="!",Ub=":",fA=[],Bb=(t,n,r,s,i)=>({modifiers:t,hasImportantModifier:n,baseClassName:r,maybePostfixModifierPosition:s,isExternal:i}),mA=t=>{const{prefix:n,experimentalParseClassName:r}=t;let s=i=>{const c=[];let u=0,f=0,g=0,p;const y=i.length;for(let _=0;_<y;_++){const E=i[_];if(u===0&&f===0){if(E===Ub){c.push(i.slice(g,_)),g=_+1;continue}if(E==="/"){p=_;continue}}E==="["?u++:E==="]"?u--:E==="("?f++:E===")"&&f--}const v=c.length===0?i:i.slice(g);let w=v,C=!1;v.endsWith(KLine truncated
|
||||
`).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),s=u.substring(i+1).trim(),!(!r||n[r]&&eO[r])&&(r==="set-cookie"?n[r]?n[r].push(s):n[r]=[s]:n[r]=n[r]?n[r]+", "+s:s)}),n},Zb=Symbol("internals");function Fi(t){return t&&String(t).trim().toLowerCase()}function Xc(t){return t===!1||t==null?t:W.isArray(t)?t.map(Xc):String(t)}function nO(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 aO=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Sm(t,n,r,s,i){if(W.isFunction(s))return s.call(this,n,r);if(i&&(n=r),!!W.isString(n)){if(W.isString(s))return n.indexOf(s)!==-1;if(W.isRegExp(s))return s.test(n)}}function rO(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(n,r,s)=>r.toUpperCase()+s)}function sO(t,n){const r=W.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 kn=class{constructor(n){n&&this.set(n)}set(n,r,s){const i=this;function c(f,g,p){const y=Fi(g);if(!y)throw new Error("header name must be a non-empty string");const v=W.findKey(i,y);(!v||i[v]===void 0||p===!0||p===void 0&&i[v]!==!1)&&(i[v||g]=Xc(f))}const u=(f,g)=>W.forEach(f,(p,y)=>c(p,y,g));if(W.isPlainObject(n)||n instanceof this.constructor)u(n,r);else if(W.isString(n)&&(n=n.trim())&&!aO(n))u(tO(n),r);else if(W.isObject(n)&&W.isIterable(n)){let f={},g,p;for(const y of n){if(!W.isArray(y))throw TypeError("Object iterator must return a key-value pair");f[p=y[0]]=(g=f[p])?W.isArray(g)?[...g,y[1]]:[g,y[1]]:y[1]}u(f,r)}else n!=null&&c(r,n,s);return this}get(n,r){if(n=Fi(n),n){const s=W.findKey(this,n);if(s){const i=this[s];if(!r)return i;if(r===!0)return nO(i);if(W.isFunction(r))return r.call(this,i,s);if(W.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(n,r){if(n=Fi(n),n){const s=W.findKey(this,n);return!!(s&&this[s]!==void 0&&(!r||Sm(this,this[s],s,r)))}return!1}delete(n,r){const s=this;let i=!1;function c(u){if(u=Fi(u),u){const f=W.findKey(s,u);f&&(!r||Sm(s,s[f],f,r))&&(delete s[f],i=!0)}}return W.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||Sm(this,this[c],c,n,!0))&&(delete this[c],i=!0)}return i}normalize(n){const r=this,s={};return W.forEach(this,(i,c)=>{const u=W.findKey(s,c);if(u){r[u]=Xc(i),delete r[c];return}const f=n?rO(c):String(c).trim();f!==c&&delete r[c],r[f]=Xc(i),s[f]=!0}),this}concat(...n){return this.constructor.concat(this,...n)}toJSON(n){const r=Object.create(null);return W.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=n&&W.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[Zb]=this[Zb]={accessors:{}}).accessors,i=this.prototype;function c(u){const f=Fi(u);s[f]||(sO(i,u),s[f]=!0)}return W.isArray(n)?n.forEach(c):c(n),this}};kn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);W.reduceDescriptors(kn.prototype,({value:t},n)=>{let r=n[0].toUpperCase()+n.slice(1);return{get:()=>t,set(s){this[r]=s}}});W.freezeMethods(kn);function Em(t,n){const r=this||fl,s=n||r,i=kn.from(s.headers);let c=s.data;return W.forEach(t,function(f){c=f.call(r,c,i.normalize(),n?n.status:void 0)}),i.normalize(),c}function y1(t){return!!(t&&t.__CANCEL__)}let ml=class extends Be{constructor(n,r,s){super(n??"canceled",Be.ERR_CANCELED,r,s),this.name="CanceledError",this.__CANCEL__=!0}};function b1(t,n,r){const s=r.config.validateStatus;!r.status||!s||s(r.status)?t(r):n(new Be("Request failed with status code "+r.status,[Be.ERR_BAD_REQUEST,Be.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function oO(t){const n=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return n&&n[1]||""}function iO(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(),y=s[c];u||(u=p),r[i]=g,s[i]=p;let v=c,w=0;for(;v!==i;)w+=r[v++],v=v%t;if(i=(i+1)%t,i===c&&(c=(c+1)%t),p-u<n)return;const C=y&&p-y;return C?Math.round(w*1e3/C):void 0}}function lO(t,n){let r=0,s=1e3/n,i,c;const u=(p,y=Date.now())=>{r=y,i=null,c&&(clearTimeout(c),c=null),t(...p)};return[(...p)=>{const y=Date.now(),v=y-r;v>=s?u(p,y):(i=p,c||(c=setTimeout(()=>{c=null,u(i)},s-v)))},()=>i&&u(i)]}const nu=(t,n,r=3)=>{let s=0;const i=iO(50,250);return lO(c=>{const u=c.loaded,f=c.lengthComputable?c.total:void 0,g=u-s,p=i(g),y=u<=f;s=u;const v={loaded:u,total:f,progress:f?u/f:void 0,bytes:g,rate:p||void 0,estimated:p&&f&&y?(f-u)/p:void 0,event:c,lengthComputable:f!=null,[n?"download":"upload"]:!0};t(v)},r)},Xb=(t,n)=>{const r=t!=null;return[s=>n[0]({lengthComputable:r,total:t,loaded:s}),n[1]]},Kb=t=>(...n)=>W.asap(()=>t(...n)),cO=mn.hasStandardBrowserEnv?((t,n)=>r=>(r=new URL(r,mn.origin),t.protocol===r.protocol&&t.host===r.host&&(n||t.port===r.port)))(new URL(mn.origin),mn.navigator&&/(msie|trident)/i.test(mn.navigator.userAgent)):()=>!0,uO=mn.hasStandardBrowserEnv?{write(t,n,r,s,i,c,u){if(typeof document>"u")return;const f=[`${t}=${encodeURIComponent(n)}`];W.isNumber(r)&&f.push(`expires=${new Date(r).toUTCString()}`),W.isString(s)&&f.push(`path=${s}`),W.isString(i)&&f.push(`domain=${i}`),c===!0&&f.push("secure"),W.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 dO(t){return typeof t!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function fO(t,n){return n?t.replace(/\/?\/$/,"")+"/"+n.replace(/^\/+/,""):t}function x1(t,n,r){let s=!dO(n);return t&&(s||r==!1)?fO(t,n):n}const Qb=t=>t instanceof kn?{...t}:t;function Es(t,n){n=n||{};const r={};function s(p,y,v,w){return W.isPlainObject(p)&&W.isPlainObject(y)?W.merge.call({caseless:w},p,y):W.isPlainObject(y)?W.merge({},y):W.isArray(y)?y.slice():y}function i(p,y,v,w){if(W.isUndefined(y)){if(!W.isUndefined(p))return s(void 0,p,v,w)}else return s(p,y,v,w)}function c(p,y){if(!W.isUndefined(y))return s(void 0,y)}function u(p,y){if(W.isUndefined(y)){if(!W.isUndefined(p))return s(void 0,p)}else return s(void 0,y)}function f(p,y,v){if(v in n)return s(p,y);if(v 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,y,v)=>i(Qb(p),Qb(y),v,!0)};return W.forEach(Object.keys({...t,...n}),function(y){if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=W.hasOwnProp(g,y)?g[y]:i,w=v(t[y],n[y],y);W.isUndefined(w)&&v!==f||(r[y]=w)}),r}const w1=t=>{const n=Es({},t);let{data:r,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:c,headers:u,auth:f}=n;if(n.headers=u=kn.from(u),n.url=g1(x1(n.baseURL,n.url,n.allowAbsoluteUrls),t.params,t.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):""))),W.isFormData(r)){if(mn.hasStandardBrowserEnv||mn.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if(W.isFunction(r.getHeader
Line truncated
|
||||
`+u.map(ax).join(`
|
||||
`):" "+ax(u[0]):"as no adapter specified";throw new Be("There is no suitable adapter to dispatch the request "+f,"ERR_NOT_SUPPORT")}return i}const E1={getAdapter:EO,adapters:Uh};function _m(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new ml(null,t)}function rx(t){return _m(t),t.headers=kn.from(t.headers),t.data=Em.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),E1.getAdapter(t.adapter||fl.adapter,t)(t).then(function(s){return _m(t),s.data=Em.call(t,t.transformResponse,s),s.headers=kn.from(s.headers),s},function(s){return y1(s)||(_m(t),s&&s.response&&(s.response.data=Em.call(t,t.transformResponse,s.response),s.response.headers=kn.from(s.response.headers))),Promise.reject(s)})}const _1="1.13.6",Du={};["object","boolean","number","function","string","symbol"].forEach((t,n)=>{Du[t]=function(s){return typeof s===t||"a"+(n<1?"n ":" ")+t}});const sx={};Du.transitional=function(n,r,s){function i(c,u){return"[Axios v"+_1+"] Transitional option '"+c+"'"+u+(s?". "+s:"")}return(c,u,f)=>{if(n===!1)throw new Be(i(u," has been removed"+(r?" in "+r:"")),Be.ERR_DEPRECATED);return r&&!sx[u]&&(sx[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}};Du.spelling=function(n){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${n}`),!0)};function _O(t,n,r){if(typeof t!="object")throw new Be("options must be an object",Be.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 Be("option "+c+" must be "+g,Be.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Be("Unknown option "+c,Be.ERR_BAD_OPTION)}}const Kc={assertOptions:_O,validators:Du},ra=Kc.validators;let Ss=class{constructor(n){this.defaults=n||{},this.interceptors={request:new Yb,response:new Yb}}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=Es(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:c}=r;s!==void 0&&Kc.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&&(W.isFunction(i)?r.paramsSerializer={serialize:i}:Kc.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),Kc.assertOptions(r,{baseUrl:ra.spelling("baseURL"),withXsrfToken:ra.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let u=c&&W.merge(c.common,c[r.method]);c&&W.forEach(["delete","get","head","post","put","patch","common"],S=>{delete c[S]}),r.headers=kn.concat(u,c);const f=[];let g=!0;this.interceptors.request.forEach(function(_){if(typeof _.runWhen=="function"&&_.runWhen(r)===!1)return;g=g&&_.synchronous;const E=r.transitional||zh;E&&E.legacyInterceptorReqResOrdering?f.unshift(_.fulfilled,_.rejected):f.push(_.fulfilled,_.rejected)});const p=[];this.interceptors.response.forEach(function(_){p.push(_.fulfilled,_.rejected)});let y,v=0,w;if(!g){const S=[rx.bind(this),void 0];for(S.unshift(...f),S.push(...p),w=S.length,y=Promise.resolve(r);v<w;)y=y.then(S[v++],S[v++]);return y}w=f.length;let C=r;for(;v<w;){const S=f[v++],_=f[v++];try{C=S(C)}catch(E){_.call(this,E);break}}try{y=rx.call(this,C)}catch(S){return Promise.reject(S)}for(v=0,w=p.length;v<w;)y=y.then(p[v++],p[v++]);return y}getUri(n){n=Es(this.defaults,n);const r=x1(n.baseURL,n.url,n.allowAbsoluteUrls);return g1(r,n.params,n.paramsSerializer)}};W.forEach(["delete","get","head","options"],function(n){Ss.prototype[n]=function(r,s){return this.request(Es(s||{},{method:n,url:r,data:(s||{}).data}))}});W.forEach(["post","put","patch"],function(n){function r(s){return function(c,u,f){return this.request(Es(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 CO=class C1{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 ml(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 C1(function(i){n=i}),cancel:n}}};function NO(t){return function(r){return t.apply(null,r)}}function RO(t){return W.isObject(t)&&t.isAxiosError===!0}const nh={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(nh).forEach(([t,n])=>{nh[n]=t});function N1(t){const n=new Ss(t),r=s1(Ss.prototype.request,n);return W.extend(r,Ss.prototype,n,{allOwnKeys:!0}),W.extend(r,n,null,{allOwnKeys:!0}),r.create=function(i){return N1(Es(t,i))},r}const Bt=N1(fl);Bt.Axios=Ss;Bt.CanceledError=ml;Bt.CancelToken=CO;Bt.isCancel=y1;Bt.VERSION=_1;
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 JO=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ej=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),ix=t=>{const n=ej(t);return n.charAt(0).toUpperCase()+n.slice(1)},j1=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),tj=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 nj={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 aj=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,...nj,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:j1("lucide",i),...!c&&!tj(f)&&{"aria-hidden":"true"},...f},[...u.map(([p,y])=>b.createElement(p,y)),...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 rj=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(aj,{ref:c,iconNode:n,className:j1(`lucide-${JO(ix(t))}`,`lucide-${t}`,s),...i}));return r.displayName=ix(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 sj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],oj=rj("x",sj),lx=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,cx=Oh,Ph=(t,n)=>r=>{var s;if((n==null?void 0:n.variants)==null)return cx(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 y=r==null?void 0:r[p],v=c==null?void 0:c[p];if(y===null)return null;const w=lx(y)||lx(v);return i[p][w]}),f=r&&Object.entries(r).reduce((p,y)=>{let[v,w]=y;return w===void 0||(p[v]=w),p},{}),g=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((p,y)=>{let{class:v,className:w,...C}=y;return Object.entries(C).every(S=>{let[_,E]=S;return Array.isArray(E)?E.includes({...c,...f}[_]):{...c,...f}[_]===E})?[...p,v,w]:p},[]);return cx(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 ij(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 lj="DismissableLayer",ah="dismissableLayer.update",cj="dismissableLayer.pointerDownOutside",uj="dismissableLayer.focusOutside",ux,k1=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Lu=b.forwardRef((t,n)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:c,onInteractOutside:u,onDismiss:f,...g}=t,p=b.useContext(k1),[y,v]=b.useState(null),w=(y==null?void 0:y.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,C]=b.useState({}),S=Wt(n,U=>v(U)),_=Array.from(p.layers),[E]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),R=_.indexOf(E),k=y?_.indexOf(y):-1,A=p.layersWithOutsidePointerEventsDisabled.size>0,D=k>=R,H=mj(U=>{const F=U.target,de=[...p.branches].some(fe=>fe.contains(F));!D||de||(i==null||i(U),u==null||u(U),U.defaultPrevented||f==null||f())},w),$=hj(U=>{const F=U.target;[...p.branches].some(fe=>fe.contains(F))||(c==null||c(U),u==null||u(U),U.defaultPrevented||f==null||f())},w);return ij(U=>{k===p.layers.size-1&&(s==null||s(U),!U.defaultPrevented&&f&&(U.preventDefault(),f()))},w),b.useEffect(()=>{if(y)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(ux=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),dx(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=ux)}},[y,w,r,p]),b.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),dx())},[y,p]),b.useEffect(()=>{const U=()=>C({});return document.addEventListener(ah,U),()=>document.removeEventListener(ah,U)},[]),h.jsx(kt.div,{...g,ref:S,style:{pointerEvents:A?D?"auto":"none":void 0,...t.style},onFocusCapture:qe(t.onFocusCapture,$.onFocusCapture),onBlurCapture:qe(t.onBlurCapture,$.onBlurCapture),onPointerDownCapture:qe(t.onPointerDownCapture,H.onPointerDownCapture)})});Lu.displayName=lj;var dj="DismissableLayerBranch",fj=b.forwardRef((t,n)=>{const r=b.useContext(k1),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]),h.jsx(kt.div,{...t,ref:i})});fj.displayName=dj;function mj(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(){M1(cj,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 hj(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&&M1(uj,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 dx(){const t=new CustomEvent(ah);document.dispatchEvent(t)}function M1(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?T1(i,c):i.dispatchEvent(c)}var Cm="focusScope.autoFocusOnMount",Nm="focusScope.autoFocusOnUnmount",fx={bubbles:!1,cancelable:!0},pj="FocusScope",Uu=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),y=sr(c),v=b.useRef(null),w=Wt(n,_=>g(_Line truncated
|
||||
.`.concat(_j,` {
|
||||
overflow: hidden `).concat(s,`;
|
||||
padding-right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
body[`).concat(Oo,`] {
|
||||
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(Qc,` {
|
||||
right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(Wc,` {
|
||||
margin-right: `).concat(f,"px ").concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(Qc," .").concat(Qc,` {
|
||||
right: 0 `).concat(s,`;
|
||||
}
|
||||
|
||||
.`).concat(Wc," .").concat(Wc,` {
|
||||
margin-right: 0 `).concat(s,`;
|
||||
}
|
||||
|
||||
body[`).concat(Oo,`] {
|
||||
`).concat(Cj,": ").concat(f,`px;
|
||||
}
|
||||
`)},yx=function(){var t=parseInt(document.body.getAttribute(Oo)||"0",10);return isFinite(t)?t:0},Fj=function(){b.useEffect(function(){return document.body.setAttribute(Oo,(yx()+1).toString()),function(){var t=yx()-1;t<=0?document.body.removeAttribute(Oo):document.body.setAttribute(Oo,t.toString())}},[])},$j=function(t){var n=t.noRelative,r=t.noImportant,s=t.gapMode,i=s===void 0?"margin":s;Fj();var c=b.useMemo(function(){return Vj(i)},[i]);return b.createElement(Ij,{styles:qj(c,!n,i,r?"":"!important")})},rh=!1;if(typeof window<"u")try{var Bc=Object.defineProperty({},"passive",{get:function(){return rh=!0,!0}});window.addEventListener("test",Bc,Bc),window.removeEventListener("test",Bc,Bc)}catch{rh=!1}var bo=rh?{passive:!1}:!1,Gj=function(t){return t.tagName==="TEXTAREA"},P1=function(t,n){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[n]!=="hidden"&&!(r.overflowY===r.overflowX&&!Gj(t)&&r[n]==="visible")},Yj=function(t){return P1(t,"overflowY")},Zj=function(t){return P1(t,"overflowX")},bx=function(t,n){var r=n.ownerDocument,s=n;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var i=H1(t,s);if(i){var c=V1(t,s),u=c[1],f=c[2];if(u>f)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},Xj=function(t){var n=t.scrollTop,r=t.scrollHeight,s=t.clientHeight;return[n,r,s]},Kj=function(t){var n=t.scrollLeft,r=t.scrollWidth,s=t.clientWidth;return[n,r,s]},H1=function(t,n){return t==="v"?Yj(n):Zj(n)},V1=function(t,n){return t==="v"?Xj(n):Kj(n)},Qj=function(t,n){return t==="h"&&n==="rtl"?-1:1},Wj=function(t,n,r,s,i){var c=Qj(t,window.getComputedStyle(n).direction),u=c*s,f=r.target,g=n.contains(f),p=!1,y=u>0,v=0,w=0;do{if(!f)break;var C=V1(t,f),S=C[0],_=C[1],E=C[2],R=_-E-c*S;(S||R)&&H1(t,f)&&(v+=R,w+=S);var k=f.parentNode;f=k&&k.nodeType===Node.DOCUMENT_FRAGMENT_NODE?k.host:k}while(!g&&f!==document.body||g&&(n.contains(f)||n===f));return(y&&Math.abs(v)<1||!y&&Math.abs(w)<1)&&(p=!0),p},Pc=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},xx=function(t){return[t.deltaX,t.deltaY]},wx=function(t){return t&&"current"in t?t.current:t},Jj=function(t,n){return t[0]===n[0]&&t[1]===n[1]},ek=function(t){return`
|
||||
.block-interactivity-`.concat(t,` {pointer-events: none;}
|
||||
.allow-interactivity-`).concat(t,` {pointer-events: all;}
|
||||
`)},tk=0,xo=[];function nk(t){var n=b.useRef([]),r=b.useRef([0,0]),s=b.useRef(),i=b.useState(tk++)[0],c=b.useState(B1)[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 _=Ej([t.lockRef.current],(t.shards||[]).map(wx),!0).filter(Boolean);return _.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),_.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var f=b.useCallback(function(_,E){if("touches"in _&&_.touches.length===2||_.type==="wheel"&&_.ctrlKey)return!u.current.allowPinchZoom;var R=Pc(_),k=r.current,A="deltaX"in _?_.deltaX:k[0]-R[0],D="deltaY"in _?_.deltaY:k[1]-R[1],H,$=_.target,U=Math.abs(A)>Math.abs(D)?"h":"v";if("touches"in _&&U==="h"&&$.type==="range")return!1;var F=window.getSelection(),de=F&&F.anchorNode,fe=de?de===$||de.contains($):!1;if(fe)return!1;var me=bx(U,$);if(!me)return!0;if(me?H=U:(H=U==="v"?"h":"v",me=bx(U,$)),!me)return!1;if(!s.current&&"changedTouches"in _&&(A||D)&&(s.current=H),!H)return!0;var se=s.current||H;return Wj(se,E,_,se==="h"?A:D)},[]),g=b.useCallback(function(_){var E=_;if(!(!xo.length||xo[xo.length-1]!==c)){var R="deltaY"in E?xx(E):Pc(E),k=n.current.filter(function(H){return H.name===E.type&&(H.target===E.target||E.target===H.shadowParent)&&Jj(H.delta,R)})[0];if(k&&k.should){E.cancelable&&E.preventDefault();return}if(!k){var A=(u.current.shards||[]).map(wx).filter(Boolean).filter(function(H){return H.contains(E.target)}),D=A.length>0?f(E,A[0]):!u.current.noIsolation;D&&E.cancelable&&E.preventDefault()}}},[]),p=b.useCallback(function(_,E,R,k){var A={name:_,delta:E,target:R,should:k,shadowParent:ak(R)};n.current.push(A),setTimeout(function(){n.current=n.current.filter(function(D){return D!==A})},1)},[]),y=b.useCallback(function(_){r.current=Pc(_),s.current=void 0},[]),v=b.useCallback(function(_){p(_.type,xx(_),_.target,f(_,t.lockRef.current))},[]),w=b.useCallback(function(_){p(_.type,Pc(_),_.target,f(_,t.lockRef.current))},[]);b.useEffect(function(){return xo.push(c),t.setCallbacks({onScrollCapture:v,onWheelCapture:v,onTouchMoveCapture:w}),document.addEventListener("wheel",g,bo),document.addEventListener("touchmove",g,bo),document.addEventListener("touchstart",y,bo),function(){xo=xo.filter(function(_){return _!==c}),document.removeEventListener("wheel",g,bo),document.removeEventListener("touchmove",g,bo),document.removeEventListener("touchstart",y,bo)}},[]);var C=t.removeScrollBar,S=t.inert;return b.createElement(b.Fragment,null,S?b.createElement(c,{styles:ek(i)}):null,C?b.createElement($j,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function ak(t){for(var n=null;t!==null;)t instanceof ShadowRoot&&(n=t.host,t=t.host),t=t.parentNode;return n}const rk=kj(U1,nk);var Hu=b.forwardRef(function(t,n){return b.createElement(Pu,Aa({},t,{ref:n,sideCar:rk}))});Hu.classNames=Pu.classNames;var sk=function(t){if(typeof document>"u")return null;var n=Array.isArray(t)?t[0]:t;return n.ownerDocument.body},wo=new WeakMap,Hc=new WeakMap,Vc={},jm=0,I1=function(t){return t&&(t.host||I1(t.parentNode))},ok=function(t,n){return n.map(function(r){if(t.contains(r))return r;var s=I1(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})},ik=function(t,n,r,s){var i=ok(n,Array.isArray(t)?t:[t]);Vc[r]||(Vc[r]=new WeakMap);var c=Vc[r],u=[],f=new Set,g=new Set(i),p=function(v){!v||f.has(v)||(f.add(v),p(v.parentNode))};i.forEach(p);var y=function(v){!v||g.has(v)||Array.prototype.forEach.call(v.children,function(w){if(f.has(w))y(w);else try{var C=w.getAttribute(s),S=C!==null&&C!=="false",_=(wo.get(w)||0)+1,E=(c.get(w)||0)+1;wo.set(w,_),c.set(w,E),u.push(w),_===1&&S&&Hc.set(w,!0),E===1&&w.setAttribute(r,"true"),S||w.setAttribute(s,"true")}catch(R){console.error("aria-hidden: cannot operate on ",w,R)}})};return y(n),f.clear(),jm++,function(){u.forEach(function(v){var w=wo.get(v)-1,C=c.get(v)-1;wo.set(v,w),c.set(v,C),w||(Hc.has(v)||v.removeAttribute(s),Hc.delete(v)),C||v.removeAttribute(r)}),jm--,jm||(wo=new WeakMap,wo=new WeakMap,Hc=new WeakMap,Vc={})}},Vh=function(t,n,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(t)?t:[t]),i=sk(t);return i?(s.push.apply(s,Array.from(i.querySelectorAll("[aria-live], script"))),ik(s,i,r,"aria-hidden")):function(){return null}},Vu="Dialog",[q1]=Ts(Vu),[lk,ba]=q1(Vu),F1=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,y]=Bh({prop:s,defaultProp:i??!1,onChange:c,caller:Vu});return h.jsx(lk,{scope:n,triggerRef:f,contentRef:g,contentId:To(),titleId:To(),descriptionId:To(),open:p,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(v=>!v),[y]),modal:u,children:r})};F1.displayName=Vu;var $1="DialogTrigger",ck=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},gk="DialogDescriptionWarning",vk=({contentRef:t,descriptionId:n})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${aw(gk).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},yk=F1,bk=Y1,rw=Z1,sw=X1,xk=Q1,wk=J1,Sk=tw,Ek=Symbol.for("react.lazy"),ru=Nu[" use ".trim().toString()];function _k(t){return typeof t=="object"&&t!==null&&"then"in t}function ow(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===Ek&&"_payload"in t&&_k(t._payload)}function iw(t){const n=Ck(t),r=b.forwardRef((s,i)=>{let{children:c,...u}=s;ow(c)&&typeof ru=="function"&&(c=ru(c._payload));const f=b.Children.toArray(c),g=f.find(Rk);if(g){const p=g.props.children,y=f.map(v=>v===g?b.Children.count(p)>1?b.Children.only(null):b.isValidElement(p)?p.props.children:null:v);return h.jsx(n,{...u,ref:i,children:b.isValidElement(p)?b.cloneElement(p,void 0,y):null})}return h.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}var lw=iw("Slot");function Ck(t){const n=b.forwardRef((r,s)=>{let{children:i,...c}=r;if(ow(i)&&typeof ru=="function"&&(i=ru(i._payload)),b.isValidElement(i)){const u=Tk(i),f=Ak(c,i.props);return i.type!==b.Fragment&&(f.ref=s?hl(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 Nk=Symbol("radix.slottable");function Rk(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Nk}function Ak(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 Tk(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 Ok=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],jk=Ok.reduce((t,n)=>{const r=iw(`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),h.jsx(g,{...f,ref:c})});return s.displayName=`Primitive.${n}`,{...t,[n]:s}},{});function kk(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 Mk=["top","right","bottom","left"],$r=Math.min,In=Math.max,su=Math.round,Ic=Math.floor,ka=t=>({x:t,y:t}),Dk={left:"right",right:"left",bottom:"top",top:"bottom"};function sh(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 Yo(t){return t.split("-")[1]}function $h(t){return t==="x"?"y":"x"}function Gh(t){return t==="y"?"height":"width"}function Oa(t){const n=t[0];return n==="t"||n==="b"?"y":"x"}function Yh(t){return $h(Oa(t))}function zk(t,n,r){r===void 0&&(r=!1);const s=Yo(t),i=Yh(t),c=Gh(i);let u=i==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return n.reference[c]>n.floating[c]&&(u=ou(u)),[u,ou(u)]}function Lk(t){const n=ou(t);return[oh(t),n,oh(n)]}function oh(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}const Sx=["left","right"],Ex=["right","left"],Uk=["top","bottom"],Bk=["bottom","top"];function Pk(t,n,r){switch(t){case"top":case"bottom":return r?n?Ex:Sx:n?Sx:Ex;case"left":case"right":return n?Uk:Bk;default:return[]}}function Hk(t,n,r,s){const i=Yo(t);let c=Pk(ir(t),r==="start",s);return i&&(c=c.map(u=>u+"-"+i),n&&(c=c.concat(c.map(oh)))),c}function ou(t){const n=ir(t);return Dk[n]+t.slice(n.length)}function Vk(t){return{top:0,right:0,bottom:0,left:0,...t}}function cw(t){return typeof t!="number"?Vk(t):{top:t,right:t,bottom:t,left:t}}function iu(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 _x(t,n,r){let{reference:s,floating:i}=t;const c=Oa(n),u=Yh(n),f=Gh(u),g=ir(n),p=c==="y",y=s.x+s.width/2-i.width/2,v=s.y+s.height/2-i.height/2,w=s[f]/2-i[f]/2;let C;switch(g){case"top":C={x:y,y:s.y-i.height};break;case"bottom":C={x:y,y:s.y+s.height};break;case"right":C={x:s.x+s.width,y:v};break;case"left":C={x:s.x-i.width,y:v};
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 XD(t,n){typeof t=="function"?t(n):t!=null&&(t.current=n)}function KD(...t){return n=>t.forEach(r=>XD(r,n))}function iS(...t){return b.useCallback(KD(...t),t)}const Dx=t=>{switch(t){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return t}};function Lm(t,n){if(!t)return()=>{};const r=t.style.cssText;return Object.assign(t.style,n),()=>{t.style.cssText=r}}function QD(...t){return(...n)=>{for(const r of t)typeof r=="function"&&r(...n)}}const Um={DURATION:.5,EASE:[.32,.72,0,1]},WD=8,JD=26,e4=()=>()=>{};function t4(){const{direction:t,isOpen:n,shouldScaleBackground:r,setBackgroundColorOnScale:s,noBodyStyles:i}=Xu(),c=ae.useRef(null),u=b.useMemo(()=>document.body.style.backgroundColor,[]);function f(){return(window.innerWidth-JD)/window.innerWidth}ae.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;QD(s&&!i?Lm(document.body,{background:"black"}):e4,Lm(g,{transformOrigin:Dx(t)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Um.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Um.EASE.join(",")})`}));const p=Lm(g,{borderRadius:`${WD}px`,overflow:"hidden",...Dx(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")},Um.DURATION*1e3)}}},[n,r,u])}const n4=ae.forwardRef(function({...t},n){const{overlayRef:r,snapPoints:s,onRelease:i,shouldFade:c,isOpen:u,modal:f,shouldAnimate:g}=Xu(),p=iS(n,r),y=s&&s.length>0;if(!f)return null;const v=ae.useCallback(w=>i(w),[i]);return ae.createElement(rw,{onMouseUp:v,ref:p,"data-vaul-overlay":"","data-vaul-snap-points":u&&y?"true":"false","data-vaul-snap-points-overlay":u&&c?"true":"false","data-vaul-animate":g!=null&&g.current?"true":"false",...t})});n4.displayName="Drawer.Overlay";const a4=ae.forwardRef(function({onPointerDownOutside:t,style:n,onOpenAutoFocus:r,...s},i){const{drawerRef:c,onPress:u,onRelease:f,onDrag:g,keyboardIsOpen:p,snapPointsOffset:y,activeSnapPointIndex:v,modal:w,isOpen:C,direction:S,snapPoints:_,container:E,handleOnly:R,shouldAnimate:k,autoFocus:A}=Xu(),[D,H]=ae.useState(!1),$=iS(i,c),U=ae.useRef(null),F=ae.useRef(null),de=ae.useRef(!1),fe=_&&_.length>0;t4();const me=(G,he,ve=0)=>{if(de.current)return!0;const T=Math.abs(G.y),K=Math.abs(G.x),te=K>T,le=["bottom","right"].includes(he)?1:-1;if(he==="left"||he==="right"){if(!(G.x*le<0)&&K>=0&&K<=ve)return te}else if(!(G.y*le<0)&&T>=0&&T<=ve)return!te;return de.current=!0,!0};ae.useEffect(()=>{fe&&window.requestAnimationFrame(()=>{H(!0)})},[]);function se(G){U.current=null,de.current=!1,f(G)}return ae.createElement(sw,{"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":E?"true":"false","data-vaul-animate":k!=null&&k.current?"true":"false",...s,ref:$,style:y&&y.length>0?{"--snap-point-height":`${y[v??0]}px`,...n}:n,onPointerDown:G=>{R||(s.onPointerDown==null||s.onPointerDown.call(s,G),U.current={x:G.pageX,y:G.pageY},u(G))},onOpenAutoFocus:G=>{r==null||r(G),A||G.preventDefault()},onPointerDownOutside:G=>{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;
|
||||
}
|
||||
}`,TS="Popover",[OS]=Ts(TS,[Gu]),Wu=Gu(),[cL,Qr]=OS(TS),jS="PopoverAnchor",wz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(jS,r),c=Wu(r),{onCustomAnchorAdd:u,onCustomAnchorRemove:f}=i;return b.useEffect(()=>(u(),()=>f()),[u,f]),h.jsx(Jh,{...c,...s,ref:n})});wz.displayName=jS;var kS="PopoverTrigger",Sz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(kS,r),c=Wu(r),u=Wt(n,i.triggerRef),f=h.jsx(kt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":US(i.open),...s,ref:u,onClick:qe(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?f:h.jsx(Jh,{asChild:!0,...c,children:f})});Sz.displayName=kS;var mp="PopoverPortal",[Ez,_z]=OS(mp,{forceMount:void 0}),MS=t=>{const{__scopePopover:n,forceMount:r,children:s,container:i}=t,c=Qr(mp,n);return h.jsx(Ez,{scope:n,forceMount:r,children:h.jsx(za,{present:r||c.open,children:h.jsx(Bu,{asChild:!0,container:i,children:s})})})};MS.displayName=mp;var Uo="PopoverContent",DS=b.forwardRef((t,n)=>{const r=_z(Uo,t.__scopePopover),{forceMount:s=r.forceMount,...i}=t,c=Qr(Uo,t.__scopePopover);return h.jsx(za,{present:s||c.open,children:c.modal?h.jsx(Nz,{...i,ref:n}):h.jsx(Rz,{...i,ref:n})})});DS.displayName=Uo;var Cz=Do("PopoverContent.RemoveScroll"),Nz=b.forwardRef((t,n)=>{const r=Qr(Uo,t.__scopePopover),s=b.useRef(null),i=Wt(n,s),c=b.useRef(!1);return b.useEffect(()=>{const u=s.current;if(u)return Vh(u)},[]),h.jsx(Hu,{as:Cz,allowPinchZoom:!0,children:h.jsx(zS,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:qe(t.onCloseAutoFocus,u=>{var f;u.preventDefault(),c.current||(f=r.triggerRef.current)==null||f.focus()}),onPointerDownOutside:qe(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:qe(t.onFocusOutside,u=>u.preventDefault(),{checkForDefaultPrevented:!1})})})}),Rz=b.forwardRef((t,n)=>{const r=Qr(Uo,t.__scopePopover),s=b.useRef(!1),i=b.useRef(!1);return h.jsx(zS,{...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()}})}),zS=b.forwardRef((t,n)=>{const{__scopePopover:r,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:c,disableOutsidePointerEvents:u,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:p,onInteractOutside:y,...v}=t,w=Qr(Uo,r),C=Wu(r);return Hh(),h.jsx(Uu,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:i,onUnmountAutoFocus:c,children:h.jsx(Lu,{asChild:!0,disableOutsidePointerEvents:u,onInteractOutside:y,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:p,onDismiss:()=>w.onOpenChange(!1),children:h.jsx(Ow,{"data-state":US(w.open),role:"dialog",id:w.contentId,...C,...v,ref:n,style:{...v.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)"}})})})}),LS="PopoverClose",Az=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(LS,r);return h.jsx(kt.button,{type:"button",...s,ref:n,onClick:qe(t.onClick,()=>i.onOpenChange(!1))})});Az.displayName=LS;var Tz="PopoverArrow",Oz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Wu(r);return h.jsx(jw,{...i,...s,ref:n})});Oz.displayName=Tz;function US(t){return t?"open":"closed"}var jz=MS,BS=DS;const hp=b.createContext(null);hp.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"},pp=10,ko=b.useLayoutEffect,Yx=Nu.useId,kz=typeof Yx=="function"?Yx:()=>null;let Mz=0;function PS(t=null){const n=kz(),r=b.useRef(t||n||null);return r.current===null&&(r.current=""+Mz++),t??r.current}function HS({children:t,className:n="",collapsedSize:r,collapsible:s,defaultSize:i,forwardedRef:c,id:u,maxSize:f,minSize:g,onCollapse:p,onExpand:y,onResize:v,order:w,style:C,tagName:S="div",..._}){const E=b.useContext(hp);if(E===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:R,expandPanel:k,getPanelSize:A,getPanelStyle:D,groupId:H,isPanelCollapsed:$,reevaluatePanelConstraints:U,registerPanel:F,resizeP
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-CRnVAbpY.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-BsMXpWP7.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
package call_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type CallHandler interface {
|
||||
RejectCall(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type callHandler struct {
|
||||
callService call_service.CallService
|
||||
}
|
||||
|
||||
// Reject call
|
||||
// @Summary Reject call
|
||||
// @Description Reject call
|
||||
// @Tags Call
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body call_service.RejectCallStruct true "Call data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /call/reject [post]
|
||||
func (g *callHandler) RejectCall(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *call_service.RejectCallStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.callService.RejectCall(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
func NewCallHandler(
|
||||
callService call_service.CallService,
|
||||
) CallHandler {
|
||||
return &callHandler{
|
||||
callService: callService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package call_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"github.com/gomessguii/logger"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type CallService interface {
|
||||
RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error
|
||||
}
|
||||
|
||||
type callService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type RejectCallStruct struct {
|
||||
CallCreator types.JID `json:"callCreator"`
|
||||
CallID string `json:"callId"`
|
||||
}
|
||||
|
||||
func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := c.clientPointer[instanceId]
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := c.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = c.clientPointer[instanceId]
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = client.RejectCall(context.Background(), data.CallCreator, data.CallID)
|
||||
if err != nil {
|
||||
logger.LogError("[%s] error reject call: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewCallService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) CallService {
|
||||
return &callService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
package chat_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ChatHandler interface {
|
||||
ChatPin(ctx *gin.Context)
|
||||
ChatUnpin(ctx *gin.Context)
|
||||
ChatArchive(ctx *gin.Context)
|
||||
ChatUnarchive(ctx *gin.Context)
|
||||
ChatMute(ctx *gin.Context)
|
||||
ChatUnmute(ctx *gin.Context)
|
||||
HistorySyncRequest(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type chatHandler struct {
|
||||
chatService chat_service.ChatService
|
||||
}
|
||||
|
||||
// Pin a chat
|
||||
// @Summary Pin a chat
|
||||
// @Description Pin a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/pin [post]
|
||||
func (c *chatHandler) ChatPin(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatPin(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Unpin a chat
|
||||
// @Summary Unpin a chat
|
||||
// @Description Unpin a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/unpin [post]
|
||||
func (c *chatHandler) ChatUnpin(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatUnpin(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Archive a chat
|
||||
// @Summary Archive a chat
|
||||
// @Description Archive a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/archive [post]
|
||||
func (c *chatHandler) ChatArchive(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatArchive(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Unarchive a chat
|
||||
// @Summary Unarchive a chat
|
||||
// @Description Unarchive a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/unarchive [post]
|
||||
func (c *chatHandler) ChatUnarchive(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatUnarchive(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Mute a chat
|
||||
// @Summary Mute a chat
|
||||
// @Description Mute a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/mute [post]
|
||||
func (c *chatHandler) ChatMute(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatMute(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Unmute a chat
|
||||
// @Summary Unmute a chat
|
||||
// @Description Unmute a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.BodyStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/unmute [post]
|
||||
func (c *chatHandler) ChatUnmute(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.BodyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := c.chatService.ChatUnmute(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// HistorySyncRequest a chat
|
||||
// @Summary HistorySyncRequest a chat
|
||||
// @Description HistorySyncRequest a chat
|
||||
// @Tags Chat
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body chat_service.HistorySyncRequestStruct true "Chat"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /chat/history-sync-request [post]
|
||||
func (c *chatHandler) HistorySyncRequest(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *chat_service.HistorySyncRequestStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := c.chatService.HistorySyncRequest(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
func NewChatHandler(
|
||||
chatService chat_service.ChatService,
|
||||
) ChatHandler {
|
||||
return &chatHandler{
|
||||
chatService: chatService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package chat_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/appstate"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type ChatService interface {
|
||||
ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
||||
HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error)
|
||||
}
|
||||
|
||||
type chatService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type BodyStruct struct {
|
||||
Chat string `json:"chat"`
|
||||
}
|
||||
|
||||
type HistorySyncRequestStruct struct {
|
||||
MessageInfo *types.MessageInfo `json:"messageInfo"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := c.clientPointer[instanceId]
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := c.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = c.clientPointer[instanceId]
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, true))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error pin chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, false))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unpin chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, true, time.Time{}, nil))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error archive chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, false, time.Time{}, nil))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unarchive chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, true, 1*time.Hour))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, false, 0*time.Hour))
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmute chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
messageInfo := types.MessageInfo{
|
||||
MessageSource: types.MessageSource{
|
||||
Chat: data.MessageInfo.Chat,
|
||||
IsFromMe: data.MessageInfo.IsFromMe,
|
||||
IsGroup: data.MessageInfo.IsGroup,
|
||||
},
|
||||
ID: data.MessageInfo.ID,
|
||||
Timestamp: data.MessageInfo.Timestamp,
|
||||
}
|
||||
|
||||
histRequest := client.BuildHistorySyncRequest(&messageInfo, data.Count)
|
||||
|
||||
res, err := client.SendMessage(context.Background(), messageInfo.Chat, histRequest, whatsmeow.SendRequestExtra{Peer: true})
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error history sync request: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
func NewChatService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) ChatService {
|
||||
return &chatService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package community_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type CommunityHandler interface {
|
||||
CreateCommunity(ctx *gin.Context)
|
||||
CommunityAdd(ctx *gin.Context)
|
||||
CommunityRemove(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type communityHandler struct {
|
||||
communityService community_service.CommunityService
|
||||
}
|
||||
|
||||
// Create community
|
||||
// @Summary Create community
|
||||
// @Description Create community
|
||||
// @Tags Community
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body community_service.CreateCommunityStruct true "Community data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /community/create [post]
|
||||
func (c *communityHandler) CreateCommunity(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *community_service.CreateCommunityStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.CommunityName == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
community, err := c.communityService.CreateCommunity(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": community})
|
||||
}
|
||||
|
||||
// Add participant to community
|
||||
// @Summary Add participant to community
|
||||
// @Description Add participant to community
|
||||
// @Tags Community
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body community_service.AddParticipantStruct true "Participant data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /community/add [post]
|
||||
func (c *communityHandler) CommunityAdd(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *community_service.AddParticipantStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.CommunityJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.GroupJID) == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := c.communityService.CommunityAdd(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Remove participant from community
|
||||
// @Summary Remove participant from community
|
||||
// @Description Remove participant from community
|
||||
// @Tags Community
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body community_service.AddParticipantStruct true "Participant data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /community/remove [post]
|
||||
func (c *communityHandler) CommunityRemove(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *community_service.AddParticipantStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.CommunityJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.GroupJID) == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := c.communityService.CommunityRemove(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
func NewCommunityHandler(
|
||||
communityService community_service.CommunityService,
|
||||
) CommunityHandler {
|
||||
return &communityHandler{
|
||||
communityService: communityService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package community_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type CommunityService interface {
|
||||
CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error)
|
||||
CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
|
||||
CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
|
||||
}
|
||||
|
||||
type communityService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type CreateCommunityStruct struct {
|
||||
CommunityName string `json:"communityName"`
|
||||
}
|
||||
|
||||
type AddParticipantStruct struct {
|
||||
CommunityJID string `json:"communityJid"`
|
||||
GroupJID []string `json:"groupJid"`
|
||||
}
|
||||
|
||||
func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := c.clientPointer[instanceId]
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := c.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = c.clientPointer[instanceId]
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *communityService) CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{
|
||||
Name: data.CommunityName,
|
||||
GroupParent: types.GroupParent{
|
||||
IsParent: true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create community: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (c *communityService) CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
communityJID, ok := utils.ParseJID(data.CommunityJID)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return nil, errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
var successList []string
|
||||
var failedList []string
|
||||
|
||||
for _, participant := range data.GroupJID {
|
||||
groupJID, _ := utils.ParseJID(participant)
|
||||
err := client.LinkGroup(context.Background(), communityJID, groupJID)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
|
||||
failedList = append(failedList, groupJID.String())
|
||||
}
|
||||
successList = append(failedList, groupJID.String())
|
||||
}
|
||||
|
||||
return gin.H{
|
||||
"success": successList,
|
||||
"failed": failedList,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
|
||||
client, err := c.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
communityJID, ok := utils.ParseJID(data.CommunityJID)
|
||||
if !ok {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return nil, errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
var successList []string
|
||||
var failedList []string
|
||||
|
||||
for _, participant := range data.GroupJID {
|
||||
groupJID, _ := utils.ParseJID(participant)
|
||||
err := client.UnlinkGroup(context.Background(), communityJID, groupJID)
|
||||
if err != nil {
|
||||
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
|
||||
failedList = append(failedList, groupJID.String())
|
||||
}
|
||||
successList = append(failedList, groupJID.String())
|
||||
}
|
||||
|
||||
return gin.H{
|
||||
"success": successList,
|
||||
"failed": failedList,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func NewCommunityService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) CommunityService {
|
||||
return &communityService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gomessguii/logger"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
|
||||
config_env "github.com/EvolutionAPI/evolution-go/pkg/config/env"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
PostgresAuthDB string
|
||||
postgresUsersDB string
|
||||
PostgresHost string
|
||||
PostgresPort string
|
||||
PostgresUser string
|
||||
PostgresPassword string
|
||||
PostgresDB string
|
||||
DatabaseSaveMessages bool
|
||||
GlobalApiKey string
|
||||
WaDebug string
|
||||
LogType string
|
||||
WebhookFiles bool
|
||||
ConnectOnStartup bool
|
||||
OsName string
|
||||
AmqpUrl string
|
||||
AmqpGlobalEnabled bool
|
||||
WebhookUrl string
|
||||
ClientName string
|
||||
ApiAudioConverter string
|
||||
ApiAudioConverterKey string
|
||||
MinioEndpoint string
|
||||
MinioAccessKey string
|
||||
MinioSecretKey string
|
||||
MinioBucket string
|
||||
MinioUseSSL bool
|
||||
MinioEnabled bool
|
||||
MinioRegion string
|
||||
WhatsappVersionMajor int
|
||||
WhatsappVersionMinor int
|
||||
WhatsappVersionPatch int
|
||||
ProxyHost string
|
||||
ProxyPort string
|
||||
ProxyUsername string
|
||||
ProxyPassword string
|
||||
AmqpGlobalEvents []string
|
||||
AmqpSpecificEvents []string
|
||||
NatsUrl string
|
||||
NatsGlobalEnabled bool
|
||||
NatsGlobalEvents []string
|
||||
EventIgnoreGroup bool
|
||||
EventIgnoreStatus bool
|
||||
QrcodeMaxCount int
|
||||
CheckUserExists bool
|
||||
|
||||
// Logger configurations
|
||||
LogMaxSize int
|
||||
LogMaxBackups int
|
||||
LogMaxAge int
|
||||
LogDirectory string
|
||||
LogCompress bool
|
||||
|
||||
}
|
||||
|
||||
// EnsureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.
|
||||
func (c *Config) EnsureDBExists(dsn string) error {
|
||||
return ensureDBExists(dsn)
|
||||
}
|
||||
|
||||
// ensureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.
|
||||
func ensureDBExists(dsn string) error {
|
||||
dbName, adminDSN, err := extractDBNameAndAdminDSN(dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
db, err := sql.Open("postgres", adminDSN)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to postgres for auto-setup: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
var exists bool
|
||||
err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", dbName).Scan(&exists)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check database existence: %v", err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
logger.LogInfo("[CONFIG] Database %q not found, creating it automatically...", dbName)
|
||||
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE %q", dbName))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create database %q: %v", dbName, err)
|
||||
}
|
||||
logger.LogInfo("[CONFIG] Database %q created successfully", dbName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractDBNameAndAdminDSN parses a DSN (URL or key=value) and returns the database name
|
||||
// and a DSN pointing to the "postgres" maintenance database.
|
||||
func extractDBNameAndAdminDSN(dsn string) (string, string, error) {
|
||||
// Try URL format: postgres://user:pass@host:port/dbname?...
|
||||
if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("failed to parse DSN URL: %v", err)
|
||||
}
|
||||
dbName := strings.TrimPrefix(u.Path, "/")
|
||||
u.Path = "/postgres"
|
||||
return dbName, u.String(), nil
|
||||
}
|
||||
|
||||
// Key=value format: host=... user=... password=... dbname=... sslmode=...
|
||||
parts := strings.Fields(dsn)
|
||||
kvMap := make(map[string]string, len(parts))
|
||||
for _, p := range parts {
|
||||
kv := strings.SplitN(p, "=", 2)
|
||||
if len(kv) == 2 {
|
||||
kvMap[kv[0]] = kv[1]
|
||||
}
|
||||
}
|
||||
dbName, ok := kvMap["dbname"]
|
||||
if !ok || dbName == "" {
|
||||
return "", "", fmt.Errorf("could not extract dbname from DSN")
|
||||
}
|
||||
kvMap["dbname"] = "postgres"
|
||||
adminParts := make([]string, 0, len(kvMap))
|
||||
for k, v := range kvMap {
|
||||
adminParts = append(adminParts, k+"="+v)
|
||||
}
|
||||
return dbName, strings.Join(adminParts, " "), nil
|
||||
}
|
||||
|
||||
func (c *Config) CreateUsersDB() (*gorm.DB, error) {
|
||||
logger.LogDebug("Connecting to database on: %s", c.postgresUsersDB)
|
||||
|
||||
dbDSN := c.postgresUsersDB
|
||||
|
||||
if c.postgresUsersDB == "" {
|
||||
dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)
|
||||
}
|
||||
|
||||
if err := ensureDBExists(dbDSN); err != nil {
|
||||
logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)
|
||||
}
|
||||
|
||||
db, err := gorm.Open(
|
||||
postgres.Open(dbDSN),
|
||||
&gorm.Config{},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Configurar pool de conexões no GORM
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erro ao obter sql.DB do GORM: %v", err)
|
||||
}
|
||||
|
||||
// Configurar pool de conexões para evitar conexões ociosas não fechadas
|
||||
sqlDB.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente
|
||||
sqlDB.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool
|
||||
sqlDB.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts
|
||||
sqlDB.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func (c *Config) CreateAuthDB() (*sql.DB, error) {
|
||||
dbDSN := c.postgresUsersDB
|
||||
|
||||
if c.postgresUsersDB == "" {
|
||||
dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)
|
||||
}
|
||||
|
||||
if err := ensureDBExists(dbDSN); err != nil {
|
||||
logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)
|
||||
}
|
||||
|
||||
db, err := sql.Open("postgres", dbDSN)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Configurar pool de conexões para evitar conexões ociosas não fechadas
|
||||
db.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente
|
||||
db.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool
|
||||
db.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts
|
||||
db.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto
|
||||
|
||||
// Testar a conexão
|
||||
err = db.Ping()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erro ao testar conexão PostgreSQL AUTH: %v", err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
postgresAuthDB := os.Getenv(config_env.POSTGRES_AUTH_DB)
|
||||
|
||||
postgresUsersDB := os.Getenv(config_env.POSTGRES_USERS_DB)
|
||||
|
||||
postgresHost := os.Getenv(config_env.POSTGRES_HOST)
|
||||
postgresPort := os.Getenv(config_env.POSTGRES_PORT)
|
||||
postgresUser := os.Getenv(config_env.POSTGRES_USER)
|
||||
postgresPassword := os.Getenv(config_env.POSTGRES_PASSWORD)
|
||||
postgresDB := os.Getenv(config_env.POSTGRES_DB)
|
||||
|
||||
if postgresUsersDB == "" && (postgresHost == "" || postgresPort == "" || postgresUser == "" || postgresPassword == "" || postgresDB == "") {
|
||||
logger.LogFatal("[CONFIG] required database configuration variables are missing. Please check your environment configuration.")
|
||||
}
|
||||
|
||||
databaseSaveMessages := os.Getenv(config_env.DATABASE_SAVE_MESSAGES)
|
||||
panicIfEmpty(config_env.DATABASE_SAVE_MESSAGES, databaseSaveMessages)
|
||||
|
||||
globalApiKey := os.Getenv(config_env.GLOBAL_API_KEY)
|
||||
panicIfEmpty(config_env.GLOBAL_API_KEY, globalApiKey)
|
||||
|
||||
clientName := os.Getenv(config_env.CLIENT_NAME)
|
||||
|
||||
waDebug := os.Getenv(config_env.WA_DEBUG)
|
||||
|
||||
logType := os.Getenv(config_env.LOGTYPE)
|
||||
|
||||
webhookFiles := os.Getenv(config_env.WEBHOOKFILES)
|
||||
if webhookFiles == "" {
|
||||
webhookFiles = "true"
|
||||
}
|
||||
|
||||
connectOnStartup := os.Getenv(config_env.CONNECT_ON_STARTUP)
|
||||
if connectOnStartup == "" {
|
||||
connectOnStartup = "false"
|
||||
}
|
||||
|
||||
osName := os.Getenv(config_env.OS_NAME)
|
||||
|
||||
amqpUrl := os.Getenv(config_env.AMQP_URL)
|
||||
|
||||
// Validate AMQP URL format
|
||||
if err := validateAMQPURL(amqpUrl); err != nil {
|
||||
logger.LogFatal("[CONFIG] AMQP URL validation failed: %v", err)
|
||||
}
|
||||
|
||||
amqpGlobalEnabled := os.Getenv(config_env.AMQP_GLOBAL_ENABLED)
|
||||
|
||||
webhookUrl := os.Getenv(config_env.WEBHOOK_URL)
|
||||
|
||||
apiAudioConverter := os.Getenv(config_env.API_AUDIO_CONVERTER)
|
||||
apiAudioConverterKey := os.Getenv(config_env.API_AUDIO_CONVERTER_KEY)
|
||||
|
||||
whatsappVersionMajor := os.Getenv(config_env.WHATSAPP_VERSION_MAJOR)
|
||||
whatsappVersionMinor := os.Getenv(config_env.WHATSAPP_VERSION_MINOR)
|
||||
whatsappVersionPatch := os.Getenv(config_env.WHATSAPP_VERSION_PATCH)
|
||||
|
||||
proxyHost := os.Getenv(config_env.PROXY_HOST)
|
||||
proxyPort := os.Getenv(config_env.PROXY_PORT)
|
||||
proxyUsername := os.Getenv(config_env.PROXY_USERNAME)
|
||||
proxyPassword := os.Getenv(config_env.PROXY_PASSWORD)
|
||||
|
||||
eventIgnoreGroup := os.Getenv(config_env.EVENT_IGNORE_GROUP)
|
||||
eventIgnoreStatus := os.Getenv(config_env.EVENT_IGNORE_STATUS)
|
||||
qrcodeMaxCount := os.Getenv(config_env.QRCODE_MAX_COUNT)
|
||||
checkUserExists := os.Getenv(config_env.CHECK_USER_EXISTS)
|
||||
|
||||
if checkUserExists == "" {
|
||||
checkUserExists = "true"
|
||||
}
|
||||
|
||||
// Convertendo para int com valores padrão caso estejam vazios
|
||||
major := 0
|
||||
if whatsappVersionMajor != "" {
|
||||
major, _ = strconv.Atoi(whatsappVersionMajor)
|
||||
}
|
||||
minor := 0
|
||||
if whatsappVersionMinor != "" {
|
||||
minor, _ = strconv.Atoi(whatsappVersionMinor)
|
||||
}
|
||||
patch := 0
|
||||
if whatsappVersionPatch != "" {
|
||||
patch, _ = strconv.Atoi(whatsappVersionPatch)
|
||||
}
|
||||
|
||||
qrMaxCount := 5 // Valor padrão
|
||||
if qrcodeMaxCount != "" {
|
||||
qrMaxCount, _ = strconv.Atoi(qrcodeMaxCount)
|
||||
}
|
||||
|
||||
amqpGlobalEvents := strings.Split(os.Getenv(config_env.AMQP_GLOBAL_EVENTS), ",")
|
||||
if len(amqpGlobalEvents) == 1 && amqpGlobalEvents[0] == "" {
|
||||
amqpGlobalEvents = []string{}
|
||||
}
|
||||
|
||||
amqpSpecificEvents := strings.Split(os.Getenv(config_env.AMQP_SPECIFIC_EVENTS), ",")
|
||||
if len(amqpSpecificEvents) == 1 && amqpSpecificEvents[0] == "" {
|
||||
amqpSpecificEvents = []string{}
|
||||
}
|
||||
|
||||
natsUrl := os.Getenv(config_env.NATS_URL)
|
||||
natsGlobalEnabled := os.Getenv(config_env.NATS_GLOBAL_ENABLED)
|
||||
natsGlobalEvents := strings.Split(os.Getenv(config_env.NATS_GLOBAL_EVENTS), ",")
|
||||
if len(natsGlobalEvents) == 1 && natsGlobalEvents[0] == "" {
|
||||
natsGlobalEvents = []string{}
|
||||
}
|
||||
|
||||
// Logger configurations
|
||||
logMaxSize, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_SIZE))
|
||||
if logMaxSize == 0 {
|
||||
logMaxSize = 100 // Default 100MB
|
||||
}
|
||||
|
||||
logMaxBackups, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_BACKUPS))
|
||||
if logMaxBackups == 0 {
|
||||
logMaxBackups = 5 // Default 5 backups
|
||||
}
|
||||
|
||||
logMaxAge, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_AGE))
|
||||
if logMaxAge == 0 {
|
||||
logMaxAge = 30 // Default 30 days
|
||||
}
|
||||
|
||||
logDirectory := os.Getenv(config_env.LOG_DIRECTORY)
|
||||
if logDirectory == "" {
|
||||
logDirectory = "./logs" // Default logs directory
|
||||
}
|
||||
|
||||
logCompress := os.Getenv(config_env.LOG_COMPRESS) == "true"
|
||||
if os.Getenv(config_env.LOG_COMPRESS) == "" {
|
||||
logCompress = true // Default compression enabled
|
||||
}
|
||||
|
||||
config := &Config{
|
||||
PostgresAuthDB: postgresAuthDB,
|
||||
postgresUsersDB: postgresUsersDB,
|
||||
DatabaseSaveMessages: databaseSaveMessages == "true",
|
||||
GlobalApiKey: globalApiKey,
|
||||
WaDebug: waDebug,
|
||||
LogType: logType,
|
||||
WebhookFiles: webhookFiles == "true",
|
||||
ConnectOnStartup: connectOnStartup == "true",
|
||||
OsName: osName,
|
||||
AmqpUrl: amqpUrl,
|
||||
AmqpGlobalEnabled: amqpGlobalEnabled == "true",
|
||||
WebhookUrl: webhookUrl,
|
||||
ClientName: clientName,
|
||||
ApiAudioConverter: apiAudioConverter,
|
||||
ApiAudioConverterKey: apiAudioConverterKey,
|
||||
PostgresHost: postgresHost,
|
||||
PostgresPort: postgresPort,
|
||||
PostgresUser: postgresUser,
|
||||
PostgresPassword: postgresPassword,
|
||||
PostgresDB: postgresDB,
|
||||
WhatsappVersionMajor: major,
|
||||
WhatsappVersionMinor: minor,
|
||||
WhatsappVersionPatch: patch,
|
||||
ProxyHost: proxyHost,
|
||||
ProxyPort: proxyPort,
|
||||
ProxyUsername: proxyUsername,
|
||||
ProxyPassword: proxyPassword,
|
||||
EventIgnoreGroup: eventIgnoreGroup == "true",
|
||||
EventIgnoreStatus: eventIgnoreStatus == "true",
|
||||
QrcodeMaxCount: qrMaxCount,
|
||||
CheckUserExists: checkUserExists != "false", // Default true, set to false to disable
|
||||
AmqpGlobalEvents: amqpGlobalEvents,
|
||||
AmqpSpecificEvents: amqpSpecificEvents,
|
||||
NatsUrl: natsUrl,
|
||||
NatsGlobalEnabled: natsGlobalEnabled == "true",
|
||||
NatsGlobalEvents: natsGlobalEvents,
|
||||
LogMaxSize: logMaxSize,
|
||||
LogMaxBackups: logMaxBackups,
|
||||
LogMaxAge: logMaxAge,
|
||||
LogDirectory: logDirectory,
|
||||
LogCompress: logCompress,
|
||||
}
|
||||
|
||||
minioEnabled := os.Getenv(config_env.MINIO_ENABLED) == "true"
|
||||
if minioEnabled {
|
||||
config.MinioEnabled = true
|
||||
loadMinioConfig(config)
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
func loadMinioConfig(config *Config) {
|
||||
minioEndpoint := os.Getenv(config_env.MINIO_ENDPOINT)
|
||||
panicIfEmpty(config_env.MINIO_ENDPOINT, minioEndpoint)
|
||||
|
||||
minioAccessKey := os.Getenv(config_env.MINIO_ACCESS_KEY)
|
||||
panicIfEmpty(config_env.MINIO_ACCESS_KEY, minioAccessKey)
|
||||
|
||||
minioSecretKey := os.Getenv(config_env.MINIO_SECRET_KEY)
|
||||
panicIfEmpty(config_env.MINIO_SECRET_KEY, minioSecretKey)
|
||||
|
||||
minioBucket := os.Getenv(config_env.MINIO_BUCKET)
|
||||
panicIfEmpty(config_env.MINIO_BUCKET, minioBucket)
|
||||
|
||||
minioUseSSL := os.Getenv(config_env.MINIO_USE_SSL) == "true"
|
||||
|
||||
minioRegion := os.Getenv(config_env.MINIO_REGION)
|
||||
|
||||
config.MinioEndpoint = minioEndpoint
|
||||
config.MinioAccessKey = minioAccessKey
|
||||
config.MinioSecretKey = minioSecretKey
|
||||
config.MinioBucket = minioBucket
|
||||
config.MinioUseSSL = minioUseSSL
|
||||
config.MinioRegion = minioRegion
|
||||
}
|
||||
|
||||
func panicIfEmpty(key, value string) {
|
||||
if value == "" {
|
||||
if os.Getenv("DEBUG_ENABLED") != "1" {
|
||||
logger.LogInfo("You are NOT on development mode")
|
||||
}
|
||||
logger.LogFatal("[CONFIG] required configuration variable is missing. Please check your environment configuration.")
|
||||
}
|
||||
}
|
||||
|
||||
// validateAMQPURL validates if the AMQP URL has the correct scheme and format
|
||||
func validateAMQPURL(amqpURL string) error {
|
||||
if amqpURL == "" {
|
||||
return nil // Empty URL is allowed (RabbitMQ disabled)
|
||||
}
|
||||
|
||||
// Parse the URL
|
||||
parsedURL, err := url.Parse(amqpURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid AMQP URL format: %v", err)
|
||||
}
|
||||
|
||||
// Check if scheme is valid
|
||||
if parsedURL.Scheme != "amqp" && parsedURL.Scheme != "amqps" {
|
||||
return fmt.Errorf("AMQP scheme must be either 'amqp://' or 'amqps://', got: '%s://'", parsedURL.Scheme)
|
||||
}
|
||||
|
||||
// Check if host is present
|
||||
if parsedURL.Host == "" {
|
||||
return fmt.Errorf("AMQP URL must include a host")
|
||||
}
|
||||
|
||||
logger.LogInfo("[CONFIG] AMQP URL validation successful: %s://%s", parsedURL.Scheme, parsedURL.Host)
|
||||
return nil
|
||||
}
|
||||
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
package config_env
|
||||
|
||||
const (
|
||||
POSTGRES_AUTH_DB = "POSTGRES_AUTH_DB"
|
||||
POSTGRES_USERS_DB = "POSTGRES_USERS_DB"
|
||||
POSTGRES_HOST = "POSTGRES_HOST"
|
||||
POSTGRES_PORT = "POSTGRES_PORT"
|
||||
POSTGRES_USER = "POSTGRES_USER"
|
||||
POSTGRES_PASSWORD = "POSTGRES_PASSWORD"
|
||||
POSTGRES_DB = "POSTGRES_DB"
|
||||
DATABASE_SAVE_MESSAGES = "DATABASE_SAVE_MESSAGES"
|
||||
GLOBAL_API_KEY = "GLOBAL_API_KEY"
|
||||
WA_DEBUG = "DEBUG_ENABLED"
|
||||
LOGTYPE = "LOG_TYPE"
|
||||
WEBHOOKFILES = "WEBHOOK_FILES"
|
||||
CONNECT_ON_STARTUP = "CONNECT_ON_STARTUP"
|
||||
OS_NAME = "OS_NAME"
|
||||
AMQP_URL = "AMQP_URL"
|
||||
AMQP_GLOBAL_ENABLED = "AMQP_GLOBAL_ENABLED"
|
||||
AMQP_GLOBAL_EVENTS = "AMQP_GLOBAL_EVENTS"
|
||||
AMQP_SPECIFIC_EVENTS = "AMQP_SPECIFIC_EVENTS"
|
||||
WEBHOOK_URL = "WEBHOOK_URL"
|
||||
CLIENT_NAME = "CLIENT_NAME"
|
||||
API_AUDIO_CONVERTER = "API_AUDIO_CONVERTER"
|
||||
API_AUDIO_CONVERTER_KEY = "API_AUDIO_CONVERTER_KEY"
|
||||
MINIO_ENDPOINT = "MINIO_ENDPOINT"
|
||||
MINIO_ACCESS_KEY = "MINIO_ACCESS_KEY"
|
||||
MINIO_SECRET_KEY = "MINIO_SECRET_KEY"
|
||||
MINIO_BUCKET = "MINIO_BUCKET"
|
||||
MINIO_USE_SSL = "MINIO_USE_SSL"
|
||||
MINIO_ENABLED = "MINIO_ENABLED"
|
||||
MINIO_REGION = "MINIO_REGION"
|
||||
WHATSAPP_VERSION_MAJOR = "WHATSAPP_VERSION_MAJOR"
|
||||
WHATSAPP_VERSION_MINOR = "WHATSAPP_VERSION_MINOR"
|
||||
WHATSAPP_VERSION_PATCH = "WHATSAPP_VERSION_PATCH"
|
||||
PROXY_HOST = "PROXY_HOST"
|
||||
PROXY_PORT = "PROXY_PORT"
|
||||
PROXY_USERNAME = "PROXY_USERNAME"
|
||||
PROXY_PASSWORD = "PROXY_PASSWORD"
|
||||
NATS_URL = "NATS_URL"
|
||||
NATS_GLOBAL_ENABLED = "NATS_GLOBAL_ENABLED"
|
||||
NATS_GLOBAL_EVENTS = "NATS_GLOBAL_EVENTS"
|
||||
EVENT_IGNORE_GROUP = "EVENT_IGNORE_GROUP"
|
||||
EVENT_IGNORE_STATUS = "EVENT_IGNORE_STATUS"
|
||||
QRCODE_MAX_COUNT = "QRCODE_MAX_COUNT"
|
||||
CHECK_USER_EXISTS = "CHECK_USER_EXISTS"
|
||||
|
||||
// Logger configurations
|
||||
LOG_MAX_SIZE = "LOG_MAX_SIZE"
|
||||
LOG_MAX_BACKUPS = "LOG_MAX_BACKUPS"
|
||||
LOG_MAX_AGE = "LOG_MAX_AGE"
|
||||
LOG_DIRECTORY = "LOG_DIRECTORY"
|
||||
LOG_COMPRESS = "LOG_COMPRESS"
|
||||
)
|
||||
+837
@@ -0,0 +1,837 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
encodedEP string
|
||||
xorKey string
|
||||
)
|
||||
|
||||
func _d0() string {
|
||||
if encodedEP != "" && xorKey != "" {
|
||||
return decodeXOR(encodedEP, xorKey)
|
||||
}
|
||||
parts := [...]string{"h", "tt", "ps", "://", "li", "ce", "nse", ".", "ev", "ol", "ut", "io", "nf", "ou", "nd", "at", "io", "n.", "co", "m.", "br"}
|
||||
var s string
|
||||
for _, p := range parts {
|
||||
s += p
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func decodeXOR(enc, key string) string {
|
||||
encBytes := hexDec(enc)
|
||||
keyBytes := hexDec(key)
|
||||
if len(keyBytes) == 0 {
|
||||
return ""
|
||||
}
|
||||
out := make([]byte, len(encBytes))
|
||||
for i, b := range encBytes {
|
||||
out[i] = b ^ keyBytes[i%len(keyBytes)]
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func hexDec(s string) []byte {
|
||||
if len(s)%2 != 0 {
|
||||
return nil
|
||||
}
|
||||
b := make([]byte, len(s)/2)
|
||||
for i := 0; i < len(s); i += 2 {
|
||||
b[i/2] = hexVal(s[i])<<4 | hexVal(s[i+1])
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func hexVal(c byte) byte {
|
||||
switch {
|
||||
case c >= '0' && c <= '9':
|
||||
return c - '0'
|
||||
case c >= 'a' && c <= 'f':
|
||||
return c - 'a' + 10
|
||||
case c >= 'A' && c <= 'F':
|
||||
return c - 'A' + 10
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var _h0 = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
func _sg(body []byte, secret string) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(body)
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func _ps(path string, payload interface{}, _a0 string) (*http.Response, error) {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
url := _d0() + path
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Api-Key", _a0)
|
||||
req.Header.Set("X-Signature", _sg(body, _a0))
|
||||
|
||||
return _h0.Do(req)
|
||||
}
|
||||
|
||||
func _gu(path string) (*http.Response, error) {
|
||||
url := _d0() + path
|
||||
return _h0.Get(url)
|
||||
}
|
||||
|
||||
func _pu(path string, payload interface{}) (*http.Response, error) {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
url := _d0() + path
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return _h0.Do(req)
|
||||
}
|
||||
|
||||
func _re(resp *http.Response) error {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
var errBody struct {
|
||||
Message string `json:"message"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &errBody); err == nil {
|
||||
msg := errBody.Message
|
||||
if msg == "" {
|
||||
msg = errBody.Error
|
||||
}
|
||||
if msg != "" {
|
||||
return fmt.Errorf("%s (HTTP %d)", strings.ToLower(msg), resp.StatusCode)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
type RuntimeConfig struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
Key string `gorm:"uniqueIndex;size:100;not null" json:"key"`
|
||||
Value string `gorm:"type:text;not null" json:"value"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (RuntimeConfig) TableName() string {
|
||||
return "runtime_configs"
|
||||
}
|
||||
|
||||
const (
|
||||
_ck0 = "instance_id"
|
||||
_ck1 = "api_key"
|
||||
_ck2 = "_a7"
|
||||
_ck3 = "customer_id"
|
||||
)
|
||||
|
||||
var _db0 *gorm.DB
|
||||
|
||||
func SetDB(db *gorm.DB) {
|
||||
_db0 = db
|
||||
}
|
||||
|
||||
func MigrateDB() error {
|
||||
if _db0 == nil {
|
||||
return fmt.Errorf("core: database not set, call SetDB first")
|
||||
}
|
||||
return _db0.AutoMigrate(&RuntimeConfig{})
|
||||
}
|
||||
|
||||
func _gc(key string) (string, error) {
|
||||
if _db0 == nil {
|
||||
return "", fmt.Errorf("core: database not set")
|
||||
}
|
||||
var cfg RuntimeConfig
|
||||
result := _db0.Where("key = ?", key).First(&cfg)
|
||||
if result.Error != nil {
|
||||
return "", result.Error
|
||||
}
|
||||
return cfg.Value, nil
|
||||
}
|
||||
|
||||
func _sc(key, value string) error {
|
||||
if _db0 == nil {
|
||||
return fmt.Errorf("core: database not set")
|
||||
}
|
||||
var cfg RuntimeConfig
|
||||
result := _db0.Where("key = ?", key).First(&cfg)
|
||||
if result.Error != nil {
|
||||
return _db0.Create(&RuntimeConfig{Key: key, Value: value}).Error
|
||||
}
|
||||
return _db0.Model(&cfg).Update("value", value).Error
|
||||
}
|
||||
|
||||
func _dc(key string) {
|
||||
if _db0 == nil {
|
||||
return
|
||||
}
|
||||
_db0.Where("key = ?", key).Delete(&RuntimeConfig{})
|
||||
}
|
||||
|
||||
type _rtd struct {
|
||||
APIKey string
|
||||
Tier string
|
||||
CustomerID int
|
||||
}
|
||||
|
||||
func _lrd() (*_rtd, error) {
|
||||
_a0, err := _gc(_ck1)
|
||||
if err != nil || _a0 == "" {
|
||||
return nil, fmt.Errorf("no license found")
|
||||
}
|
||||
|
||||
_a7, _ := _gc(_ck2)
|
||||
customerIDStr, _ := _gc(_ck3)
|
||||
customerID, _ := strconv.Atoi(customerIDStr)
|
||||
|
||||
return &_rtd{
|
||||
APIKey: _a0,
|
||||
Tier: _a7,
|
||||
CustomerID: customerID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func _srd(rd *_rtd) error {
|
||||
if err := _sc(_ck1, rd.APIKey); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := _sc(_ck2, rd.Tier); err != nil {
|
||||
return err
|
||||
}
|
||||
if rd.CustomerID > 0 {
|
||||
if err := _sc(_ck3, strconv.Itoa(rd.CustomerID)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func _rrd() {
|
||||
_dc(_ck1)
|
||||
_dc(_ck2)
|
||||
_dc(_ck3)
|
||||
}
|
||||
|
||||
func _lid() (string, error) {
|
||||
id, err := _gc(_ck0)
|
||||
if err == nil && len(id) == 36 {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
id = _ghi()
|
||||
if id == "" {
|
||||
id, err = _uuid()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
if err := _sc(_ck0, id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func _ghi() string {
|
||||
hostname, _ := os.Hostname()
|
||||
macAddr := _gpm()
|
||||
if hostname == "" && macAddr == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
seed := hostname + "|" + macAddr
|
||||
h := make([]byte, 16)
|
||||
copy(h, []byte(seed))
|
||||
for i := 16; i < len(seed); i++ {
|
||||
h[i%16] ^= seed[i]
|
||||
}
|
||||
h[6] = (h[6] & 0x0f) | 0x40 // _a8 4
|
||||
h[8] = (h[8] & 0x3f) | 0x80 // variant
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
||||
h[0:4], h[4:6], h[6:8], h[8:10], h[10:16])
|
||||
}
|
||||
|
||||
func _gpm() string {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, iface := range interfaces {
|
||||
if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
if len(iface.HardwareAddr) > 0 {
|
||||
return iface.HardwareAddr.String()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func _uuid() (string, error) {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||
}
|
||||
|
||||
|
||||
var _s0 atomic.Value // set during activation
|
||||
|
||||
func init() {
|
||||
_s0.Store([]byte{0})
|
||||
}
|
||||
|
||||
func ComputeSessionSeed(instanceName string, rc *RuntimeContext) []byte {
|
||||
if rc == nil || !rc._a2.Load() {
|
||||
return nil // Will cause panic in caller — intentional
|
||||
}
|
||||
h := sha256.New()
|
||||
h.Write([]byte(instanceName))
|
||||
h.Write([]byte(rc._a0))
|
||||
salt, _ := _s0.Load().([]byte)
|
||||
h.Write(salt)
|
||||
return h.Sum(nil)[:16]
|
||||
}
|
||||
|
||||
func ValidateRouteAccess(rc *RuntimeContext) uint64 {
|
||||
if rc == nil {
|
||||
return 0
|
||||
}
|
||||
h := rc.ContextHash()
|
||||
return binary.LittleEndian.Uint64(h[:8])
|
||||
}
|
||||
|
||||
func DeriveInstanceToken(_a1 string, rc *RuntimeContext) string {
|
||||
if rc == nil || !rc._a2.Load() {
|
||||
return ""
|
||||
}
|
||||
h := sha256.Sum256([]byte(_a1 + rc._a0))
|
||||
return _he(h[:8])
|
||||
}
|
||||
|
||||
func _he(b []byte) string {
|
||||
const hextable = "0123456789abcdef"
|
||||
dst := make([]byte, len(b)*2)
|
||||
for i, v := range b {
|
||||
dst[i*2] = hextable[v>>4]
|
||||
dst[i*2+1] = hextable[v&0x0f]
|
||||
}
|
||||
return string(dst)
|
||||
}
|
||||
|
||||
func ActivateIntegrity(rc *RuntimeContext) {
|
||||
if rc == nil {
|
||||
return
|
||||
}
|
||||
h := sha256.Sum256([]byte(rc._a0 + rc._a1 + "ev0"))
|
||||
_s0.Store(h[:])
|
||||
}
|
||||
|
||||
const (
|
||||
_p2 = 30 * time.Minute
|
||||
)
|
||||
|
||||
type RuntimeContext struct {
|
||||
_a0 string
|
||||
_a9 string // GLOBAL_API_KEY from .env — used as token for licensing check
|
||||
_a1 string
|
||||
_a2 atomic.Bool
|
||||
_a3 [32]byte // Derived from activation — required by ValidateContext
|
||||
mu sync.RWMutex
|
||||
_a5 string // Registration URL shown to users before activation
|
||||
_a6 string // Registration token for polling
|
||||
_a7 string
|
||||
_a8 string
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) ContextHash() [32]byte {
|
||||
rc.mu.RLock()
|
||||
defer rc.mu.RUnlock()
|
||||
return rc._a3
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) IsActive() bool {
|
||||
return rc._a2.Load()
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) RegistrationURL() string {
|
||||
rc.mu.RLock()
|
||||
defer rc.mu.RUnlock()
|
||||
return rc._a5
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) APIKey() string {
|
||||
rc.mu.RLock()
|
||||
defer rc.mu.RUnlock()
|
||||
return rc._a0
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) InstanceID() string {
|
||||
return rc._a1
|
||||
}
|
||||
|
||||
func InitializeRuntime(_a7, _a8, _a9 string) *RuntimeContext {
|
||||
if _a7 == "" {
|
||||
_a7 = "evolution-go"
|
||||
}
|
||||
if _a8 == "" {
|
||||
_a8 = "unknown"
|
||||
}
|
||||
|
||||
rc := &RuntimeContext{
|
||||
_a7: _a7,
|
||||
_a8: _a8,
|
||||
_a9: _a9,
|
||||
}
|
||||
|
||||
id, err := _lid()
|
||||
if err != nil {
|
||||
log.Fatalf("[runtime] failed to initialize instance: %v", err)
|
||||
}
|
||||
rc._a1 = id
|
||||
|
||||
rd, err := _lrd()
|
||||
if err == nil && rd.APIKey != "" {
|
||||
rc._a0 = rd.APIKey
|
||||
fmt.Printf(" ✓ License found: %s...%s\n", rd.APIKey[:8], rd.APIKey[len(rd.APIKey)-4:])
|
||||
|
||||
rc._a3 = sha256.Sum256([]byte(rc._a0 + rc._a1))
|
||||
rc._a2.Store(true)
|
||||
ActivateIntegrity(rc)
|
||||
fmt.Println(" ✓ License activated successfully")
|
||||
|
||||
go func() {
|
||||
if err := _ai(rc, _a8); err != nil {
|
||||
fmt.Printf(" ⚠ Remote activation notice failed (non-blocking): %v\n", err)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
fmt.Println()
|
||||
fmt.Println(" ╔══════════════════════════════════════════════════════════╗")
|
||||
fmt.Println(" ║ License Registration Required ║")
|
||||
fmt.Println(" ╚══════════════════════════════════════════════════════════╝")
|
||||
fmt.Println()
|
||||
fmt.Println(" Server starting without license.")
|
||||
fmt.Println(" API endpoints will return 503 until license is activated.")
|
||||
fmt.Println(" Use GET /license/register to get the registration URL.")
|
||||
fmt.Println()
|
||||
rc._a2.Store(false)
|
||||
}
|
||||
|
||||
return rc
|
||||
}
|
||||
|
||||
func (rc *RuntimeContext) _ca(authCodeOrKey, _a7 string, customerID int) error {
|
||||
_a0, err := _rk(authCodeOrKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("key exchange failed: %w", err)
|
||||
}
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._a0 = _a0
|
||||
rc._a5 = ""
|
||||
rc._a6 = ""
|
||||
rc.mu.Unlock()
|
||||
|
||||
if err := _srd(&_rtd{
|
||||
APIKey: _a0,
|
||||
Tier: _a7,
|
||||
CustomerID: customerID,
|
||||
}); err != nil {
|
||||
fmt.Printf(" ⚠ Warning: could not save license: %v\n", err)
|
||||
}
|
||||
|
||||
if err := _ai(rc, rc._a8); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._a3 = sha256.Sum256([]byte(rc._a0 + rc._a1))
|
||||
rc.mu.Unlock()
|
||||
rc._a2.Store(true)
|
||||
ActivateIntegrity(rc)
|
||||
|
||||
fmt.Printf(" ✓ License activated! Key: %s...%s (_a7: %s)\n",
|
||||
_a0[:8], _a0[len(_a0)-4:], _a7)
|
||||
|
||||
go func() {
|
||||
if err := _hb(rc, 0); err != nil {
|
||||
fmt.Printf(" ⚠ First heartbeat failed: %v\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateContext(rc *RuntimeContext) (bool, string) {
|
||||
if rc == nil {
|
||||
return false, ""
|
||||
}
|
||||
if !rc._a2.Load() {
|
||||
return false, rc.RegistrationURL()
|
||||
}
|
||||
expected := sha256.Sum256([]byte(rc._a0 + rc._a1))
|
||||
actual := rc.ContextHash()
|
||||
if expected != actual {
|
||||
return false, ""
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func GateMiddleware(rc *RuntimeContext) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
path := c.Request.URL.Path
|
||||
|
||||
if path == "/health" || path == "/server/ok" || path == "/favicon.ico" ||
|
||||
path == "/license/status" || path == "/license/register" || path == "/license/activate" ||
|
||||
strings.HasPrefix(path, "/manager") || strings.HasPrefix(path, "/assets") ||
|
||||
strings.HasPrefix(path, "/swagger") || path == "/ws" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
valid, _ := ValidateContext(rc)
|
||||
if !valid {
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
managerURL := fmt.Sprintf("%s://%s/manager/login", scheme, c.Request.Host)
|
||||
|
||||
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{
|
||||
"error": "service not activated",
|
||||
"code": "LICENSE_REQUIRED",
|
||||
"register_url": managerURL,
|
||||
"message": "License required. Open the manager to activate your license.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("_rch", rc.ContextHash())
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {
|
||||
lic := eng.Group("/license")
|
||||
{
|
||||
lic.GET("/status", func(c *gin.Context) {
|
||||
status := "inactive"
|
||||
if rc.IsActive() {
|
||||
status = "_a2"
|
||||
}
|
||||
|
||||
resp := gin.H{
|
||||
"status": status,
|
||||
"instance_id": rc._a1,
|
||||
}
|
||||
|
||||
rc.mu.RLock()
|
||||
if rc._a0 != "" {
|
||||
resp["api_key"] = rc._a0[:8] + "..." + rc._a0[len(rc._a0)-4:]
|
||||
}
|
||||
rc.mu.RUnlock()
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
})
|
||||
|
||||
lic.GET("/register", func(c *gin.Context) {
|
||||
if rc.IsActive() {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "_a2",
|
||||
"message": "License is already _a2",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
rc.mu.RLock()
|
||||
existingURL := rc._a5
|
||||
rc.mu.RUnlock()
|
||||
|
||||
if existingURL != "" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "pending",
|
||||
"register_url": existingURL,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
payload := map[string]string{
|
||||
"_a7": rc._a7,
|
||||
"_a8": rc._a8,
|
||||
"instance_id": rc._a1,
|
||||
}
|
||||
if redirectURI := c.Query("redirect_uri"); redirectURI != "" {
|
||||
payload["redirect_uri"] = redirectURI
|
||||
}
|
||||
|
||||
resp, err := _pu("/v1/register/init", payload)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{
|
||||
"error": "Failed to contact licensing server",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
errBody := _re(resp)
|
||||
c.JSON(resp.StatusCode, gin.H{
|
||||
"error": "Licensing server error",
|
||||
"details": errBody.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var initResult struct {
|
||||
RegisterURL string `json:"register_url"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&initResult)
|
||||
|
||||
rc.mu.Lock()
|
||||
rc._a5 = initResult.RegisterURL
|
||||
rc._a6 = initResult.Token
|
||||
rc.mu.Unlock()
|
||||
|
||||
fmt.Printf(" → Registration URL: %s\n", initResult.RegisterURL)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "pending",
|
||||
"register_url": initResult.RegisterURL,
|
||||
})
|
||||
})
|
||||
|
||||
lic.GET("/activate", func(c *gin.Context) {
|
||||
if rc.IsActive() {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "_a2",
|
||||
"message": "License is already _a2",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
code := c.Query("code")
|
||||
if code == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Missing code parameter",
|
||||
"message": "Provide ?code=AUTHORIZATION_CODE from the registration callback.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
exchangeResp, err := _pu("/v1/register/exchange", map[string]string{
|
||||
"authorization_code": code,
|
||||
"instance_id": rc._a1,
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{
|
||||
"error": "Failed to contact licensing server",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
defer exchangeResp.Body.Close()
|
||||
|
||||
if exchangeResp.StatusCode != http.StatusOK {
|
||||
errBody := _re(exchangeResp)
|
||||
c.JSON(exchangeResp.StatusCode, gin.H{
|
||||
"error": "Exchange failed",
|
||||
"details": errBody.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var result struct {
|
||||
APIKey string `json:"api_key"`
|
||||
Tier string `json:"_a7"`
|
||||
CustomerID int `json:"customer_id"`
|
||||
}
|
||||
json.NewDecoder(exchangeResp.Body).Decode(&result)
|
||||
|
||||
if result.APIKey == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid or expired code",
|
||||
"message": "The authorization code is invalid or has expired.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := rc._ca(result.APIKey, result.Tier, result.CustomerID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Activation failed",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "_a2",
|
||||
"message": "License activated successfully!",
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time) {
|
||||
go func() {
|
||||
ticker := time.NewTicker(_p2)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !rc.IsActive() {
|
||||
continue
|
||||
}
|
||||
uptime := int64(time.Since(startTime).Seconds())
|
||||
if err := _hb(rc, uptime); err != nil {
|
||||
fmt.Printf(" ⚠ Heartbeat failed (non-blocking): %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func Shutdown(rc *RuntimeContext) {
|
||||
if rc == nil || rc._a0 == "" {
|
||||
return
|
||||
}
|
||||
_sd(rc)
|
||||
}
|
||||
|
||||
|
||||
func exchangeCode(code string) (_a0 string, err error) {
|
||||
resp, err := _pu("/v1/register/exchange", map[string]string{
|
||||
"authorization_code": code,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", _re(resp)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
APIKey string `json:"api_key"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
if result.APIKey == "" {
|
||||
return "", fmt.Errorf("exchange returned empty api_key")
|
||||
}
|
||||
return result.APIKey, nil
|
||||
}
|
||||
|
||||
func _rk(authCodeOrKey string) (string, error) {
|
||||
_a0, err := exchangeCode(authCodeOrKey)
|
||||
if err == nil && _a0 != "" {
|
||||
return _a0, nil
|
||||
}
|
||||
return authCodeOrKey, nil
|
||||
}
|
||||
|
||||
func _ai(rc *RuntimeContext, _a8 string) error {
|
||||
resp, err := _ps("/v1/activate", map[string]string{
|
||||
"instance_id": rc._a1,
|
||||
"_a8": _a8,
|
||||
}, rc._a0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return _re(resp)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
|
||||
if result.Status != "_a2" {
|
||||
return fmt.Errorf("activation returned status: %s", result.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func _hb(rc *RuntimeContext, uptimeSeconds int64) error {
|
||||
resp, err := _ps("/v1/heartbeat", map[string]any{
|
||||
"instance_id": rc._a1,
|
||||
"uptime_seconds": uptimeSeconds,
|
||||
"_a8": rc._a8,
|
||||
}, rc._a0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return _re(resp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func _sd(rc *RuntimeContext) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"instance_id": rc._a1,
|
||||
})
|
||||
|
||||
url := _d0() + "/v1/deactivate"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Api-Key", rc._a0)
|
||||
req.Header.Set("X-Signature", _sg(body, rc._a0))
|
||||
_h0.Do(req)
|
||||
}
|
||||
@@ -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,81 @@
|
||||
package nats_producer
|
||||
|
||||
import (
|
||||
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
type natsProducer struct {
|
||||
conn *nats.Conn
|
||||
natsGlobalEnabled bool
|
||||
natsGlobalEvents []string
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewNatsProducer(
|
||||
url string,
|
||||
natsGlobalEnabled bool,
|
||||
natsGlobalEvents []string,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) producer_interfaces.Producer {
|
||||
conn, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
logger.LogError("Failed to connect to NATS: %v", err)
|
||||
return &natsProducer{
|
||||
conn: nil,
|
||||
natsGlobalEnabled: false,
|
||||
natsGlobalEvents: nil,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
return &natsProducer{
|
||||
conn: conn,
|
||||
natsGlobalEnabled: natsGlobalEnabled,
|
||||
natsGlobalEvents: natsGlobalEvents,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *natsProducer) Produce(
|
||||
queueName string,
|
||||
payload []byte,
|
||||
natsEnable string,
|
||||
userID string,
|
||||
) error {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Starting produce for subject: %s", userID, queueName)
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Global enabled: %v", userID, p.natsGlobalEnabled)
|
||||
|
||||
if p.conn == nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogWarn("[%s] NATS connection is nil", userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if natsEnable == "global" {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Publishing to global subject: %s", userID, queueName)
|
||||
err := p.conn.Publish(queueName, payload)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to subject %s: %v", userID, queueName, err)
|
||||
return err
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to subject: %s", userID, queueName)
|
||||
}
|
||||
|
||||
if natsEnable == "enabled" {
|
||||
err := p.conn.Publish(queueName, payload)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to instance subject %s: %v", userID, queueName, err)
|
||||
return err
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to instance subject: %s", userID, queueName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateGlobalQueues não faz nada para NATS producer pois os subjects são criados dinamicamente
|
||||
func (p *natsProducer) CreateGlobalQueues() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package rabbitmq_producer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/gomessguii/logger"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type rabbitMQProducer struct {
|
||||
conn *amqp.Connection
|
||||
amqpGlobalEnabled bool
|
||||
amqpGlobalEvents []string
|
||||
amqpSpecificEvents []string
|
||||
connStr string
|
||||
maxRetries int
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewRabbitMQProducer(
|
||||
conn *amqp.Connection,
|
||||
amqpGlobalEnabled bool,
|
||||
amqpGlobalEvents []string,
|
||||
amqpSpecificEvents []string,
|
||||
connStr string,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) producer_interfaces.Producer {
|
||||
producer := &rabbitMQProducer{
|
||||
conn: conn,
|
||||
amqpGlobalEnabled: amqpGlobalEnabled,
|
||||
amqpGlobalEvents: amqpGlobalEvents,
|
||||
amqpSpecificEvents: amqpSpecificEvents,
|
||||
connStr: connStr,
|
||||
maxRetries: 3,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
|
||||
return producer
|
||||
}
|
||||
|
||||
// maskConnectionString masks sensitive information in the connection string for logging
|
||||
func (p *rabbitMQProducer) maskConnectionString(connStr string) string {
|
||||
if connStr == "" {
|
||||
return "empty"
|
||||
}
|
||||
|
||||
parsedURL, err := url.Parse(connStr)
|
||||
if err != nil {
|
||||
return "invalid-url"
|
||||
}
|
||||
|
||||
// Mask password if present
|
||||
if parsedURL.User != nil {
|
||||
if _, hasPassword := parsedURL.User.Password(); hasPassword {
|
||||
parsedURL.User = url.UserPassword(parsedURL.User.Username(), "***")
|
||||
}
|
||||
}
|
||||
|
||||
return parsedURL.String()
|
||||
}
|
||||
|
||||
// handleConnectionClose monitors connection close events and logs them
|
||||
func (p *rabbitMQProducer) handleConnectionClose() {
|
||||
if p.conn == nil {
|
||||
return
|
||||
}
|
||||
|
||||
closeChan := make(chan *amqp.Error)
|
||||
p.conn.NotifyClose(closeChan)
|
||||
|
||||
closeErr := <-closeChan
|
||||
if closeErr != nil {
|
||||
logger.LogWarn("RabbitMQ connection closed unexpectedly: %v", closeErr)
|
||||
logger.LogInfo("Connection will be re-established on next message send")
|
||||
} else {
|
||||
logger.LogInfo("RabbitMQ connection closed gracefully")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) reconnect() error {
|
||||
if p.connStr == "" {
|
||||
return fmt.Errorf("connection string is empty - RabbitMQ URL not configured")
|
||||
}
|
||||
|
||||
logger.LogInfo("Starting RabbitMQ reconnection process with URL: %s", p.maskConnectionString(p.connStr))
|
||||
|
||||
var err error
|
||||
for i := 0; i < 3; i++ {
|
||||
logger.LogInfo("Tentando reconectar ao RabbitMQ (tentativa %d/3)", i+1)
|
||||
|
||||
// Create connection with heartbeat to prevent timeouts
|
||||
config := amqp.Config{
|
||||
Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds
|
||||
Locale: "en_US",
|
||||
}
|
||||
|
||||
p.conn, err = amqp.DialConfig(p.connStr, config)
|
||||
if err == nil {
|
||||
logger.LogInfo("Reconectado com sucesso ao RabbitMQ com heartbeat de 30s")
|
||||
|
||||
// Set up connection close notification
|
||||
go p.handleConnectionClose()
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.LogError("Falha na tentativa %d/3 de reconexão: %v", i+1, err)
|
||||
if i < 2 { // Don't sleep on the last attempt
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("falha ao reconectar após 3 tentativas: %v", err)
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) ensureConnection() error {
|
||||
if p.conn == nil || p.conn.IsClosed() {
|
||||
return p.reconnect()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) publishWithRetry(
|
||||
channel *amqp.Channel,
|
||||
queueName string,
|
||||
payload []byte,
|
||||
userID string,
|
||||
) error {
|
||||
var err error
|
||||
for i := 0; i < p.maxRetries; i++ {
|
||||
err = channel.Publish(
|
||||
"", // exchange
|
||||
queueName, // routing key
|
||||
false, // mandatory
|
||||
false, // immediate
|
||||
amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
Body: payload,
|
||||
DeliveryMode: amqp.Persistent, // Garante persistência da mensagem
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.LogWarn("[%s] Falha ao publicar mensagem (tentativa %d/%d): %v",
|
||||
userID, i+1, p.maxRetries, err)
|
||||
|
||||
// Se o erro for de conexão, tenta reconectar
|
||||
if err.Error() == "Exception (504) Reason: \"channel/connection is not open\"" {
|
||||
if err := p.ensureConnection(); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Cria novo canal após reconexão
|
||||
channel, err = p.conn.Channel()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(time.Second * time.Duration(i+1))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *rabbitMQProducer) Produce(
|
||||
queueName string,
|
||||
payload []byte,
|
||||
rabbitmqEnable string,
|
||||
userID string,
|
||||
) error {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] RabbitMQ Producer - Starting produce for queue: %s", userID, queueName)
|
||||
|
||||
if p.connStr == "" {
|
||||
return fmt.Errorf("RabbitMQ connection string is empty - check AMQP_URL configuration")
|
||||
}
|
||||
|
||||
if err := p.ensureConnection(); err != nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to ensure RabbitMQ connection: %v", userID, err)
|
||||
return fmt.Errorf("falha ao garantir conexão: %v", err)
|
||||
}
|
||||
|
||||
channel, err := p.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("falha ao abrir canal: %v", err)
|
||||
}
|
||||
defer channel.Close()
|
||||
|
||||
// Configura confirmação de publicação
|
||||
if err := channel.Confirm(false); err != nil {
|
||||
return fmt.Errorf("falha ao configurar confirms do canal: %v", err)
|
||||
}
|
||||
|
||||
args := amqp.Table{
|
||||
"x-queue-type": "quorum",
|
||||
"x-ha-policy": "all", // Alta disponibilidade
|
||||
}
|
||||
|
||||
if rabbitmqEnable == "global" || rabbitmqEnable == "enabled" {
|
||||
_, err = channel.QueueDeclare(
|
||||
queueName, // name
|
||||
true, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
args, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("falha ao declarar fila %s: %v", queueName, err)
|
||||
}
|
||||
|
||||
err = p.publishWithRetry(channel, queueName, payload, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("falha ao publicar mensagem após todas as tentativas: %v", err)
|
||||
}
|
||||
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Mensagem publicada com sucesso na fila: %s", userID, queueName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateGlobalQueues cria todas as filas globais no startup da aplicação
|
||||
func (p *rabbitMQProducer) CreateGlobalQueues() error {
|
||||
if !p.amqpGlobalEnabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Creating global queues for enabled events")
|
||||
|
||||
if err := p.ensureConnection(); err != nil {
|
||||
return fmt.Errorf("failed to ensure connection: %v", err)
|
||||
}
|
||||
|
||||
channel, err := p.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open channel: %v", err)
|
||||
}
|
||||
defer channel.Close()
|
||||
|
||||
args := amqp.Table{
|
||||
"x-queue-type": "quorum",
|
||||
"x-ha-policy": "all", // Alta disponibilidade
|
||||
}
|
||||
|
||||
createdQueues := 0
|
||||
|
||||
// AMQP_SPECIFIC_EVENTS tem prioridade sobre AMQP_GLOBAL_EVENTS
|
||||
if len(p.amqpSpecificEvents) > 0 {
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_SPECIFIC_EVENTS (priority over AMQP_GLOBAL_EVENTS)")
|
||||
|
||||
// Cria filas diretas para eventos específicos
|
||||
for _, eventName := range p.amqpSpecificEvents {
|
||||
queueName := strings.ToLower(eventName)
|
||||
|
||||
_, err = channel.QueueDeclare(
|
||||
queueName, // name
|
||||
true, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
args, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger("system").LogError("Failed to create specific queue %s: %v", queueName, err)
|
||||
return fmt.Errorf("failed to create specific queue %s: %v", queueName, err)
|
||||
}
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Specific queue created: %s", queueName)
|
||||
createdQueues++
|
||||
}
|
||||
} else {
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_GLOBAL_EVENTS (fallback mode)")
|
||||
|
||||
// Mapeia eventos globais para os eventos originais que precisam de filas (modo antigo)
|
||||
eventMap := map[string][]string{
|
||||
"MESSAGE": {"message"},
|
||||
"SEND_MESSAGE": {"sendmessage"},
|
||||
"READ_RECEIPT": {"receipt"},
|
||||
"PRESENCE": {"presence"},
|
||||
"HISTORY_SYNC": {"historysync"},
|
||||
"CHAT_PRESENCE": {"chatpresence", "archive"},
|
||||
"CALL": {"calloffer", "callaccept", "callterminate", "calloffernotice", "callrelaylatency"},
|
||||
"CONNECTION": {"connected", "pairsuccess", "temporaryban", "loggedout", "connectfailure", "disconnected"},
|
||||
"LABEL": {"labeledit", "labelassociationchat", "labelassociationmessage"},
|
||||
"CONTACT": {"contact", "pushname"},
|
||||
"GROUP": {"groupinfo", "joinedgroup"},
|
||||
"NEWSLETTER": {"newsletterjoin", "newsletterleave"},
|
||||
"QRCODE": {"qrcode", "qrtimeout", "qrsuccess"},
|
||||
}
|
||||
|
||||
for _, globalEvent := range p.amqpGlobalEvents {
|
||||
if queueNames, exists := eventMap[globalEvent]; exists {
|
||||
for _, queueName := range queueNames {
|
||||
_, err = channel.QueueDeclare(
|
||||
queueName, // name
|
||||
true, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
args, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger("system").LogError("Failed to create global queue %s: %v", queueName, err)
|
||||
return fmt.Errorf("failed to create global queue %s: %v", queueName, err)
|
||||
}
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Global queue created: %s", queueName)
|
||||
createdQueues++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
p.loggerWrapper.GetLogger("system").LogInfo("Successfully created %d global queues", createdQueues)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package webhook_producer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
)
|
||||
|
||||
type webhookProducer struct {
|
||||
url string
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewWebhookProducer(
|
||||
url string,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) producer_interfaces.Producer {
|
||||
return &webhookProducer{
|
||||
url: url,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *webhookProducer) Produce(
|
||||
queueName string,
|
||||
payload []byte,
|
||||
webhookUrl string,
|
||||
userID string,
|
||||
) error {
|
||||
splitQueue := strings.Split(queueName, ".")
|
||||
|
||||
if len(splitQueue) < 2 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if p.url != "" {
|
||||
go p.sendWebhookWithRetry(p.url, payload, 5, 30*time.Second, userID)
|
||||
}
|
||||
if webhookUrl != "" {
|
||||
go p.sendWebhookWithRetry(webhookUrl, payload, 5, 30*time.Second, userID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *webhookProducer) sendWebhookWithRetry(url string, body []byte, maxRetries int, retryInterval time.Duration, userID string) {
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
err, responseBody, statusCode := p.sendWebhook(url, body, userID)
|
||||
if err == nil {
|
||||
p.loggerWrapper.GetLogger(userID).LogInfo("[%s] webhook sent successfully - url: %s, status: %d, response: %s", userID, url, statusCode, string(responseBody))
|
||||
return
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogWarn("[%s] webhook failed - url: %s, attempt: %d, error: %v", userID, url, i+1, err)
|
||||
|
||||
time.Sleep(retryInterval)
|
||||
}
|
||||
p.loggerWrapper.GetLogger(userID).LogError("[%s] webhook failed after maximum retries - url: %s", userID, url)
|
||||
}
|
||||
|
||||
func (p *webhookProducer) sendWebhook(url string, body []byte, userID string) (error, []byte, int) {
|
||||
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
return err, nil, 0
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err, nil, 0
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
responseBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erro ao ler resposta: %v", err), nil, 0
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return errors.New("received non-2xx response: " + resp.Status), responseBody, resp.StatusCode
|
||||
}
|
||||
|
||||
return nil, responseBody, resp.StatusCode
|
||||
}
|
||||
|
||||
// CreateGlobalQueues não faz nada para webhook producer
|
||||
func (p *webhookProducer) CreateGlobalQueues() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package websocket_producer
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
logger.LogInfo("Verificando origem da conexão WebSocket")
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
type websocketProducer struct {
|
||||
clients map[string]*websocket.Conn // conexões específicas por instância
|
||||
broadcast []*websocket.Conn // conexões que recebem todos os eventos
|
||||
clientsMux sync.RWMutex
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {
|
||||
return &websocketProducer{
|
||||
clients: make(map[string]*websocket.Conn),
|
||||
broadcast: make([]*websocket.Conn, 0),
|
||||
clientsMux: sync.RWMutex{},
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
// ServeWs lida com as requisições de upgrade para websocket
|
||||
func ServeWs(w http.ResponseWriter, r *http.Request, instanceId string, producer *websocketProducer) {
|
||||
logger.LogInfo("Iniciando upgrade da conexão WebSocket")
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.LogInfo("Conexão WebSocket estabelecida com sucesso")
|
||||
|
||||
if instanceId == "" {
|
||||
producer.AddBroadcastClient(conn)
|
||||
} else {
|
||||
producer.AddClient(instanceId, conn)
|
||||
}
|
||||
|
||||
// Goroutine para limpar conexão quando fechada
|
||||
go func() {
|
||||
for {
|
||||
_, _, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
if instanceId == "" {
|
||||
producer.RemoveBroadcastClient(conn)
|
||||
} else {
|
||||
producer.RemoveClient(instanceId)
|
||||
}
|
||||
conn.Close()
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *websocketProducer) AddBroadcastClient(conn *websocket.Conn) {
|
||||
p.clientsMux.Lock()
|
||||
defer p.clientsMux.Unlock()
|
||||
p.broadcast = append(p.broadcast, conn)
|
||||
logger.LogInfo("Cliente broadcast websocket adicionado")
|
||||
}
|
||||
|
||||
func (p *websocketProducer) RemoveBroadcastClient(conn *websocket.Conn) {
|
||||
p.clientsMux.Lock()
|
||||
defer p.clientsMux.Unlock()
|
||||
for i, c := range p.broadcast {
|
||||
if c == conn {
|
||||
p.broadcast = append(p.broadcast[:i], p.broadcast[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
logger.LogInfo("Cliente broadcast websocket removido")
|
||||
}
|
||||
|
||||
func (p *websocketProducer) AddClient(instanceID string, conn *websocket.Conn) {
|
||||
p.clientsMux.Lock()
|
||||
defer p.clientsMux.Unlock()
|
||||
p.clients[instanceID] = conn
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket adicionado para instância: %s", instanceID)
|
||||
}
|
||||
|
||||
func (p *websocketProducer) RemoveClient(instanceID string) {
|
||||
p.clientsMux.Lock()
|
||||
defer p.clientsMux.Unlock()
|
||||
delete(p.clients, instanceID)
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket removido para instância: %s", instanceID)
|
||||
}
|
||||
|
||||
func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error {
|
||||
message := map[string]interface{}{
|
||||
"queue": strings.ToLower(queueName),
|
||||
"payload": string(payload),
|
||||
}
|
||||
|
||||
p.clientsMux.RLock()
|
||||
defer p.clientsMux.RUnlock()
|
||||
|
||||
// Envia para cliente específico da instância
|
||||
if client, exists := p.clients[instanceID]; exists {
|
||||
err := client.WriteJSON(message)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
|
||||
// Não remove o cliente aqui pois estamos com o RLock
|
||||
return err
|
||||
}
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo("Mensagem websocket enviada com sucesso para instância %s na fila %s", instanceID, queueName)
|
||||
}
|
||||
|
||||
// Envia para todos os clientes broadcast
|
||||
for _, conn := range p.broadcast {
|
||||
err := conn.WriteJSON(message)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem broadcast websocket: %v", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateGlobalQueues não faz nada para websocket producer
|
||||
func (p *websocketProducer) CreateGlobalQueues() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
package group_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type GroupHandler interface {
|
||||
ListGroups(ctx *gin.Context)
|
||||
GetGroupInfo(ctx *gin.Context)
|
||||
GetGroupInviteLink(ctx *gin.Context)
|
||||
SetGroupPhoto(ctx *gin.Context)
|
||||
SetGroupName(ctx *gin.Context)
|
||||
SetGroupDescription(ctx *gin.Context)
|
||||
CreateGroup(ctx *gin.Context)
|
||||
UpdateParticipant(ctx *gin.Context)
|
||||
GetMyGroups(ctx *gin.Context)
|
||||
JoinGroupLink(ctx *gin.Context)
|
||||
LeaveGroup(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type groupHandler struct {
|
||||
groupService group_service.GroupService
|
||||
}
|
||||
|
||||
// List groups
|
||||
// @Summary List groups
|
||||
// @Description List groups
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/list [get]
|
||||
func (g *groupHandler) ListGroups(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.ListGroups(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Get group info
|
||||
// @Summary Get group info
|
||||
// @Description Get group info
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.GetGroupInfoStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/info [post]
|
||||
func (g *groupHandler) GetGroupInfo(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.GetGroupInfoStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.GetGroupInfo(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Get group invite link
|
||||
// @Summary Get group invite link
|
||||
// @Description Get group invite link
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.GetGroupInviteLinkStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/invitelink [post]
|
||||
func (g *groupHandler) GetGroupInviteLink(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.GetGroupInviteLinkStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.GetGroupInviteLink(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Set group photo
|
||||
// @Summary Set group photo
|
||||
// @Description Set group photo
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.SetGroupPhotoStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/photo [post]
|
||||
func (g *groupHandler) SetGroupPhoto(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.SetGroupPhotoStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Image == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image is required"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := g.groupService.SetGroupPhoto(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
|
||||
}
|
||||
|
||||
// Set group name
|
||||
// @Summary Set group name
|
||||
// @Description Set group name
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.SetGroupNameStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/name [post]
|
||||
func (g *groupHandler) SetGroupName(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.SetGroupNameStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.SetGroupName(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Set group description
|
||||
// @Summary Set group description
|
||||
// @Description Set group description
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.SetGroupDescriptionStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/description [post]
|
||||
func (g *groupHandler) SetGroupDescription(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.SetGroupDescriptionStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Description can be empty to clear the group description
|
||||
// No validation needed for Description field
|
||||
|
||||
err = g.groupService.SetGroupDescription(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Create group
|
||||
// @Summary Create group
|
||||
// @Description Create group
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.CreateGroupStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/create [post]
|
||||
func (g *groupHandler) CreateGroup(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.CreateGroupStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupName == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupName is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.Participants) < 1 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})
|
||||
return
|
||||
}
|
||||
|
||||
group, err := g.groupService.CreateGroup(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": group})
|
||||
}
|
||||
|
||||
// Update participant
|
||||
// @Summary Update participant
|
||||
// @Description Update participant
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.AddParticipantStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/participant [post]
|
||||
func (g *groupHandler) UpdateParticipant(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.AddParticipantStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID.String() == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Action == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "action is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.Participants) < 1 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.UpdateParticipant(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Get my groups
|
||||
// @Summary Get my groups
|
||||
// @Description Get my groups
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/myall [get]
|
||||
func (g *groupHandler) GetMyGroups(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
groups, err := g.groupService.GetMyGroups(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": groups})
|
||||
}
|
||||
|
||||
// Join group link
|
||||
// @Summary Join group link
|
||||
// @Description Join group link
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.JoinGroupStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/join [post]
|
||||
func (g *groupHandler) JoinGroupLink(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.JoinGroupStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Code == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "code is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.JoinGroupLink(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Leave group
|
||||
// @Summary Leave group
|
||||
// @Description Leave group
|
||||
// @Tags Group
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body group_service.LeaveGroupStruct true "Group data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /group/leave [post]
|
||||
func (g *groupHandler) LeaveGroup(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *group_service.LeaveGroupStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.GroupJID.String() == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = g.groupService.LeaveGroup(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
func NewGroupHandler(
|
||||
groupService group_service.GroupService,
|
||||
) GroupHandler {
|
||||
return &groupHandler{
|
||||
groupService: groupService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,654 @@
|
||||
package group_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/vincent-petithory/dataurl"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type GroupService interface {
|
||||
ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error)
|
||||
GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error)
|
||||
GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error)
|
||||
SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error)
|
||||
SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error
|
||||
SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error
|
||||
CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error)
|
||||
UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error
|
||||
UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error
|
||||
GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error)
|
||||
UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error)
|
||||
GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error)
|
||||
JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error
|
||||
LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error
|
||||
}
|
||||
|
||||
type groupService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type SimpleGroupInfo struct {
|
||||
JID types.JID `json:"jid"`
|
||||
GroupName string `json:"groupName"`
|
||||
}
|
||||
|
||||
type GroupCollection struct {
|
||||
Groups []SimpleGroupInfo
|
||||
}
|
||||
|
||||
type GetGroupInfoStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
}
|
||||
|
||||
type GetGroupInviteLinkStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Reset bool `json:"reset"`
|
||||
}
|
||||
|
||||
type SetGroupPhotoStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Image string `json:"image"`
|
||||
}
|
||||
|
||||
type SetGroupNameStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type SetGroupDescriptionStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type CreateGroupStruct struct {
|
||||
GroupName string `json:"groupName"`
|
||||
Participants []string `json:"participants"`
|
||||
}
|
||||
|
||||
type AddParticipantStruct struct {
|
||||
GroupJID types.JID `json:"groupJid"`
|
||||
Participants []string `json:"participants"`
|
||||
Action whatsmeow.ParticipantChange `json:"action"`
|
||||
}
|
||||
|
||||
type JoinGroupStruct struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type LeaveGroupStruct struct {
|
||||
GroupJID types.JID `json:"groupJid"`
|
||||
}
|
||||
|
||||
type UpdateGroupSettingsStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Action string `json:"action"` // announcement, not_announcement, locked, unlocked
|
||||
}
|
||||
|
||||
type GetGroupRequestParticipantsStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
}
|
||||
|
||||
// Estrutura enriquecida com PushName
|
||||
type EnrichedGroupParticipantRequest struct {
|
||||
JID types.JID `json:"JID"`
|
||||
RequestedAt time.Time `json:"RequestedAt"`
|
||||
PushName string `json:"PushName"`
|
||||
}
|
||||
|
||||
type UpdateGroupRequestParticipantsStruct struct {
|
||||
GroupJID string `json:"groupJid"`
|
||||
Action string `json:"action"` // approve, reject
|
||||
Participants []string `json:"participants"`
|
||||
}
|
||||
|
||||
|
||||
func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := g.clientPointer[instanceId]
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := g.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = g.clientPointer[instanceId]
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (g *groupService) ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.GetJoinedGroups(context.Background())
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting groups: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gc := new(GroupCollection)
|
||||
for _, info := range resp {
|
||||
simpleGroup := SimpleGroupInfo{
|
||||
JID: info.JID,
|
||||
GroupName: info.GroupName.Name,
|
||||
}
|
||||
gc.Groups = append(gc.Groups, simpleGroup)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return nil, errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
resp, err := client.GetGroupInfo(context.Background(), recipient)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
resp, err := client.GetGroupInviteLink(context.Background(), recipient, data.Reset)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (g *groupService) SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
var fileData []byte
|
||||
|
||||
if strings.HasPrefix(data.Image, "http://") || strings.HasPrefix(data.Image, "https://") {
|
||||
resp, err := http.Get(data.Image)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not download image from URL", instance.Id)
|
||||
return "", fmt.Errorf("failed to fetch image from URL: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
fileData, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not read image data from URL", instance.Id)
|
||||
return "", fmt.Errorf("failed to read image data: %v", err)
|
||||
}
|
||||
|
||||
} else if strings.HasPrefix(data.Image, "data:image/jpeg;base64,") || strings.HasPrefix(data.Image, "data:image/png;base64,") {
|
||||
dataURL, err := dataurl.DecodeString(data.Image)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not decode base64 encoded data from payload", instance.Id)
|
||||
return "", err
|
||||
}
|
||||
fileData = dataURL.Data
|
||||
} else {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Image data should start with \"data:image/jpeg;base64,\" or be a valid URL", instance.Id)
|
||||
return "", errors.New("image data should be a valid URL or start with \"data:image/jpeg;base64,\"")
|
||||
}
|
||||
|
||||
pictureID, err := client.SetGroupPhoto(context.Background(), recipient, fileData)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error setting group photo: %v", instance.Id, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return pictureID, nil
|
||||
}
|
||||
|
||||
func (g *groupService) SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group name for %s", instance.Id, recipient.String())
|
||||
|
||||
err = client.SetGroupName(context.Background(), recipient, data.Name)
|
||||
if err != nil {
|
||||
// Log mais detalhado para erro 409
|
||||
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting name. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)
|
||||
}
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group name: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group name set successfully", instance.Id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group description for %s", instance.Id, recipient.String())
|
||||
|
||||
// Use SetGroupTopic instead of SetGroupDescription (proper WhatsApp method)
|
||||
// Empty strings for previousID and newID will be auto-filled by the library
|
||||
err = client.SetGroupTopic(context.Background(), recipient, "", "", data.Description)
|
||||
if err != nil {
|
||||
// Log mais detalhado para erro 409
|
||||
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting description. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)
|
||||
}
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group description: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group description set successfully", instance.Id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var participants []types.JID
|
||||
for _, participant := range data.Participants {
|
||||
recipient, ok := utils.ParseJID(participant)
|
||||
participants = append(participants, recipient)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return nil, errors.New("invalid phone number")
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{
|
||||
Name: data.GroupName,
|
||||
Participants: participants,
|
||||
})
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var failed []types.JID
|
||||
for _, participant := range resp.Participants {
|
||||
if participant.Error != 0 {
|
||||
failed = append(failed, participant.JID)
|
||||
}
|
||||
}
|
||||
|
||||
var added []types.JID
|
||||
infoResp, err := client.GetGroupInfo(context.Background(), resp.JID)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error get group info: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
for _, add := range infoResp.Participants {
|
||||
added = append(added, add.JID)
|
||||
}
|
||||
|
||||
response := gin.H{
|
||||
"jid": resp.JID,
|
||||
"name": resp.Name,
|
||||
"owner": resp.OwnerJID,
|
||||
"added": added,
|
||||
"failed": failed,
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (g *groupService) UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var participants []types.JID
|
||||
for _, participant := range data.Participants {
|
||||
recipient, ok := utils.ParseJID(participant)
|
||||
participants = append(participants, recipient)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return errors.New("invalid phone number")
|
||||
}
|
||||
}
|
||||
|
||||
_, err = client.UpdateGroupParticipants(context.Background(), data.GroupJID, participants, data.Action)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.GetJoinedGroups(context.Background())
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var jid string = client.Store.ID.String()
|
||||
var jidClear = strings.Split(jid, ".")[0]
|
||||
jidOfAdmin, ok := utils.ParseJID(jidClear)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return nil, errors.New("invalid phone number")
|
||||
}
|
||||
var adminGroups []types.GroupInfo
|
||||
for _, group := range resp {
|
||||
if group.OwnerJID == jidOfAdmin {
|
||||
adminGroups = append(adminGroups, *group)
|
||||
_ = adminGroups
|
||||
}
|
||||
}
|
||||
|
||||
return adminGroups, nil
|
||||
}
|
||||
|
||||
func (g *groupService) JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.JoinGroupWithLink(context.Background(), data.Code)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = client.LeaveGroup(context.Background(), data.GroupJID)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error leave group: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
|
||||
return errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
// Validate action
|
||||
validActions := map[string]bool{
|
||||
"announcement": true,
|
||||
"not_announcement": true,
|
||||
"locked": true,
|
||||
"unlocked": true,
|
||||
"approval_on": true,
|
||||
"approval_off": true,
|
||||
"admin_add": true,
|
||||
"all_member_add": true,
|
||||
}
|
||||
|
||||
if !validActions[data.Action] {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)
|
||||
return errors.New("invalid action. Valid actions: announcement, not_announcement, locked, unlocked, approval_on, approval_off, admin_add, all_member_add")
|
||||
}
|
||||
|
||||
// Apply settings based on action
|
||||
switch data.Action {
|
||||
case "announcement":
|
||||
err = client.SetGroupAnnounce(context.Background(), recipient, true)
|
||||
case "not_announcement":
|
||||
err = client.SetGroupAnnounce(context.Background(), recipient, false)
|
||||
case "locked":
|
||||
err = client.SetGroupLocked(context.Background(), recipient, true)
|
||||
case "unlocked":
|
||||
err = client.SetGroupLocked(context.Background(), recipient, false)
|
||||
case "approval_on":
|
||||
err = client.SetGroupJoinApprovalMode(context.Background(), recipient, true)
|
||||
case "approval_off":
|
||||
err = client.SetGroupJoinApprovalMode(context.Background(), recipient, false)
|
||||
case "admin_add":
|
||||
err = client.SetGroupMemberAddMode(context.Background(), recipient, "admin_add")
|
||||
case "all_member_add":
|
||||
err = client.SetGroupMemberAddMode(context.Background(), recipient, "all_member_add")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group settings: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group settings updated successfully: %s", instance.Id, data.Action)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *groupService) GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
|
||||
return nil, errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
requests, err := client.GetGroupRequestParticipants(context.Background(), recipient)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting group request participants: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Retrieved %d pending group requests", instance.Id, len(requests))
|
||||
|
||||
// Enriquecer com informações de usuário (PushName)
|
||||
enrichedRequests := make([]EnrichedGroupParticipantRequest, len(requests))
|
||||
jidsToFetch := make([]types.JID, 0, len(requests))
|
||||
|
||||
for _, req := range requests {
|
||||
if req.JID.User != "" {
|
||||
jidsToFetch = append(jidsToFetch, req.JID)
|
||||
}
|
||||
}
|
||||
|
||||
// Buscar informações de usuário em lote
|
||||
userInfoMap := make(map[types.JID]types.UserInfo)
|
||||
if len(jidsToFetch) > 0 {
|
||||
userInfoMap, err = client.GetUserInfo(context.Background(), jidsToFetch)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Could not fetch user info: %v", instance.Id, err)
|
||||
// Continuar sem pushName se falhar
|
||||
}
|
||||
}
|
||||
|
||||
// Montar resposta enriquecida
|
||||
for i, req := range requests {
|
||||
enrichedRequests[i] = EnrichedGroupParticipantRequest{
|
||||
JID: req.JID,
|
||||
RequestedAt: req.RequestedAt,
|
||||
PushName: "",
|
||||
}
|
||||
|
||||
// Tentar obter PushName
|
||||
lookupJID := req.JID
|
||||
|
||||
if userInfo, found := userInfoMap[lookupJID]; found {
|
||||
// VerifiedName é ponteiro, verificar se não é nil
|
||||
if userInfo.VerifiedName != nil && userInfo.VerifiedName.Details.GetVerifiedName() != "" {
|
||||
enrichedRequests[i].PushName = userInfo.VerifiedName.Details.GetVerifiedName()
|
||||
}
|
||||
}
|
||||
|
||||
// Tentar obter do store de contatos se não tiver VerifiedName
|
||||
if enrichedRequests[i].PushName == "" && client.Store.Contacts != nil {
|
||||
if contactInfo, err := client.Store.Contacts.GetContact(context.Background(), lookupJID); err == nil && contactInfo.PushName != "" {
|
||||
enrichedRequests[i].PushName = contactInfo.PushName
|
||||
} else if contactInfo.FullName != "" {
|
||||
enrichedRequests[i].PushName = contactInfo.FullName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return enrichedRequests, nil
|
||||
}
|
||||
|
||||
func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error) {
|
||||
client, err := g.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
recipient, ok := utils.ParseJID(data.GroupJID)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)
|
||||
return nil, errors.New("invalid group jid")
|
||||
}
|
||||
|
||||
// Validate action
|
||||
var action whatsmeow.ParticipantRequestChange
|
||||
switch data.Action {
|
||||
case "approve":
|
||||
action = whatsmeow.ParticipantChangeApprove
|
||||
case "reject":
|
||||
action = whatsmeow.ParticipantChangeReject
|
||||
default:
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)
|
||||
return nil, errors.New("invalid action. Valid actions: approve, reject")
|
||||
}
|
||||
|
||||
// Parse participants JIDs
|
||||
var participants []types.JID
|
||||
for _, participant := range data.Participants {
|
||||
participantJID, ok := utils.ParseJID(participant)
|
||||
if !ok {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating participant jid: %s", instance.Id, participant)
|
||||
return nil, errors.New("invalid participant jid: " + participant)
|
||||
}
|
||||
participants = append(participants, participantJID)
|
||||
}
|
||||
|
||||
results, err := client.UpdateGroupRequestParticipants(context.Background(), recipient, participants, action)
|
||||
if err != nil {
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group request participants: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Successfully %sd %d participants", instance.Id, data.Action, len(participants))
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func NewGroupService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) GroupService {
|
||||
return &groupService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
package instance_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
config "github.com/EvolutionAPI/evolution-go/pkg/config"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
|
||||
)
|
||||
|
||||
type InstanceHandler interface {
|
||||
Create(ctx *gin.Context)
|
||||
Connect(ctx *gin.Context)
|
||||
Reconnect(ctx *gin.Context)
|
||||
Disconnect(ctx *gin.Context)
|
||||
Logout(ctx *gin.Context)
|
||||
Delete(ctx *gin.Context)
|
||||
Status(ctx *gin.Context)
|
||||
Qr(ctx *gin.Context)
|
||||
All(ctx *gin.Context)
|
||||
Info(ctx *gin.Context)
|
||||
Pair(ctx *gin.Context)
|
||||
SetProxy(ctx *gin.Context)
|
||||
DeleteProxy(ctx *gin.Context)
|
||||
ForceReconnect(ctx *gin.Context)
|
||||
GetLogs(ctx *gin.Context)
|
||||
GetAdvancedSettings(ctx *gin.Context)
|
||||
UpdateAdvancedSettings(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type instanceHandler struct {
|
||||
config *config.Config
|
||||
instanceService instance_service.InstanceService
|
||||
}
|
||||
|
||||
// Create a new instance
|
||||
// @Summary Create a new instance
|
||||
// @Description Creates a new instance with the provided data including optional advanced settings
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.CreateStruct true "Instance data with optional advanced settings"
|
||||
// @Success 200 {object} gin.H "Instance created successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/create [post]
|
||||
func (i *instanceHandler) Create(ctx *gin.Context) {
|
||||
var data *instance_service.CreateStruct
|
||||
err := ctx.ShouldBindJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Token == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "token is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy != nil {
|
||||
if data.Proxy.Port == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy port is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Password == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy password is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Username == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy username is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Proxy.Host == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy host is required"})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if i.config.ProxyHost != "" && i.config.ProxyPort != "" && i.config.ProxyUsername != "" && i.config.ProxyPassword != "" {
|
||||
data.Proxy = &instance_service.ProxyConfig{
|
||||
Host: i.config.ProxyHost,
|
||||
Port: i.config.ProxyPort,
|
||||
Username: i.config.ProxyUsername,
|
||||
Password: i.config.ProxyPassword,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createdInstance, err := i.instanceService.Create(data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": createdInstance})
|
||||
}
|
||||
|
||||
// Connect to instance
|
||||
// @Summary Connect to instance
|
||||
// @Description Connect to instance with the provided data
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.ConnectStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Instance connected successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/connect [post]
|
||||
func (i *instanceHandler) Connect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.ConnectStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
instance, jid, eventString, err := i.instanceService.Connect(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", instance)
|
||||
|
||||
responseData := gin.H{
|
||||
"jid": jid,
|
||||
"webhookUrl": instance.Webhook,
|
||||
"eventString": eventString,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Reconnect to instance
|
||||
// @Summary Reconnect to instance
|
||||
// @Description Reconnect to instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance reconnected successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/reconnect [post]
|
||||
func (i *instanceHandler) Reconnect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.Reconnect(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Disconnect from instance
|
||||
// @Summary Disconnect from instance
|
||||
// @Description Disconnect from instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance disconnected successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/disconnect [post]
|
||||
func (i *instanceHandler) Disconnect(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
updateInstance, err := i.instanceService.Disconnect(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", updateInstance)
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Logout from instance
|
||||
// @Summary Logout from instance
|
||||
// @Description Logout from instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance logged out successfully"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/logout [delete]
|
||||
func (i *instanceHandler) Logout(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
updateInstance, err := i.instanceService.Logout(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", updateInstance)
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Get instance status
|
||||
// @Summary Get instance status
|
||||
// @Description Get instance status
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance status"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/status [get]
|
||||
func (i *instanceHandler) Status(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
status, err := i.instanceService.Status(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": status})
|
||||
}
|
||||
|
||||
// Get instance QR code
|
||||
// @Summary Get instance QR code
|
||||
// @Description Get instance QR code
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "Instance QR code"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/qr [get]
|
||||
func (i *instanceHandler) Qr(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
qrcode, err := i.instanceService.GetQr(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": qrcode})
|
||||
}
|
||||
|
||||
// Request pairing code
|
||||
// @Summary Request pairing code
|
||||
// @Description Request pairing code
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instance body instance_service.PairStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Pairing code"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/pair [post]
|
||||
func (i *instanceHandler) Pair(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.PairStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Phone == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone is required"})
|
||||
return
|
||||
}
|
||||
|
||||
pairingCode, err := i.instanceService.Pair(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": pairingCode})
|
||||
}
|
||||
|
||||
// Get all instances
|
||||
// @Summary Get all instances
|
||||
// @Description Get all instances
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "All instances"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/all [get]
|
||||
func (i *instanceHandler) All(ctx *gin.Context) {
|
||||
instances, err := i.instanceService.GetAll()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instances})
|
||||
}
|
||||
|
||||
// Get instance
|
||||
// @Summary Get instance
|
||||
// @Description Get instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Success 200 {object} gin.H "Instance"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/get/{instanceId} [get]
|
||||
func (i *instanceHandler) Info(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
instance, err := i.instanceService.Info(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instance})
|
||||
}
|
||||
|
||||
// Delete instance
|
||||
// @Summary Delete instance
|
||||
// @Description Delete instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Success 200 {object} gin.H "Instance deleted successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/delete/{instanceId} [delete]
|
||||
func (i *instanceHandler) Delete(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.Delete(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Set proxy
|
||||
// @Summary Set proxy configuration
|
||||
// @Description Set proxy configuration for an instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance id"
|
||||
// @Param proxy body instance_service.SetProxyStruct true "Proxy configuration"
|
||||
// @Success 200 {object} gin.H "Proxy set successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/proxy/{instanceId} [post]
|
||||
func (i *instanceHandler) SetProxy(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.SetProxyStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if data.Host == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "host is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Port == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "port is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = i.instanceService.SetProxyFromStruct(instanceId, data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"host": data.Host,
|
||||
"port": data.Port,
|
||||
"hasAuth": data.Username != "" && data.Password != "",
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// Delete proxy
|
||||
// @Summary Delete proxy
|
||||
// @Description Delete proxy
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance id"
|
||||
// @Success 200 {object} gin.H "Proxy deleted successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/proxy/{instanceId} [delete]
|
||||
func (i *instanceHandler) DeleteProxy(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err := i.instanceService.RemoveProxy(instanceId)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Force reconnect
|
||||
// @Summary Force reconnect
|
||||
// @Description Force reconnect
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance Id"
|
||||
// @Param instance body instance_service.ForceReconnectStruct true "Instance data"
|
||||
// @Success 200 {object} gin.H "Instance force reconnected successfully"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/forcereconnect/{instanceId} [post]
|
||||
func (i *instanceHandler) ForceReconnect(ctx *gin.Context) {
|
||||
instanceId := ctx.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *instance_service.ForceReconnectStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var number string
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
number = data.Number
|
||||
|
||||
err = i.instanceService.ForceReconnect(instanceId, number)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
type GetLogsQuery struct {
|
||||
StartDate string `form:"start_date"`
|
||||
EndDate string `form:"end_date"`
|
||||
Level string `form:"level"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
func (h *instanceHandler) GetLogs(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
var query GetLogsQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Converte as datas
|
||||
startDate, err := time.Parse("2006-01-02", query.StartDate)
|
||||
if err != nil {
|
||||
startDate = time.Now().AddDate(0, 0, -7) // Default: 7 dias atrás
|
||||
}
|
||||
|
||||
endDate, err := time.Parse("2006-01-02", query.EndDate)
|
||||
if err != nil {
|
||||
endDate = time.Now()
|
||||
}
|
||||
|
||||
// Ajusta o endDate para o final do dia
|
||||
endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, time.UTC)
|
||||
|
||||
if query.Limit == 0 {
|
||||
query.Limit = 100 // Default: 100 registros
|
||||
}
|
||||
|
||||
logs, err := h.instanceService.GetLogs(instanceId, startDate, endDate, query.Level, query.Limit)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, logs)
|
||||
}
|
||||
|
||||
// GetAdvancedSettings retrieves advanced settings for an instance
|
||||
// @Summary Get advanced settings
|
||||
// @Description Get advanced settings for a specific instance
|
||||
// @Tags Instance
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance ID"
|
||||
// @Success 200 {object} instance_model.AdvancedSettings "Advanced settings retrieved successfully"
|
||||
// @Failure 400 {object} gin.H "Invalid instance ID"
|
||||
// @Failure 404 {object} gin.H "Instance not found"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/{instanceId}/advanced-settings [get]
|
||||
func (h *instanceHandler) GetAdvancedSettings(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
settings, err := h.instanceService.GetAdvancedSettings(instanceId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, settings)
|
||||
}
|
||||
|
||||
// UpdateAdvancedSettings updates advanced settings for an instance
|
||||
// @Summary Update advanced settings
|
||||
// @Description Update advanced settings for a specific instance
|
||||
// @Tags Instance
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param instanceId path string true "Instance ID"
|
||||
// @Param settings body instance_model.AdvancedSettings true "Advanced settings data"
|
||||
// @Success 200 {object} gin.H "Advanced settings updated successfully"
|
||||
// @Failure 400 {object} gin.H "Invalid request data"
|
||||
// @Failure 404 {object} gin.H "Instance not found"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /instance/{instanceId}/advanced-settings [put]
|
||||
func (h *instanceHandler) UpdateAdvancedSettings(c *gin.Context) {
|
||||
instanceId := c.Param("instanceId")
|
||||
|
||||
if instanceId == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var settings instance_model.AdvancedSettings
|
||||
if err := c.ShouldBindJSON(&settings); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err := h.instanceService.UpdateAdvancedSettings(instanceId, &settings)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Advanced settings updated successfully",
|
||||
"settings": settings,
|
||||
})
|
||||
}
|
||||
|
||||
func NewInstanceHandler(instanceService instance_service.InstanceService, config *config.Config) InstanceHandler {
|
||||
return &instanceHandler{instanceService: instanceService, config: config}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package instance_model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Instance struct {
|
||||
Id string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
Name string `json:"name"`
|
||||
Token string `json:"token" gorm:"unique"`
|
||||
Webhook string `json:"webhook"`
|
||||
RabbitmqEnable string `json:"rabbitmqEnable"`
|
||||
WebSocketEnable string `json:"websocketEnable"`
|
||||
NatsEnable string `json:"natsEnable"`
|
||||
Jid string `json:"jid" gorm:"column:jid"`
|
||||
Qrcode string `json:"qrcode" gorm:"type:text"`
|
||||
Connected bool `json:"connected"`
|
||||
Expiration int64 `json:"expiration"`
|
||||
DisconnectReason string `json:"disconnect_reason"`
|
||||
Events string `json:"events"`
|
||||
OsName string `json:"os_name"`
|
||||
Proxy string `json:"proxy"`
|
||||
ClientName string `json:"client_name"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime"`
|
||||
|
||||
// Advanced Settings
|
||||
AlwaysOnline bool `json:"alwaysOnline" gorm:"default:false"`
|
||||
RejectCall bool `json:"rejectCall" gorm:"default:false"`
|
||||
MsgRejectCall string `json:"msgRejectCall" gorm:"default:''"`
|
||||
ReadMessages bool `json:"readMessages" gorm:"default:false"`
|
||||
IgnoreGroups bool `json:"ignoreGroups" gorm:"default:false"`
|
||||
IgnoreStatus bool `json:"ignoreStatus" gorm:"default:false"`
|
||||
}
|
||||
|
||||
// AdvancedSettings representa as configurações avançadas de uma instância
|
||||
type AdvancedSettings struct {
|
||||
AlwaysOnline bool `json:"alwaysOnline"`
|
||||
RejectCall bool `json:"rejectCall"`
|
||||
MsgRejectCall string `json:"msgRejectCall"`
|
||||
ReadMessages bool `json:"readMessages"`
|
||||
IgnoreGroups bool `json:"ignoreGroups"`
|
||||
IgnoreStatus bool `json:"ignoreStatus"`
|
||||
}
|
||||
|
||||
func (m *Instance) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
if m.Id == "" {
|
||||
m.Id = uuid.New().String()
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package instance_repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
|
||||
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
|
||||
|
||||
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
|
||||
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
|
||||
)
|
||||
|
||||
type InstanceRepository interface {
|
||||
Create(instance instance_model.Instance) (*instance_model.Instance, error)
|
||||
GetInstanceByID(instanceId string) (*instance_model.Instance, error)
|
||||
GetConnectedInstanceByID(instanceId string) (*instance_model.Instance, error)
|
||||
GetInstanceByToken(token string) (*instance_model.Instance, error)
|
||||
GetInstanceByName(name string) (*instance_model.Instance, error)
|
||||
Update(*instance_model.Instance) error
|
||||
UpdateConnected(userId string, status bool, disconnectReason string) error
|
||||
UpdateQrcode(userId string, qr string) error
|
||||
UpdateProxy(userId string, proxy string) error
|
||||
UpdateJid(userId string, jid string) error
|
||||
GetAllConnectedInstances() ([]*instance_model.Instance, error)
|
||||
GetAllConnectedInstancesByClientName(clientName string) ([]*instance_model.Instance, error)
|
||||
GetAll(clientName string) ([]*instance_model.Instance, error)
|
||||
Delete(instanceId string) error
|
||||
GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error)
|
||||
UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error
|
||||
}
|
||||
|
||||
type instanceRepository struct {
|
||||
db *gorm.DB
|
||||
labelRepo label_repository.LabelRepository
|
||||
messageRepo message_repository.MessageRepository
|
||||
}
|
||||
|
||||
func (i *instanceRepository) Create(instance instance_model.Instance) (*instance_model.Instance, error) {
|
||||
if err := i.db.Create(&instance).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetInstanceByToken(token string) (*instance_model.Instance, error) {
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("token = ?", token).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetInstanceByName(name string) (*instance_model.Instance, error) {
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("name = ?", name).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetInstanceByID(instanceId string) (*instance_model.Instance, error) {
|
||||
// Valida o formato do UUID
|
||||
if _, err := uuid.Parse(instanceId); err != nil {
|
||||
return nil, fmt.Errorf("invalid UUID format: %v", err)
|
||||
}
|
||||
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("id = ?", instanceId).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetConnectedInstanceByID(instanceId string) (*instance_model.Instance, error) {
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Where("id = ? AND connected = ?", instanceId, true).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) Update(instance *instance_model.Instance) error {
|
||||
err := i.db.Save(&instance).Error
|
||||
if err != nil {
|
||||
logger.LogError("Error updating instance in DB: %v", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateConnected(userId string, status bool, disconnectReason string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("connected", status).Update("disconnect_reason", disconnectReason).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateQrcode(userId string, qr string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("qrcode", qr).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateProxy(userId string, proxy string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("proxy", proxy).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateJid(userId string, jid string) error {
|
||||
return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("jid", jid).Error
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAllConnectedInstances() ([]*instance_model.Instance, error) {
|
||||
var instances []*instance_model.Instance
|
||||
err := i.db.Where("connected = ?", true).Find(&instances).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAllConnectedInstancesByClientName(clientName string) ([]*instance_model.Instance, error) {
|
||||
var instances []*instance_model.Instance
|
||||
err := i.db.Where("connected = ? AND client_name = ?", true, clientName).Find(&instances).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAll(clientName string) ([]*instance_model.Instance, error) {
|
||||
var instances []*instance_model.Instance
|
||||
err := i.db.Where("client_name = ?", clientName).Find(&instances).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) Delete(instanceId string) error {
|
||||
return i.db.Transaction(func(tx *gorm.DB) error {
|
||||
// Deleta todas as labels associadas à instância
|
||||
if err := tx.Where("instance_id = ?", instanceId).Delete(&label_model.Label{}).Error; err != nil {
|
||||
return fmt.Errorf("erro ao deletar labels: %v", err)
|
||||
}
|
||||
|
||||
// Deleta todas as mensagens associadas à instância
|
||||
if err := tx.Where("source = ?", instanceId).Delete(&message_model.Message{}).Error; err != nil {
|
||||
return fmt.Errorf("erro ao deletar mensagens: %v", err)
|
||||
}
|
||||
|
||||
// Deleta a instância
|
||||
if err := tx.Where("id = ?", instanceId).Delete(&instance_model.Instance{}).Error; err != nil {
|
||||
return fmt.Errorf("erro ao deletar instância: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (i *instanceRepository) GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error) {
|
||||
// Valida o formato do UUID
|
||||
if _, err := uuid.Parse(instanceId); err != nil {
|
||||
return nil, fmt.Errorf("invalid UUID format: %v", err)
|
||||
}
|
||||
|
||||
var instance instance_model.Instance
|
||||
err := i.db.Select("always_online, reject_call, msg_reject_call, read_messages, ignore_groups, ignore_status").
|
||||
Where("id = ?", instanceId).First(&instance).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
settings := &instance_model.AdvancedSettings{
|
||||
AlwaysOnline: instance.AlwaysOnline,
|
||||
RejectCall: instance.RejectCall,
|
||||
MsgRejectCall: instance.MsgRejectCall,
|
||||
ReadMessages: instance.ReadMessages,
|
||||
IgnoreGroups: instance.IgnoreGroups,
|
||||
IgnoreStatus: instance.IgnoreStatus,
|
||||
}
|
||||
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func (i *instanceRepository) UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error {
|
||||
// Valida o formato do UUID
|
||||
if _, err := uuid.Parse(instanceId); err != nil {
|
||||
return fmt.Errorf("invalid UUID format: %v", err)
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{
|
||||
"always_online": settings.AlwaysOnline,
|
||||
"reject_call": settings.RejectCall,
|
||||
"msg_reject_call": settings.MsgRejectCall,
|
||||
"read_messages": settings.ReadMessages,
|
||||
"ignore_groups": settings.IgnoreGroups,
|
||||
"ignore_status": settings.IgnoreStatus,
|
||||
}
|
||||
|
||||
err := i.db.Model(&instance_model.Instance{}).Where("id = ?", instanceId).Updates(updates).Error
|
||||
if err != nil {
|
||||
logger.LogError("Error updating advanced settings in DB: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewInstanceRepository(db *gorm.DB) InstanceRepository {
|
||||
return &instanceRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,854 @@
|
||||
package instance_service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/config"
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"
|
||||
event_types "github.com/EvolutionAPI/evolution-go/pkg/internal/event_types"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type InstanceService interface {
|
||||
Create(data *CreateStruct) (*instance_model.Instance, error)
|
||||
Connect(data *ConnectStruct, instance *instance_model.Instance) (*instance_model.Instance, string, string, error)
|
||||
Reconnect(instance *instance_model.Instance) error
|
||||
Disconnect(instance *instance_model.Instance) (*instance_model.Instance, error)
|
||||
Logout(instance *instance_model.Instance) (*instance_model.Instance, error)
|
||||
Status(instance *instance_model.Instance) (*StatusStruct, error)
|
||||
GetQr(instance *instance_model.Instance) (*QrcodeStruct, error)
|
||||
Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error)
|
||||
GetAll() ([]*instance_model.Instance, error)
|
||||
Info(instanceId string) (*instance_model.Instance, error)
|
||||
Delete(id string) error
|
||||
SetProxy(id string, proxyConfig *ProxyConfig) error
|
||||
SetProxyFromStruct(id string, data *SetProxyStruct) error
|
||||
RemoveProxy(id string) error
|
||||
ForceReconnect(instanceId string, number string) error
|
||||
GetInstanceByToken(token string) (*instance_model.Instance, error)
|
||||
GetLogs(instanceId string, startDate, endDate time.Time, level string, limit int) ([]logger_wrapper.LogEntry, error)
|
||||
GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error)
|
||||
UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error
|
||||
}
|
||||
|
||||
type instances struct {
|
||||
instanceRepository instance_repository.InstanceRepository
|
||||
config *config.Config
|
||||
killChannel map[string](chan bool)
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type ProxyConfig struct {
|
||||
Port string `json:"port"`
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
type CreateStruct struct {
|
||||
InstanceId string `json:"instanceId"`
|
||||
Name string `json:"name"`
|
||||
Token string `json:"token"`
|
||||
Proxy *ProxyConfig `json:"proxy"`
|
||||
AdvancedSettings *instance_model.AdvancedSettings `json:"advancedSettings"`
|
||||
}
|
||||
|
||||
type ConnectStruct struct {
|
||||
WebhookUrl string `json:"webhookUrl"`
|
||||
Subscribe []string `json:"subscribe"`
|
||||
Immediate bool `json:"immediate"`
|
||||
Phone string `json:"phone"`
|
||||
RabbitmqEnable string `json:"rabbitmqEnable"`
|
||||
WebSocketEnable string `json:"websocketEnable"`
|
||||
NatsEnable string `json:"natsEnable"`
|
||||
}
|
||||
|
||||
type StatusStruct struct {
|
||||
Connected bool
|
||||
LoggedIn bool
|
||||
myJid *types.JID
|
||||
Name string
|
||||
}
|
||||
|
||||
type QrcodeStruct struct {
|
||||
Qrcode string
|
||||
Code string
|
||||
}
|
||||
|
||||
type PairStruct struct {
|
||||
Subscribe []string `json:"subscribe"`
|
||||
Phone string `json:"phone"`
|
||||
}
|
||||
|
||||
type PairReturnStruct struct {
|
||||
PairingCode string
|
||||
}
|
||||
|
||||
type SetProxyStruct struct {
|
||||
Host string `json:"host" validate:"required"`
|
||||
Port string `json:"port" validate:"required"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type ForceReconnectStruct struct {
|
||||
Number string `json:"number"`
|
||||
}
|
||||
|
||||
func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
logger := i.loggerWrapper.GetLogger(instanceId)
|
||||
client := i.clientPointer[instanceId]
|
||||
logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
logger.LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := i.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
logger.LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = i.clientPointer[instanceId]
|
||||
logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
logger.LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
logger.LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
logger.LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (i instances) Create(data *CreateStruct) (*instance_model.Instance, error) {
|
||||
proxyJson, err := json.Marshal(data.Proxy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
findInstance, _ := i.instanceRepository.GetInstanceByName(data.Name)
|
||||
|
||||
if findInstance != nil {
|
||||
return nil, fmt.Errorf("instance already exists")
|
||||
}
|
||||
|
||||
instance := instance_model.Instance{
|
||||
Id: data.InstanceId,
|
||||
Name: data.Name,
|
||||
Token: data.Token,
|
||||
OsName: i.config.OsName,
|
||||
Proxy: string(proxyJson),
|
||||
Connected: false,
|
||||
ClientName: i.config.ClientName,
|
||||
}
|
||||
|
||||
// Set advanced settings if provided
|
||||
if data.AdvancedSettings != nil {
|
||||
instance.AlwaysOnline = data.AdvancedSettings.AlwaysOnline
|
||||
instance.RejectCall = data.AdvancedSettings.RejectCall
|
||||
instance.MsgRejectCall = data.AdvancedSettings.MsgRejectCall
|
||||
instance.ReadMessages = data.AdvancedSettings.ReadMessages
|
||||
instance.IgnoreGroups = data.AdvancedSettings.IgnoreGroups
|
||||
instance.IgnoreStatus = data.AdvancedSettings.IgnoreStatus
|
||||
}
|
||||
|
||||
createdInstance, err := i.instanceRepository.Create(instance)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return createdInstance, nil
|
||||
}
|
||||
|
||||
func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instance) (*instance_model.Instance, string, string, error) {
|
||||
var subscribedEvents []string
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Processing subscribe events: %v", instance.Id, data.Subscribe)
|
||||
|
||||
if len(data.Subscribe) == 0 {
|
||||
subscribedEvents = append(subscribedEvents, event_types.MESSAGE)
|
||||
} else if len(data.Subscribe) > 0 && data.Subscribe[0] == "ALL" {
|
||||
for _, event := range event_types.AllEventTypes {
|
||||
subscribedEvents = append(subscribedEvents, event)
|
||||
}
|
||||
} else {
|
||||
for _, arg := range data.Subscribe {
|
||||
if !event_types.IsEventType(arg) {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Message type discarded '%s'", instance.Id, arg)
|
||||
continue
|
||||
}
|
||||
subscribedEvents = append(subscribedEvents, arg)
|
||||
}
|
||||
}
|
||||
|
||||
eventString := strings.Join(subscribedEvents, ",")
|
||||
|
||||
instance.Events = eventString
|
||||
instance.Webhook = data.WebhookUrl
|
||||
instance.RabbitmqEnable = data.RabbitmqEnable
|
||||
instance.NatsEnable = data.NatsEnable
|
||||
instance.WebSocketEnable = data.WebSocketEnable
|
||||
|
||||
err := i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error updating instance: %s", instance.Id, err)
|
||||
return nil, "", "", err
|
||||
}
|
||||
|
||||
// Verifica se a instância já está rodando
|
||||
isInstanceRunning := i.clientPointer[instance.Id] != nil
|
||||
|
||||
// Sincroniza as configurações na instância em execução (se já estiver conectada)
|
||||
err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance not in runtime yet, will be updated when connected", instance.Id)
|
||||
isInstanceRunning = false
|
||||
} else {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance settings updated successfully in runtime", instance.Id)
|
||||
isInstanceRunning = true
|
||||
}
|
||||
|
||||
// Se a instância não estiver rodando, inicia uma nova
|
||||
if !isInstanceRunning {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
Subscriptions: subscribedEvents,
|
||||
Phone: data.Phone,
|
||||
IsProxy: false,
|
||||
}
|
||||
|
||||
if instance.Proxy != "" || i.config.ProxyHost != "" {
|
||||
var proxyConfig ProxyConfig
|
||||
err := json.Unmarshal([]byte(instance.Proxy), &proxyConfig)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmarshalling proxy config: %v", instance.Id, err)
|
||||
return nil, "", "", err
|
||||
}
|
||||
|
||||
if proxyConfig.Host != "" || i.config.ProxyHost != "" {
|
||||
clientData.IsProxy = true
|
||||
}
|
||||
}
|
||||
|
||||
go i.whatsmeowService.StartClient(clientData)
|
||||
} else {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance already running, settings updated without restarting client", instance.Id)
|
||||
}
|
||||
|
||||
// logger.LogInfo("Waiting 1 seconds")
|
||||
// time.Sleep(1000 * time.Millisecond)
|
||||
|
||||
// if i.clientPointer[instance.Id] != nil {
|
||||
// if !i.clientPointer[instance.Id].IsConnected() {
|
||||
// return instance, "", "", fmt.Errorf("failed to connect")
|
||||
// }
|
||||
// } else {
|
||||
// return instance, "", "", fmt.Errorf("failed to connect")
|
||||
// }
|
||||
|
||||
return instance, instance.Jid, eventString, nil
|
||||
}
|
||||
|
||||
func (i instances) Reconnect(instance *instance_model.Instance) error {
|
||||
_, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return i.whatsmeowService.ReconnectClient(instance.Id)
|
||||
}
|
||||
|
||||
func (i instances) Disconnect(instance *instance_model.Instance) (*instance_model.Instance, error) {
|
||||
client, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
if client.IsConnected() {
|
||||
if client.IsLoggedIn() {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
i.killChannel[instance.Id] <- true
|
||||
|
||||
instance.Events = ""
|
||||
|
||||
err := i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
return instance, nil
|
||||
}
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Ignoring disconnect as it was not connected", instance.Id)
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
func (i instances) Logout(instance *instance_model.Instance) (*instance_model.Instance, error) {
|
||||
client, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
if client.IsLoggedIn() && client.IsConnected() {
|
||||
err := client.Logout(context.Background())
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
instance.Connected = false
|
||||
err = i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
if client.IsConnected() {
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Ignoring logout as it was not connected", instance.Id)
|
||||
return instance, fmt.Errorf("ignoring logout as it was not connected")
|
||||
}
|
||||
|
||||
func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {
|
||||
client, err := i.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
isConnected := client.IsConnected()
|
||||
isLoggedIn := client.IsLoggedIn()
|
||||
|
||||
var myJid *types.JID
|
||||
var name string
|
||||
if isLoggedIn {
|
||||
myJid = client.Store.ID
|
||||
name = client.Store.PushName
|
||||
}
|
||||
|
||||
status := &StatusStruct{
|
||||
Connected: isConnected,
|
||||
LoggedIn: isLoggedIn,
|
||||
myJid: myJid,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {
|
||||
logger := i.loggerWrapper.GetLogger(instance.Id)
|
||||
client := i.clientPointer[instance.Id]
|
||||
|
||||
// Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente
|
||||
if client == nil || client.IsLoggedIn() {
|
||||
if client != nil && client.IsLoggedIn() {
|
||||
logger.LogInfo("[%s] Client is logged in, starting new instance for QR code", instance.Id)
|
||||
} else {
|
||||
logger.LogInfo("[%s] No client found, starting new instance for QR code", instance.Id)
|
||||
}
|
||||
|
||||
// Iniciar nova instância para gerar QR code
|
||||
err := i.whatsmeowService.StartInstance(instance.Id)
|
||||
if err != nil {
|
||||
logger.LogError("[%s] Failed to start instance: %v", instance.Id, err)
|
||||
return nil, fmt.Errorf("failed to start instance: %w", err)
|
||||
}
|
||||
|
||||
// Aguardar um pouco para o cliente iniciar e gerar QR code
|
||||
logger.LogInfo("[%s] Waiting for QR code generation...", instance.Id)
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Verificar novamente se há cliente
|
||||
client = i.clientPointer[instance.Id]
|
||||
if client != nil && client.IsLoggedIn() {
|
||||
return nil, fmt.Errorf("session already logged in")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
// Se o cliente existe mas não está conectado, pode estar aguardando QR code
|
||||
logger.LogInfo("[%s] Client exists but not connected, checking for existing QR code", instance.Id)
|
||||
}
|
||||
|
||||
// Buscar instância atualizada do banco para pegar o QR code mais recente
|
||||
instance, err := i.instanceRepository.GetInstanceByID(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
code := instance.Qrcode
|
||||
if code == "" {
|
||||
// Se não há QR code ainda, aguardar um pouco mais e tentar novamente
|
||||
logger.LogInfo("[%s] No QR code available yet, waiting a bit more...", instance.Id)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
instance, err = i.instanceRepository.GetInstanceByID(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
code = instance.Qrcode
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("no QR code available. Please wait a moment and try again")
|
||||
}
|
||||
}
|
||||
|
||||
parts := strings.Split(code, "|")
|
||||
if len(parts) < 2 {
|
||||
return nil, fmt.Errorf("invalid QR code format")
|
||||
}
|
||||
|
||||
qr := &QrcodeStruct{
|
||||
Qrcode: parts[0],
|
||||
Code: parts[1],
|
||||
}
|
||||
|
||||
return qr, nil
|
||||
}
|
||||
|
||||
func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {
|
||||
code, err := i.clientPointer[instance.Id].PairPhone(context.Background(), data.Phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] something went wrong calling pair phone", instance.Id)
|
||||
}
|
||||
|
||||
return &PairReturnStruct{PairingCode: code}, nil
|
||||
}
|
||||
|
||||
func (i instances) GetAll() ([]*instance_model.Instance, error) {
|
||||
instances, err := i.instanceRepository.GetAll(i.config.ClientName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, instance := range instances {
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
instance.Connected = false
|
||||
}
|
||||
|
||||
instance.Proxy = ""
|
||||
}
|
||||
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (i instances) Info(instanceId string) (*instance_model.Instance, error) {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(instanceId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Atualiza o status connected com base no estado real do cliente
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
instance.Connected = false
|
||||
}
|
||||
|
||||
instance.Proxy = ""
|
||||
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
func (i instances) Delete(id string) error {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() {
|
||||
if i.clientPointer[instance.Id].IsLoggedIn() {
|
||||
i.clientPointer[instance.Id].Logout(context.Background())
|
||||
}
|
||||
i.clientPointer[instance.Id].Disconnect()
|
||||
}
|
||||
|
||||
// Limpar todos os recursos da instância antes de deletar
|
||||
delete(i.clientPointer, instance.Id)
|
||||
if i.killChannel[instance.Id] != nil {
|
||||
close(i.killChannel[instance.Id])
|
||||
delete(i.killChannel, instance.Id)
|
||||
}
|
||||
|
||||
// Limpar cache via whatsmeow service
|
||||
err = i.whatsmeowService.ClearInstanceCache(instance.Id, instance.Token)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to clear instance cache: %v", instance.Id, err)
|
||||
}
|
||||
|
||||
err = i.instanceRepository.Delete(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) SetProxy(id string, proxyConfig *ProxyConfig) error {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Validate proxy configuration
|
||||
if proxyConfig == nil {
|
||||
return fmt.Errorf("proxy configuration cannot be nil")
|
||||
}
|
||||
|
||||
if proxyConfig.Host == "" {
|
||||
return fmt.Errorf("proxy host is required")
|
||||
}
|
||||
|
||||
if proxyConfig.Port == "" {
|
||||
return fmt.Errorf("proxy port is required")
|
||||
}
|
||||
|
||||
// Convert proxy config to JSON
|
||||
proxyJSON, err := json.Marshal(proxyConfig)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(id).LogError("[%s] Failed to marshal proxy config: %v", id, err)
|
||||
return fmt.Errorf("failed to marshal proxy configuration: %v", err)
|
||||
}
|
||||
|
||||
instance.Proxy = string(proxyJSON)
|
||||
|
||||
// Update instance in database
|
||||
err = i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(id).LogError("[%s] Failed to update instance with proxy: %v", id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration updated: %s:%s", id, proxyConfig.Host, proxyConfig.Port)
|
||||
|
||||
// Reconnect to apply proxy changes
|
||||
go i.Reconnect(instance)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) SetProxyFromStruct(id string, data *SetProxyStruct) error {
|
||||
if data == nil {
|
||||
return fmt.Errorf("proxy data cannot be nil")
|
||||
}
|
||||
|
||||
proxyConfig := &ProxyConfig{
|
||||
Host: data.Host,
|
||||
Port: data.Port,
|
||||
Username: data.Username,
|
||||
Password: data.Password,
|
||||
}
|
||||
|
||||
return i.SetProxy(id, proxyConfig)
|
||||
}
|
||||
|
||||
func (i instances) RemoveProxy(id string) error {
|
||||
instance, err := i.instanceRepository.GetInstanceByID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
instance.Proxy = ""
|
||||
|
||||
err = i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration removed", id)
|
||||
|
||||
go i.Reconnect(instance)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) ForceReconnect(instanceId string, number string) error {
|
||||
if i.clientPointer[instanceId].IsConnected() && i.clientPointer[instanceId].IsLoggedIn() {
|
||||
return fmt.Errorf("client already connected")
|
||||
}
|
||||
|
||||
err := i.whatsmeowService.ForceUpdateJid(instanceId, number)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
instance, err := i.instanceRepository.GetInstanceByID(instanceId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
subscribedEvents := strings.Split(instance.Events, ",")
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
Subscriptions: subscribedEvents,
|
||||
Phone: "",
|
||||
IsProxy: false,
|
||||
}
|
||||
|
||||
if instance.Proxy != "" || i.config.ProxyHost != "" {
|
||||
var proxyConfig ProxyConfig
|
||||
err := json.Unmarshal([]byte(instance.Proxy), &proxyConfig)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmarshalling proxy config: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if proxyConfig.Host != "" || i.config.ProxyHost != "" {
|
||||
clientData.IsProxy = true
|
||||
}
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
client := i.clientPointer[instance.Id]
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
}
|
||||
|
||||
go i.whatsmeowService.StartClient(clientData)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
if !i.clientPointer[instance.Id].IsConnected() {
|
||||
return fmt.Errorf("failed to connect")
|
||||
}
|
||||
|
||||
if !i.clientPointer[instance.Id].IsLoggedIn() {
|
||||
return fmt.Errorf("failed to login")
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("failed to connect")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i instances) GetInstanceByToken(token string) (*instance_model.Instance, error) {
|
||||
return i.instanceRepository.GetInstanceByToken(token)
|
||||
}
|
||||
|
||||
func (i instances) GetLogs(instanceId string, startDate, endDate time.Time, level string, limit int) ([]logger_wrapper.LogEntry, error) {
|
||||
// Inicializa o slice vazio para garantir que nunca retorne null
|
||||
logs := make([]logger_wrapper.LogEntry, 0)
|
||||
|
||||
// Define valores padrão
|
||||
if limit <= 0 {
|
||||
limit = 100 // Limite padrão de 100 registros
|
||||
}
|
||||
|
||||
// Se não foi fornecida data inicial, usa 7 dias atrás
|
||||
if startDate.IsZero() {
|
||||
startDate = time.Now().AddDate(0, 0, -7)
|
||||
}
|
||||
|
||||
// Se não foi fornecida data final, usa data atual
|
||||
if endDate.IsZero() {
|
||||
endDate = time.Now()
|
||||
}
|
||||
|
||||
// Ajusta as datas para início e fim do dia
|
||||
startDate = time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, time.UTC)
|
||||
endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, time.UTC)
|
||||
|
||||
// Garante que a data inicial não seja posterior à data final
|
||||
if startDate.After(endDate) {
|
||||
return logs, fmt.Errorf("data inicial não pode ser posterior à data final")
|
||||
}
|
||||
|
||||
// Níveis de log válidos
|
||||
validLevels := map[string]bool{
|
||||
"INFO": true,
|
||||
"ERROR": true,
|
||||
"WARN": true,
|
||||
"DEBUG": true,
|
||||
}
|
||||
|
||||
var levelArray []string
|
||||
if level == "" {
|
||||
// Se nenhum nível foi especificado, usa todos
|
||||
levelArray = []string{"INFO", "ERROR", "WARN", "DEBUG"}
|
||||
} else {
|
||||
// Divide e normaliza os níveis fornecidos
|
||||
for _, l := range strings.Split(level, ",") {
|
||||
l = strings.TrimSpace(strings.ToUpper(l))
|
||||
if !validLevels[l] {
|
||||
return logs, fmt.Errorf("nível de log inválido: %s", l)
|
||||
}
|
||||
levelArray = append(levelArray, l)
|
||||
}
|
||||
}
|
||||
|
||||
// Lê os logs do arquivo
|
||||
logPath := filepath.Join(i.config.LogDirectory, instanceId, "instance.log")
|
||||
file, err := os.Open(logPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return logs, nil // Retorna array vazio se arquivo não existir
|
||||
}
|
||||
return logs, fmt.Errorf("erro ao abrir arquivo de log: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
|
||||
// Aumenta o buffer do scanner para lidar com linhas grandes
|
||||
const maxCapacity = 1024 * 1024 // 1MB
|
||||
buf := make([]byte, maxCapacity)
|
||||
scanner.Buffer(buf, maxCapacity)
|
||||
|
||||
for scanner.Scan() {
|
||||
var entry logger_wrapper.LogEntry
|
||||
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
|
||||
continue // Ignora linhas inválidas
|
||||
}
|
||||
|
||||
// Ajusta o timestamp da entrada para UTC para comparação correta
|
||||
entry.Timestamp = entry.Timestamp.UTC()
|
||||
|
||||
// Aplica os filtros
|
||||
if entry.Timestamp.Before(startDate) || entry.Timestamp.After(endDate) {
|
||||
continue
|
||||
}
|
||||
|
||||
if !slices.Contains(levelArray, entry.Level) {
|
||||
continue
|
||||
}
|
||||
|
||||
logs = append(logs, entry)
|
||||
|
||||
// Verifica o limite
|
||||
if len(logs) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return logs, fmt.Errorf("erro ao ler arquivo de log: %v", err)
|
||||
}
|
||||
|
||||
// Ordena os logs por timestamp em ordem decrescente
|
||||
sort.Slice(logs, func(i, j int) bool {
|
||||
return logs[i].Timestamp.After(logs[j].Timestamp)
|
||||
})
|
||||
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
func (i instances) GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error) {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Getting advanced settings", instanceId)
|
||||
|
||||
settings, err := i.instanceRepository.GetAdvancedSettings(instanceId)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting advanced settings: %v", instanceId, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Updating advanced settings", instanceId)
|
||||
|
||||
err := i.instanceRepository.UpdateAdvancedSettings(instanceId, settings)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error updating advanced settings: %v", instanceId, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Sincroniza as configurações na instância em execução
|
||||
err = i.whatsmeowService.UpdateInstanceAdvancedSettings(instanceId)
|
||||
if err != nil {
|
||||
i.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Error syncing advanced settings to runtime: %v", instanceId, err)
|
||||
// Não falha a operação, apenas loga o warning
|
||||
}
|
||||
|
||||
i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Advanced settings updated successfully", instanceId)
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewInstanceService(
|
||||
instanceRepository instance_repository.InstanceRepository,
|
||||
killChannel map[string](chan bool),
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
config *config.Config,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) InstanceService {
|
||||
return &instances{
|
||||
instanceRepository: instanceRepository,
|
||||
killChannel: killChannel,
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
config: config,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package event_types
|
||||
|
||||
const (
|
||||
ALL = "ALL"
|
||||
MESSAGE = "MESSAGE"
|
||||
SEND_MESSAGE = "SEND_MESSAGE"
|
||||
READ_RECEIPT = "READ_RECEIPT"
|
||||
PRESENCE = "PRESENCE"
|
||||
HISTORY_SYNC = "HISTORY_SYNC"
|
||||
CHAT_PRESENCE = "CHAT_PRESENCE"
|
||||
CALL = "CALL"
|
||||
CONNECTION = "CONNECTION"
|
||||
LABEL = "LABEL"
|
||||
CONTACT = "CONTACT"
|
||||
GROUP = "GROUP"
|
||||
NEWSLETTER = "NEWSLETTER"
|
||||
QRCODE = "QRCODE"
|
||||
)
|
||||
|
||||
var AllEventTypes = []string{
|
||||
MESSAGE,
|
||||
SEND_MESSAGE,
|
||||
READ_RECEIPT,
|
||||
PRESENCE,
|
||||
HISTORY_SYNC,
|
||||
CHAT_PRESENCE,
|
||||
CALL,
|
||||
CONNECTION,
|
||||
LABEL,
|
||||
CONTACT,
|
||||
GROUP,
|
||||
NEWSLETTER,
|
||||
QRCODE,
|
||||
}
|
||||
|
||||
var validEventTypes = map[string]bool{
|
||||
ALL: true,
|
||||
MESSAGE: true,
|
||||
SEND_MESSAGE: true,
|
||||
READ_RECEIPT: true,
|
||||
PRESENCE: true,
|
||||
HISTORY_SYNC: true,
|
||||
CHAT_PRESENCE: true,
|
||||
CALL: true,
|
||||
CONNECTION: true,
|
||||
LABEL: true,
|
||||
CONTACT: true,
|
||||
GROUP: true,
|
||||
NEWSLETTER: true,
|
||||
QRCODE: true,
|
||||
}
|
||||
|
||||
func IsEventType(eventType string) bool {
|
||||
return validEventTypes[eventType]
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
package label_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type LabelHandler interface {
|
||||
ChatLabel(ctx *gin.Context)
|
||||
MessageLabel(ctx *gin.Context)
|
||||
EditLabel(ctx *gin.Context)
|
||||
ChatUnlabel(ctx *gin.Context)
|
||||
MessageUnlabel(ctx *gin.Context)
|
||||
GetLabels(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type labelHandler struct {
|
||||
labelService label_service.LabelService
|
||||
}
|
||||
|
||||
// Add label to chat
|
||||
// @Summary Add label to chat
|
||||
// @Description Add label to chat
|
||||
// @Tags Label
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body label_service.ChatLabelStruct true "Label data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /label/chat [post]
|
||||
func (l *labelHandler) ChatLabel(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *label_service.ChatLabelStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.JID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.LabelID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = l.labelService.ChatLabel(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Add label to message
|
||||
// @Summary Add label to message
|
||||
// @Description Add label to message
|
||||
// @Tags Label
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body label_service.MessageLabelStruct true "Label data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /label/message [post]
|
||||
func (l *labelHandler) MessageLabel(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *label_service.MessageLabelStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.JID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.LabelID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.MessageID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = l.labelService.MessageLabel(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Edit label
|
||||
// @Summary Edit label
|
||||
// @Description Edit label
|
||||
// @Tags Label
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body label_service.EditLabelStruct true "Label data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /label/edit [post]
|
||||
func (l *labelHandler) EditLabel(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *label_service.EditLabelStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.LabelID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = l.labelService.EditLabel(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Remove label from chat
|
||||
// @Summary Remove label from chat
|
||||
// @Description Remove label from chat
|
||||
// @Tags Label
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body label_service.ChatLabelStruct true "Label data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /unlabel/chat [post]
|
||||
func (l *labelHandler) ChatUnlabel(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *label_service.ChatLabelStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.JID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.LabelID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = l.labelService.ChatUnlabel(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Remove label from message
|
||||
// @Summary Remove label from message
|
||||
// @Description Remove label from message
|
||||
// @Tags Label
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body label_service.MessageLabelStruct true "Label data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /unlabel/message [post]
|
||||
func (l *labelHandler) MessageUnlabel(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *label_service.MessageLabelStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.JID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.LabelID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.MessageID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = l.labelService.MessageUnlabel(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Get all labels
|
||||
// @Summary Get all labels
|
||||
// @Description Get all labels
|
||||
// @Tags Label
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /label [get]
|
||||
func (l *labelHandler) GetLabels(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
labels, err := l.labelService.GetLabels(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, labels)
|
||||
}
|
||||
|
||||
func NewLabelHandler(
|
||||
labelService label_service.LabelService,
|
||||
) LabelHandler {
|
||||
return &labelHandler{
|
||||
labelService: labelService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package label_model
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Label struct {
|
||||
Id string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
InstanceID string `json:"instance_id" gorm:"type:uuid"`
|
||||
LabelID string `json:"label_id"`
|
||||
LabelName string `json:"label_name"`
|
||||
LabelColor string `json:"label_color"`
|
||||
PredefinedId string `json:"predefined_id"`
|
||||
}
|
||||
|
||||
func (m *Label) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
m.Id = uuid.New().String()
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package label_repository
|
||||
|
||||
import (
|
||||
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type LabelRepository interface {
|
||||
InsertLabel(label label_model.Label) error
|
||||
UpdateLabel(label label_model.Label) error
|
||||
GetLabelByID(id string) (*label_model.Label, error)
|
||||
DeleteLabel(id string) error
|
||||
GetAllLabelsByInstanceID(instanceID string) ([]label_model.Label, error)
|
||||
UpsertLabel(label label_model.Label) error
|
||||
}
|
||||
|
||||
type labelRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (l *labelRepository) InsertLabel(label label_model.Label) error {
|
||||
return l.db.Create(&label).Error
|
||||
}
|
||||
|
||||
func (l *labelRepository) UpdateLabel(label label_model.Label) error {
|
||||
return l.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"label_id", "label_name", "label_color"}),
|
||||
}).Create(&label).Error
|
||||
}
|
||||
|
||||
func (l *labelRepository) GetLabelByID(id string) (*label_model.Label, error) {
|
||||
var label label_model.Label
|
||||
err := l.db.Where("id = ?", id).First(&label).Error
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &label, nil
|
||||
}
|
||||
|
||||
func (l *labelRepository) DeleteLabel(id string) error {
|
||||
return l.db.Where("id = ?", id).Delete(&label_model.Label{}).Error
|
||||
}
|
||||
|
||||
func (l *labelRepository) GetAllLabelsByInstanceID(instanceID string) ([]label_model.Label, error) {
|
||||
var labels []label_model.Label
|
||||
err := l.db.Where("instance_id = ?", instanceID).Find(&labels).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return labels, nil
|
||||
}
|
||||
|
||||
func (l *labelRepository) UpsertLabel(label label_model.Label) error {
|
||||
return l.db.Where("instance_id = ? AND label_id = ?",
|
||||
label.InstanceID,
|
||||
label.LabelID,
|
||||
).Assign(label_model.Label{
|
||||
LabelName: label.LabelName,
|
||||
LabelColor: label.LabelColor,
|
||||
PredefinedId: label.PredefinedId,
|
||||
}).FirstOrCreate(&label).Error
|
||||
}
|
||||
|
||||
func NewLabelRepository(db *gorm.DB) LabelRepository {
|
||||
return &labelRepository{db: db}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package label_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
|
||||
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/appstate"
|
||||
)
|
||||
|
||||
type LabelService interface {
|
||||
ChatLabel(data *ChatLabelStruct, instance *instance_model.Instance) error
|
||||
MessageLabel(data *MessageLabelStruct, instance *instance_model.Instance) error
|
||||
EditLabel(data *EditLabelStruct, instance *instance_model.Instance) error
|
||||
ChatUnlabel(data *ChatLabelStruct, instance *instance_model.Instance) error
|
||||
MessageUnlabel(data *MessageLabelStruct, instance *instance_model.Instance) error
|
||||
GetLabels(instance *instance_model.Instance) ([]label_model.Label, error)
|
||||
}
|
||||
|
||||
type labelService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
labelRepository label_repository.LabelRepository
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type ChatLabelStruct struct {
|
||||
JID string `json:"jid"`
|
||||
LabelID string `json:"labelId"`
|
||||
}
|
||||
|
||||
type MessageLabelStruct struct {
|
||||
JID string `json:"jid"`
|
||||
LabelID string `json:"labelId"`
|
||||
MessageID string `json:"messageId"`
|
||||
}
|
||||
|
||||
type EditLabelStruct struct {
|
||||
LabelID string `json:"labelId"`
|
||||
Name string `json:"name"`
|
||||
Color int `json:"color"`
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := l.clientPointer[instanceId]
|
||||
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := l.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
l.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = l.clientPointer[instanceId]
|
||||
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
l.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
l.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (l *labelService) ChatLabel(data *ChatLabelStruct, instance *instance_model.Instance) error {
|
||||
client, err := l.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jid, ok := utils.ParseJID(data.JID)
|
||||
if !ok {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildLabelChat(
|
||||
jid,
|
||||
data.LabelID,
|
||||
true,
|
||||
))
|
||||
if err != nil {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label chat: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *labelService) MessageLabel(data *MessageLabelStruct, instance *instance_model.Instance) error {
|
||||
client, err := l.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jid, ok := utils.ParseJID(data.JID)
|
||||
if !ok {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildLabelMessage(
|
||||
jid,
|
||||
data.LabelID,
|
||||
data.MessageID,
|
||||
true,
|
||||
))
|
||||
if err != nil {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *labelService) EditLabel(data *EditLabelStruct, instance *instance_model.Instance) error {
|
||||
client, err := l.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildLabelEdit(
|
||||
data.LabelID,
|
||||
data.Name,
|
||||
int32(data.Color),
|
||||
data.Deleted,
|
||||
))
|
||||
if err != nil {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *labelService) ChatUnlabel(data *ChatLabelStruct, instance *instance_model.Instance) error {
|
||||
client, err := l.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jid, ok := utils.ParseJID(data.JID)
|
||||
if !ok {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildLabelChat(
|
||||
jid,
|
||||
data.LabelID,
|
||||
false,
|
||||
))
|
||||
if err != nil {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label chat: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *labelService) MessageUnlabel(data *MessageLabelStruct, instance *instance_model.Instance) error {
|
||||
client, err := l.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jid, ok := utils.ParseJID(data.JID)
|
||||
if !ok {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
|
||||
return errors.New("error parse community jid")
|
||||
}
|
||||
|
||||
err = client.SendAppState(context.Background(), appstate.BuildLabelMessage(
|
||||
jid,
|
||||
data.LabelID,
|
||||
data.MessageID,
|
||||
false,
|
||||
))
|
||||
if err != nil {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *labelService) GetLabels(instance *instance_model.Instance) ([]label_model.Label, error) {
|
||||
_, err := l.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
labels, err := l.labelRepository.GetAllLabelsByInstanceID(instance.Id)
|
||||
if err != nil {
|
||||
l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error fetching labels from database: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return labels, nil
|
||||
}
|
||||
|
||||
func NewLabelService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
labelRepository label_repository.LabelRepository,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) LabelService {
|
||||
return &labelService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
labelRepository: labelRepository,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/config"
|
||||
"github.com/gomessguii/logger"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
type LoggerManager struct {
|
||||
config *config.Config
|
||||
loggers map[string]*Logger
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
type Logger struct {
|
||||
config *config.Config
|
||||
instanceId string
|
||||
mu sync.Mutex
|
||||
writer *lumberjack.Logger
|
||||
}
|
||||
|
||||
type LogEntry struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Level string `json:"level"`
|
||||
InstanceId string `json:"instance_id"`
|
||||
Message string `json:"message"`
|
||||
Metadata json.RawMessage `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
func NewLoggerManager(config *config.Config) *LoggerManager {
|
||||
// Garante que o diretório base de logs existe
|
||||
if err := os.MkdirAll(config.LogDirectory, 0755); err != nil {
|
||||
logger.LogError("Falha ao criar diretório base de logs: %v", err)
|
||||
}
|
||||
|
||||
return &LoggerManager{
|
||||
config: config,
|
||||
loggers: make(map[string]*Logger),
|
||||
}
|
||||
}
|
||||
|
||||
func (lm *LoggerManager) GetLogger(instanceId string) *Logger {
|
||||
lm.mu.RLock()
|
||||
logger, exists := lm.loggers[instanceId]
|
||||
lm.mu.RUnlock()
|
||||
|
||||
if exists {
|
||||
return logger
|
||||
}
|
||||
|
||||
lm.mu.Lock()
|
||||
defer lm.mu.Unlock()
|
||||
|
||||
// Verificar novamente após obter o lock de escrita
|
||||
if logger, exists = lm.loggers[instanceId]; exists {
|
||||
return logger
|
||||
}
|
||||
|
||||
// Criar novo logger para a instância
|
||||
logger = newLogger(instanceId, lm.config)
|
||||
lm.loggers[instanceId] = logger
|
||||
return logger
|
||||
}
|
||||
|
||||
func newLogger(instanceId string, config *config.Config) *Logger {
|
||||
// Garante que o diretório existe
|
||||
logPath := filepath.Join(config.LogDirectory, instanceId)
|
||||
os.MkdirAll(logPath, 0755)
|
||||
|
||||
logFile := filepath.Join(logPath, "instance.log")
|
||||
|
||||
writer := &lumberjack.Logger{
|
||||
Filename: logFile,
|
||||
MaxSize: config.LogMaxSize,
|
||||
MaxBackups: config.LogMaxBackups,
|
||||
MaxAge: config.LogMaxAge,
|
||||
Compress: config.LogCompress,
|
||||
}
|
||||
|
||||
return &Logger{
|
||||
config: config,
|
||||
instanceId: instanceId,
|
||||
writer: writer,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Logger) LogInfo(format string, args ...interface{}) {
|
||||
l.log("INFO", format, args...)
|
||||
logger.LogInfo(format, args...)
|
||||
}
|
||||
|
||||
func (l *Logger) LogError(format string, args ...interface{}) {
|
||||
l.log("ERROR", format, args...)
|
||||
logger.LogError(format, args...)
|
||||
}
|
||||
|
||||
func (l *Logger) LogWarn(format string, args ...interface{}) {
|
||||
l.log("WARN", format, args...)
|
||||
logger.LogWarn(format, args...)
|
||||
}
|
||||
|
||||
func (l *Logger) LogDebug(format string, args ...interface{}) {
|
||||
l.log("DEBUG", format, args...)
|
||||
logger.LogDebug(format, args...)
|
||||
}
|
||||
|
||||
func (l *Logger) log(level string, format string, args ...interface{}) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
entry := LogEntry{
|
||||
Timestamp: time.Now(),
|
||||
Level: level,
|
||||
InstanceId: l.instanceId,
|
||||
Message: fmt.Sprintf(format, args...),
|
||||
}
|
||||
|
||||
jsonEntry, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
logger.LogError("Failed to marshal log entry: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := l.writer.Write(append(jsonEntry, '\n')); err != nil {
|
||||
logger.LogError("Failed to write log: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Logger) Close() error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.writer.Close()
|
||||
}
|
||||
|
||||
// GetLogs retorna os logs da instância com filtros opcionais
|
||||
func (l *Logger) GetLogs(startDate, endDate time.Time, level string, limit int) ([]LogEntry, error) {
|
||||
// Implementação movida para o service
|
||||
return nil, fmt.Errorf("método movido para instance_service")
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
package message_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type MessageHandler interface {
|
||||
React(ctx *gin.Context)
|
||||
ChatPresence(ctx *gin.Context)
|
||||
MarkRead(ctx *gin.Context)
|
||||
DownloadMedia(ctx *gin.Context)
|
||||
GetMessageStatus(ctx *gin.Context)
|
||||
DeleteMessageEveryone(ctx *gin.Context)
|
||||
EditMessage(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type messageHandler struct {
|
||||
messageService message_service.MessageService
|
||||
}
|
||||
|
||||
// React a message
|
||||
// @Summary React a message
|
||||
// @Description React to a message with support for fromMe field and participant field for group messages
|
||||
// @Tags Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body message_service.ReactStruct true "React to a message with fromMe and participant fields"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /message/react [post]
|
||||
func (m *messageHandler) React(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *message_service.ReactStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Reaction == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message reaction is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := m.messageService.React(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// ChatPresence set chat presence
|
||||
// @Summary Set chat presence
|
||||
// @Description Set chat presence
|
||||
// @Tags Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body message_service.ChatPresenceStruct true "Set chat presence"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /message/presence [post]
|
||||
func (m *messageHandler) ChatPresence(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *message_service.ChatPresenceStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.State == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "state is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := m.messageService.ChatPresence(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// MarkRead mark a message as read
|
||||
// @Summary Mark a message as read
|
||||
// @Description Mark a message as read
|
||||
// @Tags Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body message_service.MarkReadStruct true "Mark a message as read"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /message/markread [post]
|
||||
func (m *messageHandler) MarkRead(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *message_service.MarkReadStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.Id) < 1 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
ts, err := m.messageService.MarkRead(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// DownloadImage download an image
|
||||
// @Summary Download an image
|
||||
// @Description Download an image
|
||||
// @Tags Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body message_service.DownloadImageStruct true "Download an image"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /message/downloadimage [post]
|
||||
func (m *messageHandler) DownloadMedia(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *message_service.DownloadMediaStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dataUrl, ts, err := m.messageService.DownloadMedia(data, instance, ctx.Request)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"base64": dataUrl.String(),
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// GetMessageStatus get message status
|
||||
// @Summary Get message status
|
||||
// @Description Get message status
|
||||
// @Tags Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body message_service.MessageStatusStruct true "Get message status"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /message/status [post]
|
||||
func (m *messageHandler) GetMessageStatus(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *message_service.MessageStatusStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Id == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, ts, err := m.messageService.GetMessageStatus(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"result": message,
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// DeleteMessageEveryone delete a message for everyone
|
||||
// @Summary Delete a message for everyone
|
||||
// @Description Delete a message for everyone
|
||||
// @Tags Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body message_service.MessageStruct true "Delete a message for everyone"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /message/delete [post]
|
||||
func (m *messageHandler) DeleteMessageEveryone(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *message_service.MessageStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.MessageID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "messageId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
msgId, ts, err := m.messageService.DeleteMessageEveryone(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"messageId": msgId,
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
// EditMessage edit a message
|
||||
// @Summary Edit a message
|
||||
// @Description Edit a message
|
||||
// @Tags Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body message_service.EditMessageStruct true "Edit a message"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /message/edit [post]
|
||||
func (m *messageHandler) EditMessage(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *message_service.EditMessageStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Chat == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Message == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.MessageID == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "messageId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
msgId, ts, err := m.messageService.EditMessage(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responseData := gin.H{
|
||||
"messageId": msgId,
|
||||
"timestamp": ts,
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
|
||||
}
|
||||
|
||||
func NewMessageHandler(
|
||||
messageService message_service.MessageService,
|
||||
) MessageHandler {
|
||||
return &messageHandler{
|
||||
messageService: messageService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package message_model
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Id string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
MessageID string `json:"message_id" gorm:"unique"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
m.Id = uuid.New().String()
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package message_repository
|
||||
|
||||
import (
|
||||
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type MessageRepository interface {
|
||||
InsertMessage(message message_model.Message) error
|
||||
GetMessageByID(messageID string) (*message_model.Message, error)
|
||||
DeleteAllMessages() (int64, error)
|
||||
GetLatestMessageID(source string) (string, string, error)
|
||||
}
|
||||
|
||||
type messageRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (m *messageRepository) InsertMessage(message message_model.Message) error {
|
||||
return m.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "message_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"timestamp", "status", "source"}),
|
||||
}).Create(&message).Error
|
||||
}
|
||||
|
||||
func (m *messageRepository) GetMessageByID(messageID string) (*message_model.Message, error) {
|
||||
var message message_model.Message
|
||||
err := m.db.Where("message_id = ?", messageID).First(&message).Error
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
func (m *messageRepository) DeleteAllMessages() (int64, error) {
|
||||
result := m.db.Exec("DELETE FROM messages")
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
func (m *messageRepository) GetLatestMessageID(source string) (string, string, error) {
|
||||
var message message_model.Message
|
||||
err := m.db.Where("source = ?", source).Order("timestamp DESC").First(&message).Error
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return "", "", nil
|
||||
}
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
return message.MessageID, message.Timestamp, nil
|
||||
}
|
||||
|
||||
func NewMessageRepository(db *gorm.DB) MessageRepository {
|
||||
return &messageRepository{db: db}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
package message_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
|
||||
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/utils"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"github.com/vincent-petithory/dataurl"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/proto/waCommon"
|
||||
"go.mau.fi/whatsmeow/proto/waE2E"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type MessageService interface {
|
||||
React(data *ReactStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
|
||||
ChatPresence(data *ChatPresenceStruct, instance *instance_model.Instance) (string, error)
|
||||
MarkRead(data *MarkReadStruct, instance *instance_model.Instance) (string, error)
|
||||
DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error)
|
||||
GetMessageStatus(data *MessageStatusStruct, instance *instance_model.Instance) (*message_model.Message, string, error)
|
||||
DeleteMessageEveryone(data *MessageStruct, instance *instance_model.Instance) (string, string, error)
|
||||
EditMessage(data *EditMessageStruct, instance *instance_model.Instance) (string, string, error)
|
||||
}
|
||||
|
||||
type messageService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
messageRepository message_repository.MessageRepository
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type ReactStruct struct {
|
||||
Number string `json:"number"`
|
||||
Reaction string `json:"reaction"`
|
||||
Id string `json:"id"`
|
||||
FromMe bool `json:"fromMe"`
|
||||
Participant string `json:"participant,omitempty"`
|
||||
}
|
||||
|
||||
type ChatPresenceStruct struct {
|
||||
Number string `json:"number"`
|
||||
State string `json:"state"`
|
||||
IsAudio bool `json:"isAudio"`
|
||||
}
|
||||
|
||||
type MarkReadStruct struct {
|
||||
Id []string `json:"id"`
|
||||
Number string `json:"number"`
|
||||
}
|
||||
|
||||
type DownloadMediaStruct struct {
|
||||
Message *waE2E.Message `json:"message"`
|
||||
}
|
||||
|
||||
type MessageStatusStruct struct {
|
||||
Id string `json:"id"`
|
||||
}
|
||||
|
||||
type MessageStruct struct {
|
||||
Chat string `json:"chat"`
|
||||
MessageID string `json:"messageId"`
|
||||
}
|
||||
|
||||
type EditMessageStruct struct {
|
||||
Chat string `json:"chat"`
|
||||
Message string `json:"message"`
|
||||
MessageID string `json:"messageId"`
|
||||
}
|
||||
|
||||
type MessageSendStruct struct {
|
||||
Info types.MessageInfo
|
||||
Message *waE2E.Message
|
||||
MessageContextInfo *waE2E.ContextInfo
|
||||
}
|
||||
|
||||
func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := m.clientPointer[instanceId]
|
||||
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := m.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = m.clientPointer[instanceId]
|
||||
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
m.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
m.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (m *messageService) React(data *ReactStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {
|
||||
client, err := m.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgId := ""
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Number)
|
||||
if !ok {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return nil, errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
if data.Id == "" {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Missing Id in Payload", instance.Id)
|
||||
return nil, errors.New("missing id in payload")
|
||||
} else {
|
||||
msgId = data.Id
|
||||
}
|
||||
|
||||
fromMe := data.FromMe
|
||||
reaction := data.Reaction
|
||||
if reaction == "remove" {
|
||||
reaction = ""
|
||||
}
|
||||
|
||||
// Create MessageKey
|
||||
messageKey := &waCommon.MessageKey{
|
||||
RemoteJID: proto.String(recipient.String()),
|
||||
FromMe: proto.Bool(fromMe),
|
||||
ID: proto.String(msgId),
|
||||
}
|
||||
|
||||
// Add participant if provided (for group messages)
|
||||
if data.Participant != "" {
|
||||
participantJID, ok := utils.ParseJID(data.Participant)
|
||||
if ok {
|
||||
messageKey.Participant = proto.String(participantJID.String())
|
||||
}
|
||||
}
|
||||
|
||||
msg := &waE2E.Message{
|
||||
ReactionMessage: &waE2E.ReactionMessage{
|
||||
Key: messageKey,
|
||||
Text: proto.String(reaction),
|
||||
// GroupingKey: proto.String(reaction),
|
||||
SenderTimestampMS: proto.Int64(time.Now().UnixMilli()),
|
||||
},
|
||||
}
|
||||
|
||||
response, err := client.SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{
|
||||
ID: msgId,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
isGroup := strings.Contains(data.Number, "@g.us")
|
||||
messageType := "ReactionMessage"
|
||||
|
||||
messageInfo := types.MessageInfo{
|
||||
MessageSource: types.MessageSource{
|
||||
Chat: recipient,
|
||||
Sender: *client.Store.ID,
|
||||
IsFromMe: true,
|
||||
IsGroup: isGroup,
|
||||
},
|
||||
ID: msgId,
|
||||
Timestamp: time.Now(),
|
||||
ServerID: response.ServerID,
|
||||
Type: messageType,
|
||||
}
|
||||
|
||||
messageSent := &MessageSendStruct{
|
||||
Info: messageInfo,
|
||||
Message: msg,
|
||||
}
|
||||
|
||||
return messageSent, nil
|
||||
}
|
||||
|
||||
func (m *messageService) ChatPresence(data *ChatPresenceStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := m.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Number)
|
||||
if !ok {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
media := ""
|
||||
|
||||
if data.IsAudio {
|
||||
media = "audio"
|
||||
}
|
||||
|
||||
err = client.SendChatPresence(context.Background(), recipient, types.ChatPresence(data.State), types.ChatPresenceMedia(media))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogInfo("Message sent to %s", data.Number)
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (m *messageService) MarkRead(data *MarkReadStruct, instance *instance_model.Instance) (string, error) {
|
||||
client, err := m.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
jid, ok := utils.ParseJID(data.Number)
|
||||
if !ok {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
err = client.MarkRead(context.Background(), data.Id, time.Now(), jid, jid)
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error marking message as read: %v", instance.Id, err)
|
||||
return "", errors.New("error marking message as read")
|
||||
}
|
||||
|
||||
return ts.String(), nil
|
||||
}
|
||||
|
||||
func (m *messageService) DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error) {
|
||||
client, err := m.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
msg := data.Message
|
||||
|
||||
mimetype := ""
|
||||
var mediaData []byte
|
||||
|
||||
img := msg.GetImageMessage()
|
||||
audio := msg.GetAudioMessage()
|
||||
document := msg.GetDocumentMessage()
|
||||
video := msg.GetVideoMessage()
|
||||
sticker := msg.GetStickerMessage()
|
||||
|
||||
if img == nil && audio == nil && document == nil && video == nil && sticker == nil {
|
||||
return nil, "", errors.New("invalid media type")
|
||||
}
|
||||
|
||||
userDirectory := fmt.Sprintf(`files/user_%s`, instance.Id)
|
||||
_, err = os.Stat(userDirectory)
|
||||
if os.IsNotExist(err) {
|
||||
errDir := os.MkdirAll(userDirectory, 0751)
|
||||
if errDir != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not create user directory (%s)", instance.Id, userDirectory)
|
||||
return nil, "", errDir
|
||||
}
|
||||
}
|
||||
|
||||
if img != nil {
|
||||
mediaData, err = client.Download(context.Background(), img)
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download image", instance.Id)
|
||||
msg := fmt.Sprintf("Failed to download image %v", err)
|
||||
return nil, "", errors.New(msg)
|
||||
}
|
||||
mimetype = img.GetMimetype()
|
||||
}
|
||||
|
||||
if audio != nil {
|
||||
mediaData, err = client.Download(context.Background(), audio)
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download audio", instance.Id)
|
||||
msg := fmt.Sprintf("Failed to download audio %v", err)
|
||||
return nil, "", errors.New(msg)
|
||||
}
|
||||
mimetype = audio.GetMimetype()
|
||||
}
|
||||
|
||||
if document != nil {
|
||||
mediaData, err = client.Download(context.Background(), document)
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download document", instance.Id)
|
||||
msg := fmt.Sprintf("Failed to download document %v", err)
|
||||
return nil, "", errors.New(msg)
|
||||
}
|
||||
mimetype = document.GetMimetype()
|
||||
}
|
||||
|
||||
if video != nil {
|
||||
mediaData, err = client.Download(context.Background(), video)
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download video", instance.Id)
|
||||
msg := fmt.Sprintf("Failed to download video %v", err)
|
||||
return nil, "", errors.New(msg)
|
||||
}
|
||||
mimetype = video.GetMimetype()
|
||||
}
|
||||
|
||||
if sticker != nil {
|
||||
mediaData, err = client.Download(context.Background(), sticker)
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download sticker", instance.Id)
|
||||
msg := fmt.Sprintf("Failed to download sticker %v", err)
|
||||
return nil, "", errors.New(msg)
|
||||
}
|
||||
mimetype = sticker.GetMimetype()
|
||||
}
|
||||
|
||||
dataURL := dataurl.New(mediaData, mimetype)
|
||||
|
||||
return dataURL, ts.String(), nil
|
||||
}
|
||||
|
||||
func (m *messageService) GetMessageStatus(data *MessageStatusStruct, instance *instance_model.Instance) (*message_model.Message, string, error) {
|
||||
_, err := m.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
result, err := m.messageRepository.GetMessageByID(data.Id)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return result, ts.String(), nil
|
||||
}
|
||||
|
||||
func (m *messageService) DeleteMessageEveryone(data *MessageStruct, instance *instance_model.Instance) (string, string, error) {
|
||||
client, err := m.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogInfo("Revoking message %s from %s", data.MessageID, recipient)
|
||||
|
||||
resp, err := client.SendMessage(
|
||||
context.Background(),
|
||||
recipient,
|
||||
client.BuildRevoke(recipient, types.EmptyJID, data.MessageID))
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error revoking message: %v", instance.Id, err)
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
response := resp.ID
|
||||
|
||||
return response, ts.String(), nil
|
||||
}
|
||||
|
||||
func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance_model.Instance) (string, string, error) {
|
||||
client, err := m.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
var ts time.Time
|
||||
|
||||
recipient, ok := utils.ParseJID(data.Chat)
|
||||
if !ok {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
||||
return "", "", errors.New("invalid phone number")
|
||||
}
|
||||
|
||||
resp, err := client.SendMessage(
|
||||
context.Background(),
|
||||
recipient,
|
||||
client.BuildEdit(
|
||||
recipient,
|
||||
data.MessageID,
|
||||
&waE2E.Message{
|
||||
Conversation: proto.String(data.Message),
|
||||
}))
|
||||
if err != nil {
|
||||
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error revoking message: %v", instance.Id, err)
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
response := resp.ID
|
||||
|
||||
return response, ts.String(), nil
|
||||
}
|
||||
|
||||
func NewMessageService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
messageRepository message_repository.MessageRepository,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) MessageService {
|
||||
return &messageService{
|
||||
clientPointer: clientPointer,
|
||||
messageRepository: messageRepository,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package auth_middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/config"
|
||||
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Middleware interface {
|
||||
Auth(ctx *gin.Context)
|
||||
AuthAdmin(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type middleware struct {
|
||||
config *config.Config
|
||||
instanceService instance_service.InstanceService
|
||||
}
|
||||
|
||||
func (m middleware) Auth(ctx *gin.Context) {
|
||||
token := ctx.GetHeader("apikey")
|
||||
if token == "" {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
|
||||
return
|
||||
}
|
||||
|
||||
instance, err := m.instanceService.GetInstanceByToken(token)
|
||||
if err != nil {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Set("instance", instance)
|
||||
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func (m middleware) AuthAdmin(ctx *gin.Context) {
|
||||
token := ctx.GetHeader("apikey")
|
||||
if token == "" {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
|
||||
return
|
||||
}
|
||||
|
||||
if token != m.config.GlobalApiKey {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func NewMiddleware(config *config.Config, instanceService instance_service.InstanceService) *middleware {
|
||||
return &middleware{config: config, instanceService: instanceService}
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
package auth_middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gomessguii/logger"
|
||||
)
|
||||
|
||||
// JIDValidationMiddleware validates JID parameters in request bodies
|
||||
type JIDValidationMiddleware struct{}
|
||||
|
||||
// NewJIDValidationMiddleware creates a new JID validation middleware
|
||||
func NewJIDValidationMiddleware() *JIDValidationMiddleware {
|
||||
return &JIDValidationMiddleware{}
|
||||
}
|
||||
|
||||
// ValidateJIDFields validates and normalizes JID fields in request body
|
||||
func (m *JIDValidationMiddleware) ValidateJIDFields(fieldNames ...string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Only process JSON requests
|
||||
contentType := c.ContentType()
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
// For multipart/form-data, validate form fields
|
||||
if strings.Contains(contentType, "multipart/form-data") {
|
||||
m.validateFormFields(c, fieldNames...)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Read the request body
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Restore the request body for downstream handlers
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
// Parse JSON
|
||||
var requestData map[string]interface{}
|
||||
if err := json.Unmarshal(body, &requestData); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Validate and normalize JID fields
|
||||
modified := false
|
||||
for _, fieldName := range fieldNames {
|
||||
if value, exists := requestData[fieldName]; exists {
|
||||
if strValue, ok := value.(string); ok && strValue != "" {
|
||||
// Validate and normalize the JID
|
||||
normalizedJID, err := utils.CreateJID(strValue)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid %s format: %s", fieldName, err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Update the value if it was normalized
|
||||
if normalizedJID != strValue {
|
||||
requestData[fieldName] = normalizedJID
|
||||
modified = true
|
||||
logger.LogDebug("Normalized %s from %s to %s", fieldName, strValue, normalizedJID)
|
||||
}
|
||||
} else if strValue == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("%s is required and cannot be empty", fieldName),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we modified the request, update the body
|
||||
if modified {
|
||||
newBody, err := json.Marshal(requestData)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// validateFormFields validates JID fields in multipart form data
|
||||
func (m *JIDValidationMiddleware) validateFormFields(c *gin.Context, fieldNames ...string) {
|
||||
for _, fieldName := range fieldNames {
|
||||
value := c.PostForm(fieldName)
|
||||
if value != "" {
|
||||
// Validate the JID format
|
||||
_, err := utils.CreateJID(value)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid %s format: %s", fieldName, err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
} else if fieldName == "number" { // number is typically required
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("%s is required and cannot be empty", fieldName),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// ValidateNumberField is a convenience method for the common "number" field
|
||||
// It handles both single strings and arrays of strings
|
||||
func (m *JIDValidationMiddleware) ValidateNumberField() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Only process JSON requests
|
||||
contentType := c.ContentType()
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
// For multipart/form-data, validate form fields
|
||||
if strings.Contains(contentType, "multipart/form-data") {
|
||||
m.validateFormFields(c, "number")
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Read the request body
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Restore the request body for downstream handlers
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
// Parse JSON
|
||||
var requestData map[string]interface{}
|
||||
if err := json.Unmarshal(body, &requestData); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Validate and normalize number field (can be string or array)
|
||||
modified := false
|
||||
if value, exists := requestData["number"]; exists {
|
||||
// Handle array of strings
|
||||
if arrayValue, ok := value.([]interface{}); ok {
|
||||
if len(arrayValue) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "number array cannot be empty",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
for i, item := range arrayValue {
|
||||
if strValue, ok := item.(string); ok && strValue != "" {
|
||||
normalizedJID, err := utils.CreateJID(strValue)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid number[%d] format: %s", i, err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if normalizedJID != strValue {
|
||||
arrayValue[i] = normalizedJID
|
||||
modified = true
|
||||
logger.LogDebug("Normalized number[%d] from %s to %s", i, strValue, normalizedJID)
|
||||
}
|
||||
} else if strValue == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("number[%d] cannot be empty", i),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
} else if strValue, ok := value.(string); ok {
|
||||
// Handle single string
|
||||
if strValue == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "number is required and cannot be empty",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
normalizedJID, err := utils.CreateJID(strValue)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid number format: %s", err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if normalizedJID != strValue {
|
||||
requestData["number"] = normalizedJID
|
||||
modified = true
|
||||
logger.LogDebug("Normalized number from %s to %s", strValue, normalizedJID)
|
||||
}
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "number must be a string or array of strings",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// If we modified the request, update the body
|
||||
if modified {
|
||||
newBody, err := json.Marshal(requestData)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateMultipleNumbers validates multiple number fields (for arrays or multiple contacts)
|
||||
func (m *JIDValidationMiddleware) ValidateMultipleNumbers(fieldName string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Only process JSON requests
|
||||
contentType := c.ContentType()
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Read the request body
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Restore the request body for downstream handlers
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
// Parse JSON
|
||||
var requestData map[string]interface{}
|
||||
if err := json.Unmarshal(body, &requestData); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Validate array of numbers
|
||||
if value, exists := requestData[fieldName]; exists {
|
||||
modified := false
|
||||
|
||||
// Handle array of strings
|
||||
if arrayValue, ok := value.([]interface{}); ok {
|
||||
for i, item := range arrayValue {
|
||||
if strValue, ok := item.(string); ok && strValue != "" {
|
||||
normalizedJID, err := utils.CreateJID(strValue)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid %s[%d] format: %s", fieldName, i, err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if normalizedJID != strValue {
|
||||
arrayValue[i] = normalizedJID
|
||||
modified = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we modified the request, update the body
|
||||
if modified {
|
||||
newBody, err := json.Marshal(requestData)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
|
||||
}
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateNumberFieldWithFormatJid validates number field but respects FormatJid parameter
|
||||
// When FormatJid is true (default), numbers are normalized to full JID format
|
||||
// When FormatJid is false, numbers are kept as received (raw format)
|
||||
func (m *JIDValidationMiddleware) ValidateNumberFieldWithFormatJid() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Only process JSON requests
|
||||
contentType := c.ContentType()
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Read the request body
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Restore the request body for downstream handlers
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
// Parse JSON
|
||||
var requestData map[string]interface{}
|
||||
if err := json.Unmarshal(body, &requestData); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Check FormatJid parameter (default is true)
|
||||
formatJid := true
|
||||
if formatJidValue, exists := requestData["formatJid"]; exists {
|
||||
if formatJidBool, ok := formatJidValue.(bool); ok {
|
||||
formatJid = formatJidBool
|
||||
}
|
||||
}
|
||||
|
||||
// Validate and optionally normalize number field based on FormatJid
|
||||
modified := false
|
||||
if value, exists := requestData["number"]; exists {
|
||||
// Handle array of strings
|
||||
if arrayValue, ok := value.([]interface{}); ok {
|
||||
if len(arrayValue) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "number array cannot be empty",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
for i, item := range arrayValue {
|
||||
if strValue, ok := item.(string); ok && strValue != "" {
|
||||
// Only validate and normalize if FormatJid is true
|
||||
if formatJid {
|
||||
normalizedJID, err := utils.CreateJID(strValue)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid number[%d] format: %s", i, err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if normalizedJID != strValue {
|
||||
arrayValue[i] = normalizedJID
|
||||
modified = true
|
||||
logger.LogDebug("Normalized number[%d] from %s to %s", i, strValue, normalizedJID)
|
||||
}
|
||||
}
|
||||
// When formatJid is false, we accept numbers as received without validation
|
||||
} else if strValue == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("number[%d] cannot be empty", i),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
} else if strValue, ok := value.(string); ok {
|
||||
// Handle single string
|
||||
if strValue == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "number is required and cannot be empty",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Only validate and normalize if FormatJid is true
|
||||
if formatJid {
|
||||
normalizedJID, err := utils.CreateJID(strValue)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid number format: %s", err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if normalizedJID != strValue {
|
||||
requestData["number"] = normalizedJID
|
||||
modified = true
|
||||
logger.LogDebug("Normalized number from %s to %s", strValue, normalizedJID)
|
||||
}
|
||||
}
|
||||
// When formatJid is false, we accept numbers as received without validation
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "number must be a string or array of strings",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// If we modified the request, update the body
|
||||
if modified {
|
||||
newBody, err := json.Marshal(requestData)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateContactFields validates contact-specific fields that may contain phone numbers
|
||||
func (m *JIDValidationMiddleware) ValidateContactFields() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Only process JSON requests
|
||||
contentType := c.ContentType()
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Read the request body
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Restore the request body for downstream handlers
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
// Parse JSON
|
||||
var requestData map[string]interface{}
|
||||
if err := json.Unmarshal(body, &requestData); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
modified := false
|
||||
|
||||
// Validate main number field
|
||||
if value, exists := requestData["number"]; exists {
|
||||
if strValue, ok := value.(string); ok && strValue != "" {
|
||||
normalizedJID, err := utils.CreateJID(strValue)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid number format: %s", err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if normalizedJID != strValue {
|
||||
requestData["number"] = normalizedJID
|
||||
modified = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate vcard phone field if present
|
||||
if vcardValue, exists := requestData["vcard"]; exists {
|
||||
if vcardMap, ok := vcardValue.(map[string]interface{}); ok {
|
||||
if phoneValue, phoneExists := vcardMap["phone"]; phoneExists {
|
||||
if phoneStr, ok := phoneValue.(string); ok && phoneStr != "" {
|
||||
// For vcard phone, we just validate format but don't necessarily convert to JID
|
||||
_, err := utils.CreateJID(phoneStr)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Invalid vcard phone format: %s", err.Error()),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we modified the request, update the body
|
||||
if modified {
|
||||
newBody, err := json.Marshal(requestData)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package newsletter_handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type NewsletterHandler interface {
|
||||
CreateNewsletter(ctx *gin.Context)
|
||||
ListNewsletter(ctx *gin.Context)
|
||||
GetNewsletter(ctx *gin.Context)
|
||||
GetNewsletterInvite(ctx *gin.Context)
|
||||
SubscribeNewsletter(ctx *gin.Context)
|
||||
GetNewsletterMessages(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type newsletterHandler struct {
|
||||
newsletterService newsletter_service.NewsletterService
|
||||
}
|
||||
|
||||
// Create newsletter
|
||||
// @Summary Create newsletter
|
||||
// @Description Create newsletter
|
||||
// @Tags Newsletter
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body newsletter_service.CreateNewsletterStruct true "Newsletter data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /newsletter/create [post]
|
||||
func (n *newsletterHandler) CreateNewsletter(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *newsletter_service.CreateNewsletterStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
newsletter, err := n.newsletterService.CreateNewsletter(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})
|
||||
}
|
||||
|
||||
// List newsletters
|
||||
// @Summary List newsletters
|
||||
// @Description List newsletters
|
||||
// @Tags Newsletter
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /newsletter/list [get]
|
||||
func (n *newsletterHandler) ListNewsletter(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
newsletters, err := n.newsletterService.ListNewsletter(instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletters})
|
||||
}
|
||||
|
||||
// Get newsletter
|
||||
// @Summary Get newsletter
|
||||
// @Description Get newsletter
|
||||
// @Tags Newsletter
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body newsletter_service.GetNewsletterStruct true "Newsletter data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /newsletter/info [post]
|
||||
func (n *newsletterHandler) GetNewsletter(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *newsletter_service.GetNewsletterStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.JID.String() == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
newsletter, err := n.newsletterService.GetNewsletter(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})
|
||||
}
|
||||
|
||||
// Get newsletter invite
|
||||
// @Summary Get newsletter invite
|
||||
// @Description Get newsletter invite
|
||||
// @Tags Newsletter
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body newsletter_service.GetNewsletterInviteStruct true "Newsletter data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /newsletter/link [post]
|
||||
func (n *newsletterHandler) GetNewsletterInvite(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *newsletter_service.GetNewsletterInviteStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Key == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "key is required"})
|
||||
return
|
||||
}
|
||||
|
||||
newsletter, err := n.newsletterService.GetNewsletterInvite(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})
|
||||
}
|
||||
|
||||
// Subscribe newsletter
|
||||
// @Summary Subscribe newsletter
|
||||
// @Description Subscribe newsletter
|
||||
// @Tags Newsletter
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body newsletter_service.GetNewsletterStruct true "Newsletter data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /newsletter/subscribe [post]
|
||||
func (n *newsletterHandler) SubscribeNewsletter(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *newsletter_service.GetNewsletterStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.JID.String() == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
err = n.newsletterService.SubscribeNewsletter(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
}
|
||||
|
||||
// Get newsletter messages
|
||||
// @Summary Get newsletter messages
|
||||
// @Description Get newsletter messages
|
||||
// @Tags Newsletter
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body newsletter_service.GetNewsletterMessagesStruct true "Newsletter data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /newsletter/messages [post]
|
||||
func (n *newsletterHandler) GetNewsletterMessages(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *newsletter_service.GetNewsletterMessagesStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.JID.String() == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})
|
||||
return
|
||||
}
|
||||
|
||||
messages, err := n.newsletterService.GetNewsletterMessages(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": messages})
|
||||
}
|
||||
|
||||
func NewNewsletterHandler(
|
||||
newsletterService newsletter_service.NewsletterService,
|
||||
) NewsletterHandler {
|
||||
return &newsletterHandler{
|
||||
newsletterService: newsletterService,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package newsletter_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
type NewsletterService interface {
|
||||
CreateNewsletter(data *CreateNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)
|
||||
ListNewsletter(instance *instance_model.Instance) ([]*types.NewsletterMetadata, error)
|
||||
GetNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)
|
||||
GetNewsletterInvite(data *GetNewsletterInviteStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)
|
||||
SubscribeNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) error
|
||||
GetNewsletterMessages(data *GetNewsletterMessagesStruct, instance *instance_model.Instance) ([]*types.NewsletterMessage, error)
|
||||
}
|
||||
|
||||
type newsletterService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
type CreateNewsletterStruct struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type GetNewsletterStruct struct {
|
||||
JID types.JID `json:"jid"`
|
||||
}
|
||||
|
||||
type GetNewsletterInviteStruct struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
type GetNewsletterMessagesStruct struct {
|
||||
JID types.JID `json:"jid"`
|
||||
Count int `json:"count"`
|
||||
BeforeID int `json:"before_id"`
|
||||
}
|
||||
|
||||
func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
client := n.clientPointer[instanceId]
|
||||
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
|
||||
err := n.whatsmeowService.StartInstance(instanceId)
|
||||
if err != nil {
|
||||
n.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
|
||||
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = n.clientPointer[instanceId]
|
||||
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
n.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
client != nil && client.IsConnected())
|
||||
return nil, errors.New("no active session found")
|
||||
}
|
||||
} else if !client.IsConnected() {
|
||||
n.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
|
||||
instanceId,
|
||||
client.IsConnected())
|
||||
return nil, errors.New("client disconnected")
|
||||
}
|
||||
|
||||
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (n *newsletterService) CreateNewsletter(data *CreateNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {
|
||||
client, err := n.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newsletter, err := client.CreateNewsletter(context.Background(), whatsmeow.CreateNewsletterParams{
|
||||
Name: data.Name,
|
||||
Description: data.Description,
|
||||
})
|
||||
if err != nil {
|
||||
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create newsletter: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newsletter, nil
|
||||
}
|
||||
|
||||
func (n *newsletterService) ListNewsletter(instance *instance_model.Instance) ([]*types.NewsletterMetadata, error) {
|
||||
client, err := n.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newsletters, err := client.GetSubscribedNewsletters(context.Background())
|
||||
if err != nil {
|
||||
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletters: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// For each newsletter, fetch full info to get subscribers_count
|
||||
fullNewsletters := make([]*types.NewsletterMetadata, 0, len(newsletters))
|
||||
for _, newsletter := range newsletters {
|
||||
fullInfo, err := client.GetNewsletterInfo(context.Background(), newsletter.ID)
|
||||
if err != nil {
|
||||
// If we can't get full info, use the basic one
|
||||
n.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] error getting full info for newsletter %s: %v", instance.Id, newsletter.ID.String(), err)
|
||||
fullNewsletters = append(fullNewsletters, newsletter)
|
||||
continue
|
||||
}
|
||||
fullNewsletters = append(fullNewsletters, fullInfo)
|
||||
}
|
||||
|
||||
return fullNewsletters, nil
|
||||
}
|
||||
|
||||
func (n *newsletterService) GetNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {
|
||||
client, err := n.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newsletter, err := client.GetNewsletterInfo(context.Background(), data.JID)
|
||||
if err != nil {
|
||||
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newsletter, nil
|
||||
}
|
||||
|
||||
func (n *newsletterService) GetNewsletterInvite(data *GetNewsletterInviteStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {
|
||||
client, err := n.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newsletter, err := client.GetNewsletterInfoWithInvite(context.Background(), data.Key)
|
||||
if err != nil {
|
||||
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newsletter, nil
|
||||
}
|
||||
|
||||
func (n *newsletterService) SubscribeNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) error {
|
||||
client, err := n.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.NewsletterSubscribeLiveUpdates(context.TODO(), data.JID)
|
||||
if err != nil {
|
||||
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *newsletterService) GetNewsletterMessages(data *GetNewsletterMessagesStruct, instance *instance_model.Instance) ([]*types.NewsletterMessage, error) {
|
||||
client, err := n.ensureClientConnected(instance.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
messages, err := client.GetNewsletterMessages(context.Background(), data.JID,
|
||||
&whatsmeow.GetNewsletterMessagesParams{
|
||||
Count: data.Count, Before: data.BeforeID,
|
||||
})
|
||||
if err != nil {
|
||||
n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
func NewNewsletterService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) NewsletterService {
|
||||
return &newsletterService{
|
||||
clientPointer: clientPointer,
|
||||
whatsmeowService: whatsmeowService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package poll_handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
poll_service "github.com/EvolutionAPI/evolution-go/pkg/poll/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type PollHandler struct {
|
||||
pollService poll_service.PollService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
// NewPollHandler cria handler usando PollService existente (evita dupla inicialização)
|
||||
func NewPollHandler(pollService poll_service.PollService, loggerWrapper *logger_wrapper.LoggerManager) *PollHandler {
|
||||
return &PollHandler{
|
||||
pollService: pollService,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
// GetPollResults retorna os resultados de uma enquete
|
||||
// @Summary Get poll results
|
||||
// @Description Retorna todos os votos de uma enquete específica
|
||||
// @Tags Polls
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param pollMessageId path string true "ID da mensagem da enquete"
|
||||
// @Success 200 {object} model.PollResults
|
||||
// @Failure 400 {object} gin.H
|
||||
// @Failure 404 {object} gin.H
|
||||
// @Failure 500 {object} gin.H
|
||||
// @Router /polls/{pollMessageId}/results [get]
|
||||
func (h *PollHandler) GetPollResults(c *gin.Context) {
|
||||
pollMessageID := c.Param("pollMessageId")
|
||||
|
||||
// Pegar instance do contexto de autenticação
|
||||
instanceInterface, exists := c.Get("instance")
|
||||
if !exists {
|
||||
h.loggerWrapper.GetLogger("poll-handler").LogWarn("[POLL] Instance not found in context")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Authentication required",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Converter para struct Instance
|
||||
type Instance struct {
|
||||
Id string `json:"id"`
|
||||
}
|
||||
instanceBytes, _ := json.Marshal(instanceInterface)
|
||||
var instance Instance
|
||||
if err := json.Unmarshal(instanceBytes, &instance); err != nil {
|
||||
h.loggerWrapper.GetLogger("poll-handler").LogError("[POLL] Failed to parse instance: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to get instance information",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
instanceID := instance.Id
|
||||
|
||||
// Validações de segurança
|
||||
if pollMessageID == "" {
|
||||
h.loggerWrapper.GetLogger("poll-handler").LogWarn("[POLL] Missing pollMessageId")
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "pollMessageId is required",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] Fetching results for poll %s (instance: %s)", pollMessageID, instanceID)
|
||||
|
||||
// Buscar resultados do banco
|
||||
results, err := h.pollService.GetPollResults(c.Request.Context(), pollMessageID, instanceID)
|
||||
if err != nil {
|
||||
h.loggerWrapper.GetLogger("poll-handler").LogError("[POLL] Error fetching results: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to fetch poll results",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if results.TotalVotes == 0 {
|
||||
h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] No votes found for poll %s", pollMessageID)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": "No votes found for this poll",
|
||||
"message": "This poll has no votes yet, or the pollMessageId is incorrect",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] Returning %d votes for poll %s", results.TotalVotes, pollMessageID)
|
||||
c.JSON(http.StatusOK, results)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// PollVote representa um voto em uma enquete do WhatsApp
|
||||
type PollVote struct {
|
||||
ID string `json:"id"`
|
||||
CompanyID string `json:"companyId"`
|
||||
InstanceID string `json:"instanceId"`
|
||||
PollMessageID string `json:"pollMessageId"`
|
||||
PollChatJid string `json:"pollChatJid"`
|
||||
VoteMessageID string `json:"voteMessageId"`
|
||||
VoterJid string `json:"voterJid"`
|
||||
VoterPhone string `json:"voterPhone,omitempty"`
|
||||
VoterName string `json:"voterName,omitempty"`
|
||||
SelectedOptions []string `json:"selectedOptions"` // SHA-256 hashes
|
||||
VotedAt time.Time `json:"votedAt"`
|
||||
ReceivedAt time.Time `json:"receivedAt"`
|
||||
}
|
||||
|
||||
// PollResults representa os resultados agregados de uma enquete
|
||||
type PollResults struct {
|
||||
PollMessageID string `json:"pollMessageId"`
|
||||
PollChatJid string `json:"pollChatJid"`
|
||||
TotalVotes int `json:"totalVotes"`
|
||||
Votes []PollVote `json:"votes"`
|
||||
OptionCounts map[string]int `json:"optionCounts"` // hash -> count
|
||||
Voters []VoterInfo `json:"voters"`
|
||||
}
|
||||
|
||||
// VoterInfo representa informações de um votante
|
||||
type VoterInfo struct {
|
||||
Jid string `json:"jid"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
SelectedOptions []string `json:"selectedOptions"`
|
||||
VotedAt time.Time `json:"votedAt"`
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package poll_service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
|
||||
"github.com/EvolutionAPI/evolution-go/pkg/poll/model"
|
||||
"github.com/google/uuid"
|
||||
waProto "go.mau.fi/whatsmeow/proto/waE2E"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
)
|
||||
|
||||
// PollService define a interface para gerenciamento de votos de enquetes
|
||||
type PollService interface {
|
||||
// SavePollVote salva um voto de enquete no banco de dados
|
||||
SavePollVote(ctx context.Context, vote *model.PollVote) error
|
||||
|
||||
// GetPollResults retorna os resultados de uma enquete
|
||||
GetPollResults(ctx context.Context, pollMessageID string, instanceID string) (*model.PollResults, error)
|
||||
}
|
||||
|
||||
type pollService struct {
|
||||
db *sql.DB
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
// NewPollService cria uma nova instância do serviço de polls
|
||||
func NewPollService(db *sql.DB, loggerWrapper *logger_wrapper.LoggerManager) PollService {
|
||||
service := &pollService{
|
||||
db: db,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
|
||||
// Auto-migration: criar tabela se não existir
|
||||
if err := service.autoMigrate(); err != nil {
|
||||
loggerWrapper.GetLogger("poll-service").LogError("[POLL] Auto-migration failed: %v", err)
|
||||
}
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
// autoMigrate cria a tabela poll_votes se não existir
|
||||
func (s *pollService) autoMigrate() error {
|
||||
createTableSQL := `
|
||||
CREATE TABLE IF NOT EXISTS poll_votes (
|
||||
id VARCHAR(255) PRIMARY KEY,
|
||||
company_id VARCHAR(255) NOT NULL,
|
||||
instance_id VARCHAR(255) NOT NULL,
|
||||
poll_message_id VARCHAR(255) NOT NULL,
|
||||
poll_chat_jid VARCHAR(255) NOT NULL,
|
||||
vote_message_id VARCHAR(255) NOT NULL,
|
||||
voter_jid VARCHAR(255) NOT NULL,
|
||||
voter_phone VARCHAR(255),
|
||||
voter_name VARCHAR(255),
|
||||
selected_options TEXT[] NOT NULL DEFAULT '{}',
|
||||
voted_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
received_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT unique_vote_per_poll UNIQUE (poll_message_id, voter_jid)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_poll_votes_company ON poll_votes(company_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_poll_votes_instance ON poll_votes(instance_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_poll_votes_poll_message ON poll_votes(poll_message_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_poll_votes_chat ON poll_votes(poll_chat_jid);
|
||||
CREATE INDEX IF NOT EXISTS idx_poll_votes_voter ON poll_votes(voter_jid);
|
||||
`
|
||||
|
||||
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Running auto-migration...")
|
||||
|
||||
_, err := s.db.Exec(createTableSQL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create poll_votes table: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SavePollVote salva um voto de enquete no banco de dados (NÃO-INVASIVO)
|
||||
func (s *pollService) SavePollVote(ctx context.Context, vote *model.PollVote) error {
|
||||
// Log seguro - não expõe dados sensíveis
|
||||
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Saving vote for poll %s from %s", vote.PollMessageID, vote.VoterJid)
|
||||
|
||||
// Extrair telefone do JID de forma segura
|
||||
if vote.VoterPhone == "" && strings.Contains(vote.VoterJid, "@") {
|
||||
phone := strings.Split(vote.VoterJid, "@")[0]
|
||||
vote.VoterPhone = phone
|
||||
}
|
||||
|
||||
// Garantir ID único
|
||||
if vote.ID == "" {
|
||||
vote.ID = uuid.New().String()
|
||||
}
|
||||
|
||||
// Query INSERT com ON CONFLICT para evitar duplicatas (SEGURO)
|
||||
query := `
|
||||
INSERT INTO poll_votes (
|
||||
id, company_id, instance_id, poll_message_id, poll_chat_jid,
|
||||
vote_message_id, voter_jid, voter_phone, voter_name,
|
||||
selected_options, voted_at, received_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5,
|
||||
$6, $7, $8, $9,
|
||||
$10, $11, $12
|
||||
)
|
||||
ON CONFLICT (poll_message_id, voter_jid)
|
||||
DO UPDATE SET
|
||||
selected_options = EXCLUDED.selected_options,
|
||||
voted_at = EXCLUDED.voted_at,
|
||||
received_at = EXCLUDED.received_at
|
||||
`
|
||||
|
||||
_, err := s.db.ExecContext(ctx, query,
|
||||
vote.ID,
|
||||
vote.CompanyID,
|
||||
vote.InstanceID,
|
||||
vote.PollMessageID,
|
||||
vote.PollChatJid,
|
||||
vote.VoteMessageID,
|
||||
vote.VoterJid,
|
||||
vote.VoterPhone,
|
||||
vote.VoterName,
|
||||
stringArrayToPostgresArray(vote.SelectedOptions),
|
||||
vote.VotedAt,
|
||||
vote.ReceivedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to save vote: %v", err)
|
||||
return fmt.Errorf("failed to save poll vote: %w", err)
|
||||
}
|
||||
|
||||
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Vote saved successfully for poll %s", vote.PollMessageID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetPollResults retorna os resultados agregados de uma enquete
|
||||
func (s *pollService) GetPollResults(ctx context.Context, pollMessageID string, instanceID string) (*model.PollResults, error) {
|
||||
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Fetching results for poll %s", pollMessageID)
|
||||
|
||||
query := `
|
||||
SELECT
|
||||
id, company_id, instance_id, poll_message_id, poll_chat_jid,
|
||||
vote_message_id, voter_jid, voter_phone, voter_name,
|
||||
selected_options, voted_at, received_at
|
||||
FROM poll_votes
|
||||
WHERE poll_message_id = $1 AND instance_id = $2
|
||||
ORDER BY voted_at ASC
|
||||
`
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, query, pollMessageID, instanceID)
|
||||
if err != nil {
|
||||
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to query votes: %v", err)
|
||||
return nil, fmt.Errorf("failed to query poll votes: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var votes []model.PollVote
|
||||
optionCounts := make(map[string]int)
|
||||
|
||||
for rows.Next() {
|
||||
var vote model.PollVote
|
||||
var selectedOptionsStr string
|
||||
|
||||
err := rows.Scan(
|
||||
&vote.ID,
|
||||
&vote.CompanyID,
|
||||
&vote.InstanceID,
|
||||
&vote.PollMessageID,
|
||||
&vote.PollChatJid,
|
||||
&vote.VoteMessageID,
|
||||
&vote.VoterJid,
|
||||
&vote.VoterPhone,
|
||||
&vote.VoterName,
|
||||
&selectedOptionsStr,
|
||||
&vote.VotedAt,
|
||||
&vote.ReceivedAt,
|
||||
)
|
||||
if err != nil {
|
||||
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to scan vote: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Converter array do PostgreSQL para []string
|
||||
vote.SelectedOptions = postgresArrayToStringSlice(selectedOptionsStr)
|
||||
|
||||
// Contar opções
|
||||
for _, option := range vote.SelectedOptions {
|
||||
optionCounts[option]++
|
||||
}
|
||||
|
||||
votes = append(votes, vote)
|
||||
}
|
||||
|
||||
if err = rows.Err(); err != nil {
|
||||
s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Rows iteration error: %v", err)
|
||||
return nil, fmt.Errorf("error iterating votes: %w", err)
|
||||
}
|
||||
|
||||
// Verificar se há votos antes de construir resultado
|
||||
if len(votes) == 0 {
|
||||
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] No votes found for poll %s", pollMessageID)
|
||||
return &model.PollResults{
|
||||
PollMessageID: pollMessageID,
|
||||
PollChatJid: "",
|
||||
TotalVotes: 0,
|
||||
Votes: []model.PollVote{},
|
||||
OptionCounts: make(map[string]int),
|
||||
Voters: []model.VoterInfo{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Construir informações dos votantes
|
||||
voters := make([]model.VoterInfo, len(votes))
|
||||
for i, vote := range votes {
|
||||
voters[i] = model.VoterInfo{
|
||||
Jid: vote.VoterJid,
|
||||
Phone: vote.VoterPhone,
|
||||
Name: vote.VoterName,
|
||||
SelectedOptions: vote.SelectedOptions,
|
||||
VotedAt: vote.VotedAt,
|
||||
}
|
||||
}
|
||||
|
||||
results := &model.PollResults{
|
||||
PollMessageID: pollMessageID,
|
||||
PollChatJid: votes[0].PollChatJid,
|
||||
TotalVotes: len(votes),
|
||||
Votes: votes,
|
||||
OptionCounts: optionCounts,
|
||||
Voters: voters,
|
||||
}
|
||||
|
||||
s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Found %d votes for poll %s", len(votes), pollMessageID)
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// Helper para converter []string em formato PostgreSQL array
|
||||
func stringArrayToPostgresArray(arr []string) string {
|
||||
if len(arr) == 0 {
|
||||
return "{}"
|
||||
}
|
||||
return fmt.Sprintf("{%s}", strings.Join(arr, ","))
|
||||
}
|
||||
|
||||
// Helper para converter array PostgreSQL de volta para []string
|
||||
func postgresArrayToStringSlice(s string) []string {
|
||||
// Remove { e }
|
||||
s = strings.TrimPrefix(s, "{")
|
||||
s = strings.TrimSuffix(s, "}")
|
||||
|
||||
if s == "" {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
return strings.Split(s, ",")
|
||||
}
|
||||
|
||||
// BuildPollVoteFromEvent constrói um model.PollVote a partir de eventos do WhatsApp (HELPER SEGURO)
|
||||
// NOTA: Espera que voteInfo já tenha passado pelo JID swap (Sender = número real)
|
||||
func BuildPollVoteFromEvent(
|
||||
pollInfo *types.MessageInfo,
|
||||
voteInfo *types.MessageInfo,
|
||||
decryptedVote *waProto.PollVoteMessage,
|
||||
companyID string,
|
||||
instanceID string,
|
||||
) *model.PollVote {
|
||||
// Extrair opções selecionadas (hashes SHA-256)
|
||||
selectedOptions := make([]string, len(decryptedVote.SelectedOptions))
|
||||
for i, option := range decryptedVote.SelectedOptions {
|
||||
selectedOptions[i] = fmt.Sprintf("%x", option) // Converte bytes para hex
|
||||
}
|
||||
|
||||
// Extrair telefone do votante
|
||||
// NOTA: O JID swap já foi feito antes de chegar aqui!
|
||||
// Se havia LID+WhatsApp, o Sender JÁ É o número real (@s.whatsapp.net) e SenderAlt é o LID
|
||||
voterPhone := voteInfo.Sender.User
|
||||
voterJid := voteInfo.Sender.String()
|
||||
|
||||
fmt.Printf("[POLL DEBUG] ==========================================\n")
|
||||
fmt.Printf("[POLL DEBUG] Voter JID: %s\n", voterJid)
|
||||
fmt.Printf("[POLL DEBUG] Sender.Server: %s\n", voteInfo.Sender.Server)
|
||||
fmt.Printf("[POLL DEBUG] Sender.User: %s\n", voteInfo.Sender.User)
|
||||
fmt.Printf("[POLL DEBUG] FINAL voterPhone: %s\n", voterPhone)
|
||||
fmt.Printf("[POLL DEBUG] ==========================================\n")
|
||||
|
||||
return &model.PollVote{
|
||||
ID: uuid.New().String(),
|
||||
CompanyID: companyID,
|
||||
InstanceID: instanceID,
|
||||
PollMessageID: pollInfo.ID,
|
||||
PollChatJid: pollInfo.Chat.String(),
|
||||
VoteMessageID: voteInfo.ID,
|
||||
VoterJid: voteInfo.Sender.String(),
|
||||
VoterPhone: voterPhone,
|
||||
VoterName: voteInfo.PushName,
|
||||
SelectedOptions: selectedOptions,
|
||||
VotedAt: voteInfo.Timestamp,
|
||||
ReceivedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
|
||||
_ "github.com/EvolutionAPI/evolution-go/docs"
|
||||
call_handler "github.com/EvolutionAPI/evolution-go/pkg/call/handler"
|
||||
chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler"
|
||||
community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler"
|
||||
group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler"
|
||||
instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler"
|
||||
label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler"
|
||||
message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler"
|
||||
auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware"
|
||||
newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler"
|
||||
poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler"
|
||||
send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler"
|
||||
server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler"
|
||||
user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler"
|
||||
)
|
||||
|
||||
type Routes struct {
|
||||
authMiddleware auth_middleware.Middleware
|
||||
jidValidationMiddleware *auth_middleware.JIDValidationMiddleware
|
||||
instanceHandler instance_handler.InstanceHandler
|
||||
userHandler user_handler.UserHandler
|
||||
sendHandler send_handler.SendHandler
|
||||
messageHandler message_handler.MessageHandler
|
||||
chatHandler chat_handler.ChatHandler
|
||||
groupHandler group_handler.GroupHandler
|
||||
callHandler call_handler.CallHandler
|
||||
communityHandler community_handler.CommunityHandler
|
||||
labelHandler label_handler.LabelHandler
|
||||
newsletterHandler newsletter_handler.NewsletterHandler
|
||||
pollHandler *poll_handler.PollHandler
|
||||
serverHandler server_handler.ServerHandler
|
||||
}
|
||||
|
||||
func (r *Routes) AssignRoutes(eng *gin.Engine) {
|
||||
// Configuração do CORS
|
||||
eng.Use(func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Cache-Control, X-Requested-With, apikey, ApiKey")
|
||||
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(200)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
})
|
||||
|
||||
eng.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
|
||||
eng.GET("/favicon.ico", func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
|
||||
// Rotas para o gerenciador React (sem autenticação)
|
||||
eng.Static("/assets", "./manager/dist/assets")
|
||||
|
||||
// Ajuste nas rotas do manager para suportar client-side routing do React
|
||||
eng.GET("/manager/*any", func(c *gin.Context) {
|
||||
c.File("manager/dist/index.html")
|
||||
})
|
||||
|
||||
eng.GET("/manager", func(c *gin.Context) {
|
||||
c.File("manager/dist/index.html")
|
||||
})
|
||||
|
||||
eng.GET("/server/ok", r.serverHandler.ServerOk)
|
||||
|
||||
routes := eng.Group("/instance")
|
||||
{
|
||||
routes.Use(r.authMiddleware.AuthAdmin)
|
||||
{
|
||||
routes.POST("/create", r.instanceHandler.Create)
|
||||
routes.GET("/all", r.instanceHandler.All)
|
||||
routes.GET("/info/:instanceId", r.instanceHandler.Info)
|
||||
routes.DELETE("/delete/:instanceId", r.instanceHandler.Delete)
|
||||
routes.POST("/proxy/:instanceId", r.instanceHandler.SetProxy)
|
||||
routes.DELETE("/proxy/:instanceId", r.instanceHandler.DeleteProxy)
|
||||
routes.POST("/forcereconnect/:instanceId", r.instanceHandler.ForceReconnect)
|
||||
routes.GET("/logs/:instanceId", r.instanceHandler.GetLogs)
|
||||
}
|
||||
}
|
||||
|
||||
routes = eng.Group("/instance")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/connect", r.instanceHandler.Connect)
|
||||
routes.GET("/status", r.instanceHandler.Status)
|
||||
routes.GET("/qr", r.instanceHandler.Qr)
|
||||
routes.POST("/pair", r.jidValidationMiddleware.ValidateNumberField(), r.instanceHandler.Pair)
|
||||
routes.POST("/disconnect", r.instanceHandler.Disconnect)
|
||||
routes.POST("/reconnect", r.instanceHandler.Reconnect)
|
||||
routes.DELETE("/logout", r.instanceHandler.Logout)
|
||||
routes.GET("/:instanceId/advanced-settings", r.instanceHandler.GetAdvancedSettings)
|
||||
routes.PUT("/:instanceId/advanced-settings", r.instanceHandler.UpdateAdvancedSettings)
|
||||
}
|
||||
}
|
||||
|
||||
routes = eng.Group("/send")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/text", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendText)
|
||||
routes.POST("/link", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendLink)
|
||||
routes.POST("/media", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendMedia)
|
||||
routes.POST("/poll", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendPoll)
|
||||
routes.POST("/sticker", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendSticker)
|
||||
routes.POST("/location", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendLocation)
|
||||
routes.POST("/contact", r.jidValidationMiddleware.ValidateContactFields(), r.sendHandler.SendContact) // TODO: send multiple contacts
|
||||
routes.POST("/button", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendButton)
|
||||
routes.POST("/list", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendList)
|
||||
// TODO: send status
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/user")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/info", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.GetUser)
|
||||
routes.POST("/check", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.userHandler.CheckUser)
|
||||
routes.POST("/avatar", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.GetAvatar)
|
||||
routes.GET("/contacts", r.userHandler.GetContacts)
|
||||
routes.GET("/privacy", r.userHandler.GetPrivacy)
|
||||
routes.POST("/privacy", r.userHandler.SetPrivacy)
|
||||
routes.POST("/block", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.BlockContact)
|
||||
routes.POST("/unblock", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.UnblockContact)
|
||||
routes.GET("/blocklist", r.userHandler.GetBlockList)
|
||||
routes.POST("/profilePicture", r.userHandler.SetProfilePicture)
|
||||
routes.POST("/profileName", r.userHandler.SetProfileName)
|
||||
routes.POST("/profileStatus", r.userHandler.SetProfileStatus)
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/message")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/react", r.jidValidationMiddleware.ValidateJIDFields("number"), r.messageHandler.React)
|
||||
routes.POST("/presence", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.ChatPresence)
|
||||
routes.POST("/markread", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.MarkRead)
|
||||
routes.POST("/downloadmedia", r.messageHandler.DownloadMedia)
|
||||
routes.POST("/status", r.messageHandler.GetMessageStatus)
|
||||
routes.POST("/delete", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.DeleteMessageEveryone)
|
||||
routes.POST("/edit", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.EditMessage) // TODO: edit MediaMessage too
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/chat")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/pin", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatPin) // TODO: not working
|
||||
routes.POST("/unpin", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnpin) // TODO: not working
|
||||
routes.POST("/archive", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatArchive) // TODO: not working
|
||||
routes.POST("/unarchive", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnarchive) // TODO: not working
|
||||
routes.POST("/mute", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatMute) // TODO: not working
|
||||
routes.POST("/unmute", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnmute) // TODO: not working
|
||||
routes.POST("/history-sync", r.chatHandler.HistorySyncRequest)
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/group")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.GET("/list", r.groupHandler.ListGroups)
|
||||
routes.POST("/info", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.GetGroupInfo)
|
||||
routes.POST("/invitelink", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.GetGroupInviteLink)
|
||||
routes.POST("/photo", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupPhoto)
|
||||
routes.POST("/name", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupName)
|
||||
routes.POST("/description", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupDescription)
|
||||
routes.POST("/create", r.jidValidationMiddleware.ValidateMultipleNumbers("participants"), r.groupHandler.CreateGroup)
|
||||
routes.POST("/participant", r.jidValidationMiddleware.ValidateJIDFields("number", "participants"), r.groupHandler.UpdateParticipant)
|
||||
routes.GET("/myall", r.groupHandler.GetMyGroups) // TODO: not working
|
||||
routes.POST("/join", r.groupHandler.JoinGroupLink)
|
||||
routes.POST("/leave", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.LeaveGroup)
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/call")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/reject", r.jidValidationMiddleware.ValidateNumberField(), r.callHandler.RejectCall)
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/community")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/create", r.communityHandler.CreateCommunity)
|
||||
routes.POST("/add", r.jidValidationMiddleware.ValidateJIDFields("number", "communityId"), r.communityHandler.CommunityAdd)
|
||||
routes.POST("/remove", r.jidValidationMiddleware.ValidateJIDFields("number", "communityId"), r.communityHandler.CommunityRemove)
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/label")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/chat", r.jidValidationMiddleware.ValidateNumberField(), r.labelHandler.ChatLabel)
|
||||
routes.POST("/message", r.labelHandler.MessageLabel)
|
||||
routes.POST("/edit", r.labelHandler.EditLabel)
|
||||
routes.GET("/list", r.labelHandler.GetLabels)
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/unlabel")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/chat", r.jidValidationMiddleware.ValidateNumberField(), r.labelHandler.ChatUnlabel)
|
||||
routes.POST("/message", r.labelHandler.MessageUnlabel)
|
||||
}
|
||||
}
|
||||
routes = eng.Group("/newsletter")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.POST("/create", r.newsletterHandler.CreateNewsletter)
|
||||
routes.GET("/list", r.newsletterHandler.ListNewsletter)
|
||||
routes.POST("/info", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletter)
|
||||
routes.POST("/link", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletterInvite)
|
||||
routes.POST("/subscribe", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.SubscribeNewsletter)
|
||||
routes.POST("/messages", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletterMessages)
|
||||
}
|
||||
}
|
||||
|
||||
// NOVO: Rotas de Enquetes (Polls)
|
||||
routes = eng.Group("/polls")
|
||||
{
|
||||
routes.Use(r.authMiddleware.Auth)
|
||||
{
|
||||
routes.GET("/:pollMessageId/results", r.pollHandler.GetPollResults)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func NewRouter(
|
||||
authMiddleware auth_middleware.Middleware,
|
||||
instanceHandler instance_handler.InstanceHandler,
|
||||
userHandler user_handler.UserHandler,
|
||||
sendHandler send_handler.SendHandler,
|
||||
messageHandler message_handler.MessageHandler,
|
||||
chatHandler chat_handler.ChatHandler,
|
||||
groupHandler group_handler.GroupHandler,
|
||||
callHandler call_handler.CallHandler,
|
||||
communityHandler community_handler.CommunityHandler,
|
||||
labelHandler label_handler.LabelHandler,
|
||||
newsletterHandler newsletter_handler.NewsletterHandler,
|
||||
pollHandler *poll_handler.PollHandler,
|
||||
serverHandler server_handler.ServerHandler,
|
||||
) *Routes {
|
||||
return &Routes{
|
||||
authMiddleware: authMiddleware,
|
||||
jidValidationMiddleware: auth_middleware.NewJIDValidationMiddleware(),
|
||||
instanceHandler: instanceHandler,
|
||||
userHandler: userHandler,
|
||||
sendHandler: sendHandler,
|
||||
messageHandler: messageHandler,
|
||||
chatHandler: chatHandler,
|
||||
groupHandler: groupHandler,
|
||||
callHandler: callHandler,
|
||||
communityHandler: communityHandler,
|
||||
labelHandler: labelHandler,
|
||||
newsletterHandler: newsletterHandler,
|
||||
pollHandler: pollHandler,
|
||||
serverHandler: serverHandler,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
package send_handler
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
|
||||
send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type SendHandler interface {
|
||||
SendText(ctx *gin.Context)
|
||||
SendLink(ctx *gin.Context)
|
||||
SendMedia(ctx *gin.Context)
|
||||
SendPoll(ctx *gin.Context)
|
||||
SendSticker(ctx *gin.Context)
|
||||
SendLocation(ctx *gin.Context)
|
||||
SendContact(ctx *gin.Context)
|
||||
SendButton(ctx *gin.Context)
|
||||
SendList(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type sendHandler struct {
|
||||
sendMessageService send_service.SendService
|
||||
}
|
||||
|
||||
// Send a text message
|
||||
// @Summary Send a text message
|
||||
// @Description Send a text message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.TextStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/text [post]
|
||||
func (s *sendHandler) SendText(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.TextStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Text == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message body is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendText(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// Send a link message
|
||||
// @Summary Send a link message
|
||||
// @Description Send a link message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.LinkStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/link [post]
|
||||
func (s *sendHandler) SendLink(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.LinkStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Text == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "message body is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendLink(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// Send a media message
|
||||
// @Summary Send a media message
|
||||
// @Description Send a media message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.MediaStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/media [post]
|
||||
func (s *sendHandler) SendMedia(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
contentType := ctx.ContentType()
|
||||
|
||||
var data *send_service.MediaStruct
|
||||
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
// Handle form-data
|
||||
number := ctx.PostForm("number")
|
||||
if number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
mediaType := ctx.PostForm("type")
|
||||
if mediaType == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "media type is required"})
|
||||
return
|
||||
}
|
||||
|
||||
caption := ctx.PostForm("caption")
|
||||
filename := ctx.PostForm("filename")
|
||||
id := ctx.PostForm("id")
|
||||
delayStr := ctx.PostForm("delay")
|
||||
delay := int32(0)
|
||||
if delayStr != "" {
|
||||
delay64, err := strconv.ParseInt(delayStr, 10, 32)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid delay"})
|
||||
return
|
||||
}
|
||||
delay = int32(delay64)
|
||||
}
|
||||
|
||||
// Get file
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Open file
|
||||
fileData, err := file.Open()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
|
||||
return
|
||||
}
|
||||
defer fileData.Close()
|
||||
fileBytes, err := io.ReadAll(fileData)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "cannot read file"})
|
||||
return
|
||||
}
|
||||
|
||||
// Create MediaStruct
|
||||
data = &send_service.MediaStruct{
|
||||
Number: number,
|
||||
Type: mediaType,
|
||||
Caption: caption,
|
||||
Filename: filename,
|
||||
Id: id,
|
||||
Delay: delay,
|
||||
// Other fields as necessary
|
||||
}
|
||||
|
||||
// Pass fileBytes to the send service
|
||||
message, err := s.sendMessageService.SendMediaFile(data, fileBytes, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
|
||||
} else {
|
||||
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Url == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "URL is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Type == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "media type is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendMediaUrl(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
}
|
||||
|
||||
// Send a poll message
|
||||
// @Summary Send a poll message
|
||||
// @Description Send a poll message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.PollStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/poll [post]
|
||||
func (s *sendHandler) SendPoll(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.PollStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Question == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "question is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.Options) < 2 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "minimum 2 options are required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendPoll(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// Send a sticker message
|
||||
// @Summary Send a sticker message
|
||||
// @Description Send a sticker message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.StickerStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/sticker [post]
|
||||
func (s *sendHandler) SendSticker(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.StickerStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Sticker == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "sticker is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendSticker(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// Send a location message
|
||||
// @Summary Send a location message
|
||||
// @Description Send a location message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.LocationStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/location [post]
|
||||
func (s *sendHandler) SendLocation(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.LocationStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Latitude == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "latitude is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Longitude == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "longitude is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Address == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "address is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Name == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendLocation(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// Send a contact message
|
||||
// @Summary Send a contact message
|
||||
// @Description Send a contact message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.ContactStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/contact [post]
|
||||
func (s *sendHandler) SendContact(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.ContactStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Vcard.Phone == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "contact phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Vcard.FullName == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "contact full name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendContact(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// Send a button message
|
||||
// @Summary Send a button message
|
||||
// @Description Send a button message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.ContactStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/button [post]
|
||||
func (s *sendHandler) SendButton(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.ButtonStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Title == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Description == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "description is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Footer == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "footer is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendButton(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
// Send a list message
|
||||
// @Summary Send a list message
|
||||
// @Description Send a list message
|
||||
// @Tags Send Message
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body send_service.ContactStruct true "Message data"
|
||||
// @Success 200 {object} gin.H "success"
|
||||
// @Failure 400 {object} gin.H "Error on validation"
|
||||
// @Failure 500 {object} gin.H "Internal server error"
|
||||
// @Router /send/list [post]
|
||||
func (s *sendHandler) SendList(ctx *gin.Context) {
|
||||
getInstance := ctx.MustGet("instance")
|
||||
|
||||
instance, ok := getInstance.(*instance_model.Instance)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var data *send_service.ListStruct
|
||||
err := ctx.ShouldBindBodyWithJSON(&data)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Number == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Title == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.Description == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "description is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.FooterText == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "footer is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if data.ButtonText == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "button text is required"})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := s.sendMessageService.SendList(data, instance)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})
|
||||
}
|
||||
|
||||
func NewSendHandler(
|
||||
sendMessageService send_service.SendService,
|
||||
) SendHandler {
|
||||
return &sendHandler{
|
||||
sendMessageService: sendMessageService,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
package server_handler
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
type ServerHandler interface {
|
||||
ServerOk(ctx *gin.Context)
|
||||
}
|
||||
|
||||
type serverHandler struct {
|
||||
}
|
||||
|
||||
// ServerOk implements ServerHandler.
|
||||
func (s *serverHandler) ServerOk(ctx *gin.Context) {
|
||||
ctx.JSON(200, gin.H{
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
func NewServerHandler() ServerHandler {
|
||||
return &serverHandler{}
|
||||
}
|
||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user