27 Commits
Author SHA1 Message Date
jfengandClaude Opus 5.5 997bbc85c2 merge: promote maintained-stable (v0.7.2-evogo.3) into main
Build Automatico / build (push) Successful in 27s
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 4m26s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 09:19:57 -03:00
jfengandClaude Opus 5.5 b140fdb390 fix(send): send to known LIDs passed as phone numbers; expose version
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 2m28s
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 3m58s
Docker - Promover latest / Promover release para latest (push) Successful in 4m39s
Integrations that store the contact's LID as its number (255284433936406)
failed with 'no LID found for [email protected]'. When the number
is not a registered phone and the instance's LID store maps it to a phone
number, send to <number>@lid instead.

GET /server/ok now also returns the running version, so a deployment can be
checked without reading the startup log.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 08:15:58 -03:00
jfengandClaude Opus 5.5 c9511a636e ci: retry registry login, pull and push
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 1m48s
A transient timeout on the registry token endpoint failed the publication of
v0.7.2-evogo.2 (run 482) after the image had already been built and scanned.
Login, pull and push now retry up to 5 times with linear backoff.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 07:52:15 -03:00
jfengandClaude Opus 5.5 5b71495e93 fix(send): resolve Brazilian 9th digit by asking WhatsApp for both variants
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 2m42s
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 1m23s
Accounts created before the 9th digit rollout are still registered without it
(554291389691), newer ones with it (5542991389691). The DDD-based rewrite in
CreateJID cannot be right for every account, and the existence check queried
only the number as received, so sends to 5542991389691 failed for an account
registered as 554291389691.

validateAndCheckUserExists now queries both forms in one IsOnWhatsApp call and
uses the registered one (received form first). Non-Brazilian numbers, groups,
LIDs and landlines follow the previous path unchanged. Related: upstream
issue #214 / PR #208.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:11:49 -03:00
jfengandClaude Opus 5.5 03d619bb55 ci: promote last v* release in maintained-stable to :latest without rebuilding
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 4m8s
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 2m42s
Docker - Promover latest / Promover release para latest (push) Successful in 2m18s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:40:58 -03:00
jfengandClaude Opus 5.5 0379082181 ci: daily upstream merge with PR/issue, tag-based image publishing
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 3m33s
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 3m48s
- scripts/upstream-sync.sh + upstream-sync-check.yml: fast-forward upstream-sync,
  merge upstream into maintenance/sync-upstream-<sha> from maintained-develop,
  build/vet/test, open PR (or Issue on conflict), warn on newer whatsmeow.
  Optional AUTO_MERGE_UPSTREAM repo variable; maintained-stable never touched.
- docker-build.yml: publish git.jf.eng.br/jfeng/evogo:<version> and
  <version>-<sha7> on tag v*, startup smoke test, non-blocking Trivy scan,
  :latest only on explicit promote_latest.
- CHANGELOG and maintenance docs updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:12:32 -03:00
jfengandClaude Opus 5.5 e02441fc4e style: gofmt files touched by the community fixes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:12:30 -03:00
jfengandClaude Opus 5.5 abaac8eb93 fix(build): import waWa6 for ClientPayload_UserAgent_AppVersion
maintained-develop (after PR #1) did not compile: whatsmeow.go referenced an
undefined waProto package. The AppVersion type lives in
go.mau.fi/whatsmeow/proto/waWa6. Also gofmt the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:12:27 -03:00
jfengandClaude Opus 5.5 4998ab3d45 fix(whatsmeow): harden client lifecycle against duplicate starts and races
- Skip a second StartClient while one is starting (adapted from upstream PR #239).
- Do not restart a client without a paired device; it would cycle QR codes
  forever (adapted from upstream PR #240).
- Serialize ReconnectClient per instance and nil-check the client: two
  Disconnected events in the same second dereferenced a removed client and
  killed the whole process (upstream issue #188).
- safemap.TrySend / TrySendTimeout: kill-channel sends no longer panic with
  "send on closed channel" when the instance is deleted during QR handling
  (upstream issue #222).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:04:18 -03:00
jfengandClaude Opus 5.5 74389cc8de fix(instance): do not clear event subscriptions on disconnect
Adapted from upstream PR #187 (guipratiko). Clearing instance.Events left the
instance with an empty events string after reconnecting, so CallWebhook dropped
every webhook.

Also send kill signals through safemap.TrySend/TrySendTimeout so a channel
closed by a concurrent instance delete no longer panics the process
(upstream issue #222).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:04:16 -03:00
jfengandClaude Opus 5.5 c33b4d98fd fix(utils): strip plus prefix from user JIDs in ParseJID
Adapted from upstream PR #224 (danie1net0). Queries addressed to
"+<number>@s.whatsapp.net" are never answered by WhatsApp and hang until
the IQ timeout (upstream issue #223: /user/info and /user/avatar hang 75s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:04:14 -03:00
EcoosUP fc35d72029 fix(whatsmeow): back off the reconnect loop instead of spinning forever
An instance whose device was logged out from the phone never stops restarting:

    Disconnected -> ReconnectClient -> instance comes up with no session
    -> QR -> nobody scans -> max QR count -> forced logout -> Disconnected

Measured in production: 110 reconnects and 1135 QR codes in 50 minutes from a
single instance, stopping only when a human noticed.

Nothing counted those restarts, because from ReconnectClient's point of view
every turn succeeds — the instance really does come up. What fails afterwards is
the pairing, and nobody was measuring that.

The first 5 restarts inside a 15 minute window still go straight through: that
is the good case, a healthy instance that lost its websocket and has to return
within seconds. Past that the loop becomes a growing wait (5, 15, 30 minutes)
and the instance keeps trying — a backoff, not a give-up.

Only one goroutine waits per instance. Without that guard, every Disconnected
arriving during the wait would stack another one and the backoff would become
the loop it was written to stop.

(cherry picked from commit 3b52f1c457406dc2540f7e17467b6c30e9304f7b)
2026-11-09 12:01:35 -03:00
Guilherme Souza 3fce4dbcca fix(whatsmeow): share one sqlstore.Container for auth DB
StartClient called sqlstore.New on every instance start, opening a new
*sql.DB and re-running Upgrade against PostgresAuthDB. A few parallel
QR/reconnects saturated PgBouncer (75 = 60+15) with bad connection.

Reuse the pooled authDB from initPostgresAuthDB via NewWithDB + Upgrade
once (sync.Once on a heap-allocated sharedSQLStore so value-receiver
StartClient is safe). Users/GORM DB stays separate. Do not Close the
shared container on disconnect — main owns authDB.

(cherry picked from commit f2a73c715a286aefa5c10fa8521dccc7efa56581)
2026-11-09 12:01:15 -03:00
EcoosUP 0c4ac7d9a9 fix(concurrency): guard the three shared maps with a mutex
clientPointer, myClientPointer and killChannel are created once at startup and
passed by reference into eleven packages. All of them read and wrote those plain
Go maps from different goroutines, with no synchronisation.

Go does not tolerate that: the runtime kills the process with

    fatal error: concurrent map writes

and a fatal error is not recoverable — a deferred recover() does not catch it.

Measured in production: the process died inside StartClient while five instances
were connecting at once. The orchestrator restarted it within seconds, but every
number was offline in the meantime, and it repeats on any restart that brings up
more than a couple of instances together.

The three maps become safemap.Map[T], a generic wrapper over a RWMutex. It lives
in its own package because MyClient is defined in pkg/whatsmeow/service, and
putting the type there would create an import cycle with the ten packages that
receive the maps.

98 call sites changed across 12 files, with the compiler as the judge: anything
missed is a build error, not a silent bug.

Tests: with -race, a plain map running the same exercise reports DATA RACE and
fails, while safemap.Map passes. Both halves verified.

(cherry picked from commit 3860fa278dc2b901705ffbddbed5cf59d70a85e4)
2026-11-09 12:01:08 -03:00
prakash-dev-code a5f7e1c98a fix(websocket): deliver events to every subscriber of an instance
The websocket producer kept a single connection per instance in
`clients map[string]*websocket.Conn`. Registering a second subscriber
silently replaced the first, and `RemoveClient` deleted the whole instance
entry when either one disconnected. Consuming events in two browser tabs
therefore delivered to only the most recent one, and closing that tab cut
delivery for the remaining subscriber too.

Changes:

- `clients` becomes `map[string][]*client`. Deregistration now matches the
  specific connection instead of removing the instance entry, so sibling
  subscribers keep receiving events.
- Each connection carries its own write mutex. Events are dispatched from
  independent goroutines (the `go CallWebhook` calls in the whatsmeow event
  handler) and gorilla/websocket permits only one concurrent writer per
  connection, so two simultaneous events could interleave writes on the
  same socket.
- `Produce` snapshots the subscriber list under the read lock and performs
  writes outside it, so a slow or half-open socket no longer blocks
  deliveries for other instances.
- Failed writes prune the dead connection, and `Produce` now returns nil.
  `sendToQueueOrWebhook` aborts the remaining producers when one returns an
  error, so a closed browser tab previously suppressed RabbitMQ, NATS and
  webhook delivery for that same event.

Verified with two concurrent subscribers on one instance: both receive
identical event streams, and disconnecting one leaves the other unaffected.

(cherry picked from commit 1db4408244fe75b39c2b4e1bbb8e681679dd7dae)
2026-11-09 12:01:02 -03:00
lojanica a0c74485b8 test(nats): refactor tests and add global events state assertion
(cherry picked from commit 1860110296ea775734752be8a40b93726c34ff27)
2026-11-09 12:01:00 -03:00
root a4add7cc5e fix: skip NATS connection when URL is empty
(cherry picked from commit a3c05b41717bc652ef7736cc2c2b22c4eaed0f5d)
2026-11-09 12:01:00 -03:00
EcoosUP 3cc5192b7b fix(whatsmeow): Archive event panics before reaching the webhook
The Archive case asserts postMap["data"] to map[string]interface{}, but at that
point it still holds the raw *events.Archive. The assertion panics on every
archive event:

    Event handler panicked while handling a *events.Archive:
    interface conversion: interface {} is *events.Archive,
    not map[string]interface {}

whatsmeow recovers the panic and logs it, so nothing crashes — the event simply
never reaches the webhook, silently.

Every other case in this switch marshals and unmarshals postMap["data"] into a
map before asserting. Archive was the only one missing that step. Six call sites
do the assertion; the other five are already guarded.

(cherry picked from commit 16c4be6e9a0ae8a0bbc41f8b2790a362a7a4e2e2)
2026-11-09 12:00:59 -03:00
jfeng 87a354aee8 Merge pull request 'fix: resolver erro Client outdated (405) com whatsmeow atualizado e handshake dinamico' (#1) from fix/client-outdated-405 into maintained-develop
CI - Validacao Go / Validar Codigo e Testes (push) Failing after 2m15s
Reviewed-on: #1
2026-11-09 14:45:05 +00:00
jfeng ca673bd1d4 docs(governance): update AGENTS.md with EvoGO maintenance guidelines
Build Automatico / build (push) Successful in 31s
2026-11-09 14:19:41 +00:00
jfeng 245510315c chore: sync maintenance documentation and workflows into fix branch
CI - Validacao Go / Validar Codigo e Testes (pull_request) Failing after 3m53s
CI - Validacao Go / Validar Codigo e Testes (push) Failing after 4m46s
2026-11-09 11:17:53 -03:00
jfeng 25117bd2c1 chore(governance): add AGENTS.md, maintenance documentation, Gitea workflows and sync monitoring scripts
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 5m59s
2026-11-09 11:17:45 -03:00
jfeng 91c1d0697f fix(handshake): apply dynamic store.SetWAVersion and UserAgent to prevent 405 error 2026-11-09 11:12:27 -03:00
MayconVM 70ecc1746c fix(makefile): read release version from CHANGELOG heading
The old pattern 'grep -om1 "v[0-9].*"' matched the first vN.N.N anywhere in
the file, so any mention of a module pseudo-version above the release heading
silently corrupted the build version (e.g. it produced
"v0.0.0-20261102152715-54038813c47f`." as main.version). Anchor it to the
## vX.Y.Z heading instead.
2026-11-09 11:11:21 -03:00
MayconVM ab5f84213f docs: record whatsmeow bump, Go 1.26 requirement and blocklist response change 2026-11-09 11:11:21 -03:00
MayconVM 99b4d78f62 deps: bump whatsmeow to 2026-11-02 (fix 405 client outdated)
whatsmeow was pinned to 2026-06-30 (v0.0.0-20260630180629-b572e5bcb92b),
which predates WhatsApp's minimum client version bump and causes
405 client-outdated connect failures.

- go.mau.fi/whatsmeow -> v0.0.0-20261102152715-54038813c47f
- go.mau.fi/util 0.9.10 -> 0.11.0, x/{crypto,net,sync,sys,text,tools} bumped
- go directive 1.25.0 -> 1.26.0 (upstream minimum), Dockerfile builder
  golang:1.25.0-alpine -> golang:1.26.10-alpine

API adaptations:
- UpdateBlocklist/GetBlocklist now take a dhash argument
- SetStatusMessage takes types.SetStatusInput (text behind mex query)

Store schema upgrades to v16 (companion_meta_nonce, wasa_root_secret_id)
run automatically on container open; verified against a v14 sqlite auth DB.
2026-11-09 11:11:21 -03:00
jfeng 4ddea7cd3d Initial commit 2026-11-09 13:48:37 +00:00
42 changed files with 2625 additions and 299 deletions

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
name: Build Automatico
on:
push:
branches:
- main
pull_request:
branches:
- main
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Baixar codigo
uses: actions/checkout@v4
- name: Verificar ambiente
run: |
echo "Gitea Actions funcionando!"
echo "Repositorio: ${{ github.repository }}"
echo "Branch: ${{ github.ref_name }}"
- name: Verificar projeto
run: |
if [ -f package.json ]; then
echo "Projeto Node.js detectado"
elif [ -f composer.json ]; then
echo "Projeto PHP detectado"
elif [ -f requirements.txt ]; then
echo "Projeto Python detectado"
elif [ -f Dockerfile ]; then
echo "Projeto Docker detectado"
else
echo "Projeto sem build configurado"
fi
- name: Finalizar
run: echo "Verificacao concluida!"
+52
View File
@@ -0,0 +1,52 @@
name: CI - Validacao Go
on:
push:
branches:
- main
- maintained-develop
- maintained-stable
- 'fix/*'
- 'maintenance/*'
pull_request:
branches:
- maintained-develop
- maintained-stable
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
validate:
name: Validar Codigo e Testes
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
submodules: recursive
- name: Configurar Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Instalar Dependencias de Sistema
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends libjpeg-dev libwebp-dev poppler-utils ffmpeg
- name: Verificar Integridade das Dependencias
run: go mod verify
- name: Compilar Codigo
run: go build ./...
- name: Analise Estatica (Go Vet)
run: go vet ./...
- name: Executar Testes Unitarios
run: go test -v ./...
+133
View File
@@ -0,0 +1,133 @@
name: Docker - Build e Publicacao
# Publicacao no registry do Gitea (git.jf.eng.br/jfeng/evogo):
# - push de tag v<versao> (ex: v0.7.2-evogo.1) = release aprovado -> publica
# git.jf.eng.br/jfeng/evogo:<versao> (tag semantica)
# git.jf.eng.br/jfeng/evogo:<versao>-<sha7> (tag imutavel do commit)
# - workflow_dispatch com publish_image=true -> idem, versao = target_tag ou VERSION
# - push em maintained-stable -> apenas build + teste + scan (nao publica)
# :latest so e atualizada com promote_latest=true (manual), nunca automaticamente.
on:
push:
branches:
- maintained-stable
tags:
- 'v*'
workflow_dispatch:
inputs:
publish_image:
description: 'Publicar imagem no registry apos build e testes (requer aprovacao)'
type: boolean
default: false
required: true
target_tag:
description: 'Tag semantica para publicacao (ex: 0.7.2-evogo.1). Vazio = arquivo VERSION'
type: string
default: ''
required: false
promote_latest:
description: 'Tambem atualizar :latest (somente versoes aprovadas em maintained-stable)'
type: boolean
default: false
required: false
env:
REGISTRY: git.jf.eng.br
IMAGE: git.jf.eng.br/jfeng/evogo
jobs:
build_docker:
name: Build, Scan e Publicacao
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
- name: Obter Versao e Commit SHA
id: meta
run: |
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
if [ "${{ github.ref_type }}" = "tag" ]; then
VERSION="${{ github.ref_name }}"
VERSION="${VERSION#v}"
PUBLISH=true
else
VERSION="${{ github.event.inputs.target_tag }}"
[ -n "$VERSION" ] || VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
PUBLISH="${{ github.event.inputs.publish_image == 'true' }}"
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "commit_sha=${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
echo "publish=${PUBLISH}" >> "$GITHUB_OUTPUT"
echo "Versao: ${VERSION} | Commit: ${COMMIT_SHA} | Publicar: ${PUBLISH}"
- name: Construir Imagem Docker Local
run: |
docker build \
--build-arg VERSION=${{ steps.meta.outputs.image_tag }} \
-t evogo:ci-${{ steps.meta.outputs.commit_sha }} .
- name: Testar Inicializacao do Container
run: |
# O binario precisa subir e falhar apenas por falta de banco/config,
# nunca por erro de link (CGO/libwebp/libjpeg) ou arquivo ausente.
set +e
timeout 20 docker run --rm evogo:ci-${{ steps.meta.outputs.commit_sha }} > /tmp/run.log 2>&1
set -e
tail -20 /tmp/run.log
if grep -qiE "error while loading shared libraries|exec format error|exec /app/server" /tmp/run.log; then
echo "Falha ao iniciar o binario dentro da imagem"; exit 1
fi
docker run --rm --entrypoint sh evogo:ci-${{ steps.meta.outputs.commit_sha }} -c 'test -x /app/server && test -d /app/manager/dist && cat /app/VERSION'
- name: Verificar Vulnerabilidades (Trivy, nao bloqueante)
continue-on-error: true
run: |
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
image --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
evogo:ci-${{ steps.meta.outputs.commit_sha }}
- name: Login no Gitea Package Registry
if: steps.meta.outputs.publish == 'true'
run: |
USER="${{ secrets.REGISTRY_USER }}"
[ -n "$USER" ] || USER="${{ github.actor }}"
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
# O registry ja estourou timeout pontualmente (run 482); tenta de novo antes de falhar.
for n in 1 2 3 4 5; do
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
exit 1
- name: Publicar Imagens no Registry
if: steps.meta.outputs.publish == 'true'
run: |
push() {
for n in 1 2 3 4 5; do
docker push "$1" && return 0
echo "Push de $1 falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
return 1
}
SRC=evogo:ci-${{ steps.meta.outputs.commit_sha }}
for TAG in "${{ steps.meta.outputs.image_tag }}" "${{ steps.meta.outputs.version }}"; do
docker tag "$SRC" "$IMAGE:$TAG"
push "$IMAGE:$TAG"
echo "Publicado: $IMAGE:$TAG"
done
if [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
docker tag "$SRC" "$IMAGE:latest"
push "$IMAGE:latest"
echo "Publicado: $IMAGE:latest"
fi
- name: Limpeza
if: always()
run: docker image rm -f evogo:ci-${{ steps.meta.outputs.commit_sha }} >/dev/null 2>&1 || true
+71
View File
@@ -0,0 +1,71 @@
name: Docker - Promover latest
# :latest = ultimo release v* contido em maintained-stable.
# Nao recompila: baixa a imagem imutavel <versao>-<sha7> ja publicada pelo
# docker-build.yml para aquela tag e apenas a re-etiqueta, preservando o digest.
# So roda quando maintained-stable avanca (promocao aprovada) ou manualmente.
on:
push:
branches:
- maintained-stable
workflow_dispatch:
concurrency:
group: promote-latest
cancel-in-progress: false
env:
REGISTRY: git.jf.eng.br
IMAGE: git.jf.eng.br/jfeng/evogo
jobs:
promote:
name: Promover release para latest
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Identificar release
id: rel
run: |
git fetch --tags --force
TAG=$(git describe --tags --abbrev=0 --match 'v*' HEAD)
SHA7=$(git rev-list -n1 "$TAG" | cut -c1-7)
VERSION="${TAG#v}"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "source=${IMAGE}:${VERSION}-${SHA7}" >> "$GITHUB_OUTPUT"
echo "Release: ${TAG} -> ${IMAGE}:${VERSION}-${SHA7}"
- name: Login no Gitea Package Registry
run: |
USER="${{ secrets.REGISTRY_USER }}"
[ -n "$USER" ] || USER="${{ github.actor }}"
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
for n in 1 2 3 4 5; do
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
exit 1
- name: Re-etiquetar como latest
run: |
retry() {
for n in 1 2 3 4 5; do
"$@" && return 0
echo "'$*' falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
return 1
}
SRC="${{ steps.rel.outputs.source }}"
retry docker pull "$SRC"
docker tag "$SRC" "$IMAGE:latest"
retry docker push "$IMAGE:latest"
echo "Publicado: $IMAGE:latest (mesmo digest de $SRC)"
+53
View File
@@ -0,0 +1,53 @@
name: Sincronizacao Diaria com o Upstream
# Incorpora o upstream oficial (evolution-foundation/evolution-go) sem perder as
# correcoes EvoGO: o merge e feito numa branch maintenance/sync-upstream-<sha>
# criada a partir de maintained-develop, testado e enviado como PR.
# Conflitos viram Issue. maintained-stable nunca e tocada.
# Ver scripts/upstream-sync.sh e docs/maintenance/UPSTREAM_SYNC.md.
on:
schedule:
# Diariamente as 04:00 UTC (01:00 BRT)
- cron: '0 4 * * *'
workflow_dispatch:
concurrency:
group: upstream-sync
cancel-in-progress: false
jobs:
sync:
name: Incorporar upstream e verificar whatsmeow
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
ref: maintained-develop
fetch-depth: 0
token: ${{ secrets.GITEA_TOKEN }}
- name: Configurar Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Instalar Dependencias de Sistema
run: |
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libjpeg-dev libwebp-dev
- name: Sincronizar com o upstream
env:
GITEA_URL: ${{ github.server_url }}
REPO: ${{ github.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
# Defina a variavel de repositorio AUTO_MERGE_UPSTREAM=true para mesclar
# automaticamente em maintained-develop quando build e testes passarem.
AUTO_MERGE: ${{ vars.AUTO_MERGE_UPSTREAM || 'false' }}
run: |
git config user.name "EvoGO Upstream Bot"
git config user.email "[email protected]"
bash scripts/upstream-sync.sh
+157
View File
@@ -0,0 +1,157 @@
# AGENTS.md — Diretrizes de Manutenção para Agentes de IA (EvoGO)
Este repositório é uma distribuição/fork independente do **Evolution Go**, mantido no Gitea com suporte contínuo, correções de compatibilidade, segurança e pipelines automatizados.
Qualquer agente de IA que atue neste repositório deve obrigatoriamente seguir as diretrizes abaixo.
---
## 1. Infraestrutura e Ambientes
- **Servidor Git:** `https://git.jf.eng.br` (Gitea v28.3.0)
- **Organização / Proprietário padrão:** `jfeng`
- **Repositório:** `EvoGO`
- **URL Remota (SSH):** `ssh://[email protected]:1080/jfeng/EvoGO.git`
- **Gitea Actions Runner:** `runner-do-zimaos` (Global)
- **Label para execução de jobs:** `ubuntu-latest`
- **Upstream Oficial:** `https://github.com/evolution-foundation/evolution-go.git`
### Regras de Autenticação e Segredos
- Reutilize credenciais já configuradas no Gitea (`GITEA_TOKEN` nativo).
- Segredos de container registry disponíveis: `REGISTRY_USER` e `REGISTRY_TOKEN`.
- **NUNCA** inclua credenciais, senhas ou tokens no código-fonte, nos commits ou em logs.
- Não crie runners adicionais sem autorização explícita do proprietário.
---
## 2. Arquitetura Resumida do Projeto
O Evolution Go é uma API de integração com o WhatsApp desenvolvida em Go (Go 1.25/1.26), de alta performance e baixo consumo de memória, utilizando a biblioteca `whatsmeow` (Go/WebSocket/Noise protocol).
### Estrutura de Pastas:
- `cmd/evolution-go/main.go`: Ponto de entrada da aplicação, inicialização de rotas, banco e serviços.
- `pkg/core/`: Gerenciamento de runtime, middlewares centrais e verificação de licença.
- `pkg/whatsmeow/service/`: Camada de abstração e comunicação com a biblioteca whatsmeow, controle de clientes, reconexão e handshake de versão.
- `pkg/instance/`: Gerenciamento de instâncias (iniciar, parar, conectar, QR Code, pairing).
- `pkg/message/`: Modelos, repositórios e serviços de mensagens recebidas e salvas.
- `pkg/sendMessage/`: Envio de mensagens de texto, mídias, áudios, stickers, enquetes e interações.
- `pkg/routes/`: Registro de todas as rotas da API REST (Gin).
- `pkg/events/`: Publicadores de eventos para Webhooks, WebSocket, RabbitMQ e NATS.
- `manager/dist/`: Frontend SPA compilado do console de gerenciamento.
- `.gitea/workflows/`: Pipelines de CI/CD para Gitea Actions.
- `docs/maintenance/`: Documentação operacional e governança do fork independente.
---
## 3. Estratégia de Branches e Ciclo de Vida
O repositório adota um modelo de isolamento estrito para proteger o código em produção:
```
[upstream/main] (GitHub)
│ (sincronização manual/controlada)
▼
[upstream-sync] (Gitea)
│
▼
[maintained-develop] ◄── [fix/*] (ex: fix/client-outdated-405)
│ ◄── [maintenance/*] (ex: dependências)
▼ (após testes e validação)
[maintained-stable] (origem das releases e imagens Docker oficiais)
```
1. **`upstream-sync`**:
- Espelha fielmente a branch principal do upstream oficial (`evolution-foundation/evolution-go`).
- Nunca recebe commits diretos com alterações locais ou de customização.
2. **`maintained-stable`**:
- Versão de produção da nossa distribuição.
- Apenas recebe merges após validação completa na branch `maintained-develop`.
- Origem das tags imutáveis e releases de imagens Docker.
3. **`maintained-develop`**:
- Branch principal de integração. Novas correções e bumps de dependências são mesclados aqui primeiro.
4. **`fix/*` e `maintenance/*`**:
- Branches de trabalho isoladas para correções específicas e atualizações de bibliotecas.
- Devem ser criadas a partir de `maintained-develop`.
---
## 4. Regras para Modificações e Padrões Go
1. **Priorize correções atômicas, pequenas e reversíveis:**
- Evite refatorações em massa que dificultem o rebase ou cherry-pick futuro contra o upstream.
2. **Preservação de Licenças e Atribuições:**
- Mantenha intocados os arquivos `LICENSE`, `NOTICE` e `TRADEMARKS.md`.
- Não altere, remova ou burle mecanismos de licenciamento ou autenticação existentes em `pkg/core/`.
3. **Padrões de Código Go:**
- Formatação obrigatória com `go fmt ./...`.
- Análise estática limpa com `go vet ./...`.
- Tratamento explícito de erros: nunca ignore erros (`_ = err` é proibido em I/O e conexões).
- Use contextos (`context.Context`) em todas as chamadas bloqueantes e de rede.
- Proteção de concorrência com `sync.Mutex` ao manipular estados de clientes ou caches globais.
4. **Compatibilidade com o Upstream:**
- Mantenha modificações isoladas em camadas de serviço (`pkg/.../service/`), preservando as assinaturas dos handlers HTTP e contratos públicos da API sempre que possível.
---
## 5. Procedimentos de Atualização e Sincronização
Quando houver novos lançamentos ou commits no repositório upstream:
1. **Buscar alterações sem merge imediato:**
```bash
git fetch upstream --tags
```
2. **Comparar histórico:**
```bash
git log upstream-sync..upstream/main --oneline
git diff upstream-sync..upstream/main
```
3. **Atualizar `upstream-sync` (fast-forward apenas):**
```bash
git checkout upstream-sync
git merge --ff-only upstream/main
```
4. **Criar branch de integração para análise de impacto:**
```bash
git checkout -b maintenance/sync-upstream-<versao> maintained-develop
git merge upstream-sync
```
5. **Resolver conflitos e executar testes:**
- Validar testes automatizados: `go test ./...`.
- Construir imagem de teste e validar checklist de compatibilidade.
6. **Abrir Pull Request no Gitea:**
- Submeta PR de `maintenance/sync-upstream-<versao>` para `maintained-develop`.
- Nunca faça merge direto para `maintained-stable`.
---
## 6. Procedimento de Build e Docker
### Build Local / Validação Go:
```bash
go vet ./...
go test -v ./...
CGO_ENABLED=1 go build -o server ./cmd/evolution-go
```
### Build Docker:
```bash
docker build -t evogo:local -f Dockerfile .
```
### Regras de Publicação de Imagens:
1. Imagens **NUNCA** devem ser publicadas sem aprovação humana expressa.
2. As tags devem incluir o identificador imutável do commit git (ex: `evogo:0.7.2-abc1234`) e a tag semântica (ex: `evogo:0.7.2`).
3. A tag `:latest` só deve ser atualizada quando uma versão for promovida e aprovada em `maintained-stable`.
---
## 7. Processo de Revisão e Checklist Obrigatório
Antes de aprovar ou propor qualquer merge:
- [ ] O código compila sem warnings no `go vet`.
- [ ] Todos os testes unitários passam (`go test ./...`).
- [ ] A compatibilidade com sessões do WhatsApp existentes foi avaliada (migrações de SQLite/Postgres).
- [ ] Nenhuma credencial ou segredo foi exposta.
- [ ] O arquivo `CHANGELOG.md` foi atualizado sob a seção adequada.
- [ ] O rollback foi planejado e documentado caso ocorra regressão.
+64
View File
@@ -1,5 +1,69 @@
# Evolution GO - Changelog # Evolution GO - Changelog
## Não lançado
### 🔧 Correções
- **whatsmeow atualizado para 2026-11-02** — a versão fixada na 0.7.2
(commit `b572e5bcb92b`, de 30/06/2026) ficou 125 dias atrás do upstream. O
WhatsApp subiu a versão mínima de cliente nesse intervalo e passou a recusar a
conexão com **405 client outdated**, impedindo pareamento e reconexão das
instâncias. Agora em `v0.0.0-20261102152715-54038813c47f`.
- **Go 1.26** — o whatsmeow novo exige `go >= 1.26.0`; o `Dockerfile` passou a
usar `golang:1.26.10-alpine` no estágio de build.
- **Ajustes de API do whatsmeow** — `UpdateBlocklist` e `GetBlocklist` agora
recebem um `dhash`; `SetStatusMessage` passou a receber `types.SetStatusInput`
(novo endpoint mex). O formato de resposta de bloqueio mudou de
`Modifications` para `Items` (com `LID`/`PN`/`Active`) — a documentação foi
atualizada, mas integrações que leem `Modifications` precisam de ajuste.
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe
de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
ao abrir o container; testado com banco SQLite v14 existente.
- **Build quebrado após o fix 405** — `whatsmeow.go` referenciava `waProto`
(pacote inexistente); `ClientPayload_UserAgent_AppVersion` vem de
`go.mau.fi/whatsmeow/proto/waWa6`.
- **Nono dígito (BR)** — envios para celulares brasileiros consultam no
WhatsApp as duas variantes (com e sem o 9) e usam a que está registrada.
Contas antigas sem o 9 (ex.: `554291389691`) passam a receber mesmo quando o
sistema envia `5542991389691`, e vice-versa (upstream issue #214 / PR #208).
- **LID enviado como número** — quando o `number` não existe como telefone mas
é o LID de um contato já conhecido pela instância (ex.: `255284433936406`),
o envio vai direto para `255284433936406@lid` em vez de falhar com
`no LID found for [email protected]`.
### 🆕 Novidades
- `GET /server/ok` passa a informar a versão em execução
(`{"status":"ok","version":"0.7.2-evogo.3-<sha7>"}`).
### 🛡️ Estabilidade (correções da comunidade incorporadas pelo EvoGO)
- **Crash `concurrent map writes`** — `clientPointer`, `myClientPointer` e
`killChannel` agora são `safemap.Map` com RWMutex (upstream PR #196, issue #203).
- **Vazamento de conexões Postgres** — um único `sqlstore.Container`
compartilhado em vez de um novo pool a cada `StartClient`/reconexão
(upstream PR #206, issues #165/#175/#215).
- **Loop de reconexão/QR infinito** — backoff progressivo após 5 reinícios em
15 min (upstream PR #197); cliente sem dispositivo pareado não é reiniciado
(upstream PR #240); `StartClient` duplicado é ignorado (upstream PR #239).
- **Panics que derrubavam todas as instâncias** — `ReconnectClient` serializado
por instância com checagem de nil (issue #188); envio em canal fechado ao
excluir instância durante o QR (issue #222); evento `Archive` (upstream PR #195).
- **Webhooks paravam após desconectar pela API** — `Disconnect` não apaga mais
as inscrições de eventos (upstream PR #187).
- **`/user/info` e `/user/avatar` travando 75 s** — `ParseJID` remove o `+` de
JIDs de usuário (upstream PR #224, issue #223).
- **WebSocket** — todos os assinantes de uma instância recebem eventos e as
escritas são serializadas por conexão (upstream PR #181).
- **NATS** — sem `NATS_URL` a conexão não é tentada (upstream PR #143).
### ⚙️ Manutenção EvoGO
- Sincronização diária com o upstream via Gitea Actions: merge em
`maintenance/sync-upstream-<sha>` a partir de `maintained-develop`, build/testes
e PR automático; conflitos viram Issue; aviso de whatsmeow desatualizado.
- Publicação da imagem em `git.jf.eng.br/jfeng/evogo` por tag `v*`, com tag
imutável `<versão>-<sha7>` e scan Trivy.
- Login, pull e push no registry com até 5 tentativas — um timeout pontual do
endpoint de token derrubou a publicação da `v0.7.2-evogo.2` (run 482).
## v0.7.2 ## v0.7.2
**Docker:** `evoapicloud/evolution-go:0.7.2` **Docker:** `evoapicloud/evolution-go:0.7.2`
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.25.0-alpine AS build FROM golang:1.26.10-alpine AS build
RUN apk update && apk add --no-cache git build-base libjpeg-turbo-dev libwebp-dev RUN apk update && apk add --no-cache git build-base libjpeg-turbo-dev libwebp-dev
+1 -1
View File
@@ -5,7 +5,7 @@ APP_NAME=evolution-go
MAIN_PATH=cmd/evolution-go/main.go MAIN_PATH=cmd/evolution-go/main.go
BUILD_DIR=build BUILD_DIR=build
GO=go GO=go
VERSION=$(shell grep -om1 "v[0-9].*" CHANGELOG.md) VERSION=$(shell sed -n 's/^## \(v[0-9][^ ]*\).*/\1/p' CHANGELOG.md | head -1)
LDFLAGS=-ldflags "-X main.version=$(VERSION)" LDFLAGS=-ldflags "-X main.version=$(VERSION)"
GOFLAGS=-v GOFLAGS=-v
+4 -3
View File
@@ -5,6 +5,7 @@ import (
"database/sql" "database/sql"
"flag" "flag"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"log" "log"
"net/http" "net/http"
"os" "os"
@@ -83,8 +84,8 @@ func init() {
} }
func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.Config, conn *amqp.Connection, exPath string, runtimeCtx *core.RuntimeContext) *gin.Engine { 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)) killChannel := safemap.New[chan bool]()
clientPointer := make(map[string]*whatsmeow.Client) clientPointer := safemap.New[*whatsmeow.Client]()
loggerWrapper := logger_wrapper.NewLoggerManager(config) loggerWrapper := logger_wrapper.NewLoggerManager(config)
@@ -238,7 +239,7 @@ func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.C
label_handler.NewLabelHandler(labelService), label_handler.NewLabelHandler(labelService),
newsletter_handler.NewNewsletterHandler(newsletterService), newsletter_handler.NewNewsletterHandler(newsletterService),
pollHandler, pollHandler,
server_handler.NewServerHandler(), server_handler.NewServerHandler(version),
).AssignRoutes(r) ).AssignRoutes(r)
if config.ConnectOnStartup { if config.ConnectOnStartup {
+98
View File
@@ -0,0 +1,98 @@
# Arquitetura do Sistema — EvoGO
## 1. Visão Geral
O **EvoGO** é uma distribuição independente da Evolution Go, uma API de alto desempenho construída em Go para controle e integração com instâncias do WhatsApp Web via protocolo WebSocket/Noise utilizando a biblioteca `whatsmeow`.
A aplicação atua como um gateway REST e Websocket/Eventos, permitindo que sistemas corporativos e aplicações SaaS gerenciem instâncias do WhatsApp, enviem mensagens de texto, mídias, stickers, listas interativas, botões, realizem consultas a grupos e processem webhooks em tempo real.
---
## 2. Diagrama de Arquitetura
```
┌────────────────────────────────────────────────────────┐
│ Clientes Externos │
│ (Sistemas Web, CRMs, n8n, Agentes IA) │
└───────────────────────────┬────────────────────────────┘
│ HTTP REST / WebSocket
▼
┌───────────────────────────────────────────────────────────────────────────────────┐
│ EvoGO Core │
│ │
│ ┌─────────────────────┐ ┌───────────────────────┐ ┌─────────────────────┐ │
│ │ Rotas Gin HTTP │──▶│ Auth / License Check │──▶│ Handlers (pkg/*) │ │
│ │ (pkg/routes) │ │ (pkg/core) │ │ (instance, msg, …) │ │
│ └─────────────────────┘ └───────────────────────┘ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Services de Negócio │ │
│ │ (pkg/*/service) │ │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Whatsmeow Service │ │
│ │ (Handshake/Versão) │ │
│ └──────────┬──────────┘ │
└────────────────────────────────────────────────────────────────────┼──────────────┘
│
┌───────────────────────────────────────────┴─────────────────────────┐
│ │
▼ ▼
┌───────────────────────────────────────┐ ┌───────────────────────────────────────┐
│ WhatsApp Web Servers │ │ Bancos e Mensageria Local │
│ (Noise Protocol / WebSocket) │ │ - SQLite / PostgreSQL (Sessões) │
│ - Handshake com store.SetWAVersion│ │ - Redis / Caches de Versão / MinIO │
│ - Pairing Code e QR Code │ │ - RabbitMQ / NATS / Webhooks │
└───────────────────────────────────────┘ └───────────────────────────────────────┘
```
---
## 3. Módulos e Componentes Principais
### 3.1. `cmd/evolution-go/main.go`
- Inicializa as variáveis de ambiente e configurações globais (`pkg/config`).
- Inicializa a conexão com o banco de dados (SQLite ou PostgreSQL via GORM).
- Inicializa os serviços de mensageria (RabbitMQ, NATS, Webhooks e WebSockets).
- Configura o mecanismo de licenciamento e heartbeat (`pkg/core`).
- Inicia o servidor HTTP Gin na porta configurada (padrão: 8080).
### 3.2. `pkg/core/`
- **Validação de Runtime e Licença:** Contém a verificação de ativação via `EVOLUTION_OPERATOR_EMAIL` ou `GLOBAL_API_KEY`.
- **Middleware de Proteção:** Intercepta rotas e garante que endpoints da API retornem 503 caso o serviço ainda não esteja licenciado, permitindo apenas rotas administrativas de ativação (`/license/*`).
### 3.3. `pkg/whatsmeow/service/`
- **Abstração do Whatsmeow:** Gerencia a criação do `whatsmeow.Client`, mapeia manipuladores de eventos (`EventHandler`) para mensagens, status e presença.
- **Handshake e Resolução de Versão:** Responsável por evitar o erro `Client outdated (405)`. Realiza busca da versão do WhatsApp Web em `https://web.whatsapp.com/sw.js` com cache de 1 hora, injeta User-Agent padronizado e aplica via `store.SetWAVersion` e `store.BaseClientPayload.UserAgent.AppVersion`.
### 3.4. `pkg/instance/`
- Controla o ciclo de vida de cada número de WhatsApp conectado (instância).
- Salva o estado da conexão (`connecting`, `open`, `close`, `refused`).
- Permite pareamento via QR Code (Base64) ou código de pareamento numérico (Pairing Code).
### 3.5. `pkg/sendMessage/`
- Implementa endpoints de envio com suporte a texto, áudios convertidos (opus/ogg), imagens, vídeos, documentos PDF com prévia/thumbnail rasterizada via `poppler-utils` (`pdftoppm`), enquetes, contatos e mensagens interativas (botões e listas).
### 3.6. `manager/dist/`
- Console administrativo em frontend SPA (React/Vite) servido diretamente pelo binário em `/manager`.
---
## 4. Persistência de Dados
1. **Estado das Instâncias e Mensagens da API:**
- Suporta SQLite (`evolution.db`) para ambientes simples ou PostgreSQL para ambientes de alta concorrência.
2. **Sessões Criptográficas do WhatsApp:**
- O `whatsmeow` armazena chaves de sessão, tokens de pré-chave, registros de identidade e metadados de autenticação nas tabelas de schema do whatsmeow (`whatsmeow_device`, `whatsmeow_identity_keys`, etc.).
- As migrações de schema do whatsmeow (ex: v14 para v16) são executadas automaticamente pela biblioteca na abertura do container.
---
## 5. Práticas para Manutenção por Agentes de IA
- Ao implementar novas rotas, mantenha a separação em camadas: `handler` (validação e parsing HTTP) -> `service` (regras de negócio e chamadas whatsmeow) -> `repository` (interação com banco).
- Nunca modifique métodos do `pkg/core/` que alterem a verificação de licenciamento.
- Nunca adicione chamadas diretas de rede sem timeout configurado.
+128
View File
@@ -0,0 +1,128 @@
# Guia de Compilação e Publicação (BUILD_AND_RELEASE.md)
Este documento descreve detalhadamente o processo de compilação da aplicação, construção das imagens Docker, convenções de tags e fluxo de publicação em registry próprio.
---
## 1. Requisitos de Ambiente
- **Go:** Versão Go 1.25+ ou 1.26+ (conforme exigido pela versão do `whatsmeow` em uso).
- **CGO:** Habilitado (`CGO_ENABLED=1`) para compilação com suporte a drivers nativos e processamento de imagens/PDFs.
- **Bibliotecas nativas de sistema (Alpine/Debian):**
- `libjpeg-turbo-dev`
- `libwebp-dev`
- `poppler-utils` (`pdftoppm` para geração de thumbnails de PDF)
- `ffmpeg` (para conversão e manipulação de mídias de áudio/vídeo)
- **Docker:** Engine 24.0+ com plugin `buildx`.
---
## 2. Compilação Local
### Compilar binário para teste:
```bash
# Definir versão de compilação
VERSION=$(cat VERSION 2>/dev/null || echo "dev")
# Compilar com tags de linkagem
CGO_ENABLED=1 go build -ldflags "-X main.version=${VERSION}" -o build/evolution-go ./cmd/evolution-go
```
### Executar a suite de testes:
```bash
# Executar todos os testes
go test -v ./...
# Executar testes com detecção de data race
go test -race ./...
```
---
## 3. Construção da Imagem Docker
A construção utiliza Dockerfile multi-stage otimizado:
- **Estágio 1 (`build`):** Imagem base Go Alpine com compilador, dependências C e ferramentas de build.
- **Estágio 2 (`final`):** Imagem final Alpine mínima contendo apenas os binários, dependências de runtime (`ffmpeg`, `poppler-utils`, `libwebp`), assets estáticos do manager (`manager/dist`) e timezone.
### Comando de Build Manual:
```bash
# Exemplo para versão 0.7.2 com SHA do commit
COMMIT_SHA=$(git rev-parse --short HEAD)
VERSION=$(cat VERSION)
docker build \
--build-arg VERSION="${VERSION}-${COMMIT_SHA}" \
-t evogo:${VERSION}-${COMMIT_SHA} \
-t evogo:latest \
-f Dockerfile .
```
---
## 4. Estratégia de Registry e Publicação
### Registries Alvo:
1. **Gitea Package Registry (Recomendado):**
- Endereço: `git.jf.eng.br`
- Imagem: `git.jf.eng.br/jfeng/evogo`
- Autenticação: Utiliza o token padrão do Gitea Actions (`secrets.GITEA_TOKEN`) ou credenciais configuradas.
2. **Registry Externo (se configurado):**
- Variáveis: `REGISTRY_USER` e `REGISTRY_TOKEN`.
### Convenções de Tags:
- **Tag Imutável por Commit:** `git.jf.eng.br/jfeng/evogo:${VERSION}-${COMMIT_SHA}` (ex: `0.7.2-9337afc`)
- **Tag de Versão Semântica:** `git.jf.eng.br/jfeng/evogo:${VERSION}` (ex: `0.7.2`)
- **Tag Flutuante Estável:** `git.jf.eng.br/jfeng/evogo:latest` (atualizada **somente** após aprovação em `maintained-stable`)
- **Tag de Integração:** `git.jf.eng.br/jfeng/evogo:develop`
---
## 5. Pipeline Automatizado no Gitea Actions
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
1. **Push em `maintained-stable`:** build da imagem (`linux/amd64`), teste de
inicialização do binário e scan Trivy (HIGH/CRITICAL, não bloqueante).
**Não publica.**
2. **Push de tag `v<versão>` (release aprovado):** mesmo build/teste/scan e
publicação de:
- `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
- `git.jf.eng.br/jfeng/evogo:<versão>`
3. **`workflow_dispatch`:** publica apenas com `publish_image=true`; `:latest`
só com `promote_latest=true`.
### Gerar um release
```bash
git checkout maintained-develop && git pull
git tag -a v0.7.2-evogo.1 -m "EvoGO 0.7.2-evogo.1"
git push origin v0.7.2-evogo.1 # dispara o build e a publicação
```
### Usar no docker-compose
```yaml
services:
evolution-go:
image: git.jf.eng.br/jfeng/evogo:0.7.2-evogo.1
```
Como o pacote é privado, o host precisa de `docker login git.jf.eng.br`
(usuário Gitea + token com escopo `read:package`) antes de `docker compose pull`.
Para fixar exatamente o commit testado, use a tag imutável `<versão>-<sha7>`.
### Promover para `:latest`
`.gitea/workflows/promote-latest.yml` roda quando `maintained-stable` avança:
re-etiqueta a imagem imutável do último release `v*` contido na branch
(`<versão>-<sha7>`) como `:latest`, sem recompilar (mesmo digest).
```bash
git checkout maintained-stable
git merge --ff-only v0.7.2-evogo.1
git push origin maintained-stable # dispara a promoção para :latest
```
Rollback de `:latest`: avance/reverta `maintained-stable` para o release
anterior e rode o workflow manualmente, ou fixe a tag de versão no compose.
+73
View File
@@ -0,0 +1,73 @@
# Procedimento de Rollback e Recuperação (ROLLBACK.md)
Este documento descreve os passos operacionais para reverter rapidamente uma versão do **EvoGO** em caso de falha crítica em produção.
---
## 1. Condições de Disparo para Rollback
Um rollback imediato deve ser acionado nas seguintes situações:
1. **Rejeição em Massa pelo WhatsApp:** A taxa de erro na conexão ou pareamento ultrapassa 20% com respostas `405 Client Outdated`, `401 Unauthorized` ou `503 Service Unavailable`.
2. **Panic ou Reinicializações Contínuas (CrashLoop):** O container do EvoGO reinicia em loop devido a erros de runtime, falhas de I/O ou vazamento crítico de memória.
3. **Corrupção de Sessões:** Instâncias anteriormente pareadas perdem suas chaves de sessão após atualização.
4. **Regressão de Contrato de API:** Endpoints críticos de envio de mensagens falham de forma generalizada.
---
## 2. Procedimento Operacional de Rollback
### Passo 1: Identificar a Última Imagem Estável Validada
Consulte o histórico de deploys ou os registros no Gitea Package Registry.
Exemplo:
- Versão com falha: `git.jf.eng.br/jfeng/evogo:0.7.3-f8a9b2c`
- Versão estável anterior: `git.jf.eng.br/jfeng/evogo:0.7.2-9337afc`
### Passo 2: Atualização do Container / Docker Compose
No host de produção (ex: ZimaOS ou servidor Docker Swarm/Compose):
1. Edite o arquivo `docker-compose.yml`:
```yaml
services:
evolution-go:
image: git.jf.eng.br/jfeng/evogo:0.7.2-9337afc # Reverter para a tag imutável estável
```
2. Baixe a imagem anterior e reinicie o serviço:
```bash
docker compose pull evolution-go
docker compose up -d evolution-go
```
3. Verifique os logs de inicialização imediatamente:
```bash
docker compose logs -f --tail=100 evolution-go
```
---
## 3. Considerações sobre o Banco de Dados
### Sessões Whatsmeow e Schemas:
- O banco de dados armazena o schema do `whatsmeow` nas tabelas `whatsmeow_version` e associadas.
- **Atenção:** Se a versão nova executou uma migração de schema (ex: schema v14 para v16), o downgrade da biblioteca para uma versão antiga que espere schema v14 pode falhar se não houver compatibilidade reversa.
- **Boas Práticas de Prevenção:**
- Sempre realize um snapshot/backup do volume do banco de dados (`/data` ou banco PostgreSQL) antes de rodar atualizações de versão de dependência.
- Para restaurar o backup de emergência em SQLite:
```bash
cp /var/data/evolution.db.backup /var/data/evolution.db
```
---
## 4. Reversão no Git
Caso uma branch tenha sido integrada inadvertidamente em `maintained-stable`:
1. **Reverta o commit de merge:**
```bash
git checkout maintained-stable
git revert -m 1 <commit_do_merge> -m "revert: rollback da versão com falha"
git push origin maintained-stable
```
2. **Abra uma Issue no Gitea:**
- Descreva os sintomas observados, logs do erro, versão problemática e passos executados no rollback.
- Rotule como `bug` e `critical`.
+48
View File
@@ -0,0 +1,48 @@
# Diretrizes de Segurança (SECURITY.md)
Este documento estabelece os padrões e práticas de segurança aplicáveis ao fork **EvoGO**, em conformidade com as melhores práticas de desenvolvimento seguro e OWASP.
---
## 1. Gestão de Credenciais e Segredos
1. **Proibição Absoluta de Segredos no Código:**
- Nenhum token, senha de banco de dados, chave de API (`GLOBAL_API_KEY`, `AUTHENTICATION_API_KEY`) ou chave privada SSH pode ser adicionada ao repositório git.
- Utilize arquivos `.env` locais para desenvolvimento e injete variáveis de ambiente via Docker secrets ou docker-compose em produção.
2. **Prevenção de Vazamento em Logs:**
- Assegure que handlers HTTP e middlewares sanitizem cabeçalhos como `apikey`, `Authorization`, `token` e payloads de webhook antes de imprimir logs.
- Variáveis sensíveis como chaves de sessão do WhatsApp (`noise_keys`, `prekeys`) nunca devem ser expostas em logs, mesmo com `WA_DEBUG=DEBUG`.
3. **Controle de Acesso ao Repositório:**
- O repositório no Gitea deve permanecer privado.
- Apenas o proprietário e deploys autorizados possuem permissão de push.
---
## 2. Segurança de Rede e Exposição de Serviços
1. **Isolamento de Portas e Proxies:**
- O Evolution Go não deve ser exposto diretamente na internet sem um proxy reverso seguro (ex: Traefik, Nginx ou Cloudflare Tunnel) com terminação SSL/TLS (HTTPS).
- O console de gerenciamento (`/manager`) deve ter proteção adicional por IP restrito, VPN ou autenticação básica quando acessado remotamente.
2. **Conexões com o WhatsApp:**
- Toda comunicação entre o `whatsmeow` e os servidores do WhatsApp utiliza túneis criptografados via protocolo Noise sobre WebSocket (`wss://web.whatsapp.com/ws/chat`).
- Quando configurado proxy HTTP/SOCKS5 para as instâncias, certifique-se de que as credenciais do proxy sejam transmitidas de forma segura e não fiquem expostas em requisições de listagem pública.
---
## 3. Verificação Contínua de Dependências
1. **Auditoria de Módulos Go:**
- O pipeline do Gitea Actions deve executar verificações periódicas de vulnerabilidades conhecidas:
```bash
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
```
2. **Imagens Base Atualizadas:**
- O `Dockerfile` deve utilizar imagens Alpine e Go com patches de segurança recentes (ex: `golang:1.26.10-alpine` e `alpine:3.19.1+`).
---
## 4. Licenciamento e Proteção Legal
- As condições específicas da licença do Evolution Go (preservação de logotipos e avisos de direitos autorais no frontend manager) devem ser rigorosamente respeitadas.
- Qualquer alteração nos arquivos de licença ou mecanismos de validação é estritamente proibida por diretriz arquitetural.
+70
View File
@@ -0,0 +1,70 @@
# Política de Atualizações e Dependências (UPDATE_POLICY.md)
Este documento define as regras, periodicidades e critérios técnicos para aceitação, teste e incorporação de atualizações no fork **EvoGO**.
---
## 1. Classificação das Atualizações
Toda atualização deve ser classificada em uma das seguintes categorias:
### Nível 1: Emergencial / Crítica (Hotfix)
- **Cenários:** Queda geral de conexão do WhatsApp (ex: erro `Client outdated (405)`), vulnerabilidade de execução remota de código (RCE) ou corrupção de sessões.
- **Janela de Ação:** Imediata.
- **Fluxo:** Criação direta de branch `fix/<nome-do-problema>` baseada em `maintained-develop`, testes de bancada focados e geração de hotfix com deploy controlado após aprovação.
### Nível 2: Atualização de Dependência do WhatsApp (`whatsmeow`)
- **Cenários:** Novas versões da biblioteca `whatsmeow` lançadas por Tulir Asokan, contendo suporte a novos recursos do protocolo do WhatsApp ou novas revisões de schema.
- **Janela de Ação:** Semanal ou quinzenal.
- **Regra Técnica:** Verificar se há mudanças no schema do banco (ex: v14 -> v16) e na assinatura de funções públicas (ex: `UpdateBlocklist`, `GetBlocklist`, `SetStatusMessage`).
### Nível 3: Sincronização Periódica com Upstream
- **Cenários:** Novos commits na branch `main` ou `develop` do upstream oficial que trazem melhorias incrementais, novas rotas ou correções de bugs.
- **Janela de Ação:** Quinzenal ou mensal.
- **Fluxo:** Branch `maintenance/sync-upstream-<data>` -> PR para `maintained-develop`.
### Nível 4: Manutenção de Dependências Gerais (Go Modules)
- **Cenários:** Atualização de drivers (GORM, PostgreSQL, SQLite), Gin, logger, MinIO, etc.
- **Critério:** Atualizações de patches (`patch version`) são aceitas se os testes passarem. Atualizações de minor/major exigem análise de breaking changes.
---
## 2. Regras para Atualização da Biblioteca `whatsmeow`
A biblioteca `whatsmeow` é a peça central do sistema e a mais suscetível a quebras devido a mudanças nos servidores da Meta.
Ao atualizar a versão do `whatsmeow`:
1. **Investigar o histórico recente de commits do whatsmeow:**
- Acesse o repositório oficial da biblioteca: `https://github.com/tulir/whatsmeow`.
- Analise se houve alteração na versão mínima do Go (ex: migração para Go 1.26).
2. **Avaliar alterações de Schema no Banco de Dados:**
- A biblioteca whatsmeow realiza auto-migrações das tabelas do dispositivo (`device store`).
- Verifique se novas tabelas ou colunas foram adicionadas.
- **IMPORTANTE:** Bancos de dados em produção devem ter backup realizado antes da inicialização do novo container.
3. **Manter a injeção dinâmica de versão de handshake:**
- O Evolution Go deve manter a injeção em `pkg/whatsmeow/service/whatsmeow.go` (`store.SetWAVersion` e `store.BaseClientPayload.UserAgent.AppVersion`), assegurando que a versão em runtime seja respeitada mesmo que a biblioteca compilada fique temporariamente defasada.
---
## 3. Critérios de Rejeição de Atualizações
Uma atualização externa do upstream **DEVE SER REJEITADA OU BLOQUEADA** se:
- Modificar, contornar ou desativar os termos da licença Apache 2.0 / avisos de direitos autorais.
- Adicionar dependências externas não auditadas ou binários pré-compilados proprietários sem código-fonte.
- Quebrar retrocompatibilidade com endpoints existentes sem fornecer mecanismo de fallback ou versionamento de rota (`/v1`, `/v2`).
- Remover testes automatizados existentes sem justificativa técnica.
- Apresentar falhas nos testes de estresse ou memory leaks em profiling de conexões ativas.
---
## 4. Política de Versionamento de Releases
As tags e imagens Docker do EvoGO seguem o formato semântico estendido:
- **Versões estáveis:** `v0.7.2`, `v0.7.3`, etc.
- **Imagens Docker imutáveis:** `evogo:0.7.2-<commit_sha_curto>`
- **Imagens de teste (develop):** `evogo:develop-<commit_sha_curto>`
Nenhuma tag imutável já publicada em registry deve ser sobrescrita.
+140
View File
@@ -0,0 +1,140 @@
# Procedimento de Sincronização com o Upstream (UPSTREAM_SYNC.md)
Este documento estabelece o procedimento operacional padrão para rastrear, importar e integrar atualizações do repositório oficial da Evolution Foundation (`evolution-foundation/evolution-go`) em nossa distribuição independente no Gitea.
---
## 1. Configuração dos Remotos Git
O ambiente local e os runners devem estar configurados com dois remotos oficiais:
- **`origin`**: Nosso repositório no Gitea.
- SSH: `ssh://[email protected]:1080/jfeng/EvoGO.git`
- **`upstream`**: O repositório oficial no GitHub.
- HTTPS: `https://github.com/evolution-foundation/evolution-go.git`
Para verificar:
```bash
git remote -v
```
Caso necessário reconfigurar:
```bash
git remote set-url origin ssh://[email protected]:1080/jfeng/EvoGO.git
git remote add upstream https://github.com/evolution-foundation/evolution-go.git
```
---
## 2. Sincronização Automática (Gitea Actions)
O workflow `.gitea/workflows/upstream-sync-check.yml` roda todo dia às 04:00 UTC
(e sob demanda em *Actions → Sincronizacao Diaria com o Upstream → Run workflow*)
e executa `scripts/upstream-sync.sh`:
1. `git fetch upstream main --tags`.
2. Avança `upstream-sync` **somente por fast-forward** (push sem force). Se o
upstream reescrever histórico, abre Issue e para.
3. Se `maintained-develop` ainda não contém o upstream, cria
`maintenance/sync-upstream-<sha7>` **a partir de `maintained-develop`** e faz
`git merge --no-ff upstream/main`. Nossas correções ficam preservadas porque o
upstream é mesclado *por cima* do nosso código, nunca o contrário.
- **Conflito:** aborta e abre Issue com os arquivos em conflito e os comandos
para resolver (seção 3 abaixo).
- **Merge limpo:** roda `go build`, `go vet`, `go test`, faz push da branch e
abre PR para `maintained-develop` com commits novos, arquivos sensíveis
alterados (Dockerfile, go.mod, `pkg/core`, licenças) e resultado dos testes.
4. Compara o `go.mau.fi/whatsmeow` do `go.mod` com `@latest` e abre Issue quando
há versão mais nova (defasagem do whatsmeow causa o erro 405).
Mesclagem automática em `maintained-develop` (opcional): crie a variável de
repositório `AUTO_MERGE_UPSTREAM=true` (*Settings → Actions → Variables*). O PR
só é mesclado se build e testes passarem. `maintained-stable` **nunca** é tocada
pela automação; a promoção e a publicação da imagem continuam manuais.
## 3. Fluxo Manual de Sincronização
A sincronização **NUNCA** deve sobrescrever diretamente a branch `maintained-stable` ou branches ativas de desenvolvimento sem validação.
### Etapa 1: Obter novidades do upstream
```bash
git fetch upstream --tags
```
### Etapa 2: Identificar commits e tags novas
Compare nossa branch de referência `upstream-sync` com a branch `main` do upstream:
```bash
git log upstream-sync..upstream/main --oneline
git log -n 5 upstream/main --stat
```
Verifique se foram geradas novas tags:
```bash
git tag -l -n1 --sort=-v:refname | head -n 10
```
### Etapa 3: Atualizar a branch `upstream-sync`
A branch `upstream-sync` é uma cópia 1:1 do upstream. Atualize-a utilizando exclusivamente fast-forward:
```bash
git checkout upstream-sync
git merge --ff-only upstream/main
git push origin upstream-sync --tags
```
---
## 4. Integração e Análise de Impacto
### Etapa 4: Criar branch de teste e integração
A partir de `maintained-develop`, crie uma branch de manutenção específica para a atualização:
```bash
git checkout maintained-develop
git pull origin maintained-develop
git checkout -b maintenance/sync-upstream-<nova-versao>
```
### Etapa 5: Realizar o merge controlado
```bash
git merge upstream-sync
```
Se houver conflitos:
1. Examine os arquivos em conflito com `git status` e `git diff`.
2. Dê prioridade a preservar nossas melhorias arquiteturais e correções (ex: injeção de handshake no `pkg/whatsmeow/service/whatsmeow.go`, configurações de CI do Gitea).
3. Nunca utilize `git merge -X theirs` indiscriminadamente.
4. Conclua o merge com `git commit`.
---
## 5. Validação Pós-Sincronização
Antes de propor a integração para as branches mantidas:
1. **Validação do Go:**
```bash
go vet ./...
go test -v ./...
```
2. **Compilação da aplicação:**
```bash
CGO_ENABLED=1 go build -o /dev/null ./cmd/evolution-go
```
3. **Verificação de dependências (`go.mod` e `go.sum`):**
```bash
go mod verify
```
4. **Verificação de arquivos de licença e autoria:**
Confirme que `LICENSE`, `NOTICE` e avisos legais permanecem intactos.
---
## 6. Promoção para as Branches Oficiais
1. **Abra um Pull Request no Gitea:**
- Origem: `maintenance/sync-upstream-<nova-versao>`
- Destino: `maintained-develop`
- Anexe o relatório de impacto, diffs relevantes e resultado dos testes.
2. **Revisão e Aprovação:**
- O proprietário valida as mudanças e executa testes em staging.
3. **Promoção para `maintained-stable`:**
- Uma vez homologado em `maintained-develop`, realiza-se o merge para `maintained-stable` para posterior geração de imagem Docker oficial.
@@ -0,0 +1,91 @@
# Compatibilidade com o WhatsApp e Resolução do Erro 405 (WHATSAPP_COMPATIBILITY.md)
Este documento documenta o protocolo de conexão com o WhatsApp Web, o diagnóstico aprofundado do erro **`Client outdated (405)`**, a análise comparativa dos Pull Requests da comunidade e o checklist oficial de testes de compatibilidade.
---
## 1. Funcionamento do Protocolo WhatsApp Web e Versões de Cliente
O WhatsApp Web opera sobre conexões WebSocket criptografadas via protocolo Noise. Durante o handshake de estabelecimento de conexão, o cliente deve enviar um payload (`ClientPayload`) contendo sua versão de aplicação (`AppVersion` / `waVersion`).
Periodicamente, os servidores da Meta elevam o patamar mínimo aceito da versão do cliente web. Quando um cliente envia uma versão abaixo desse patamar mínimo, o servidor WhatsApp recusa o handshake imediatamente com o código de erro:
```
405 Client outdated
```
Isso impede:
- Conexão e inicialização de novas instâncias.
- Geração de QR Code e Pairing Code.
- Reconexão de sessões existentes após reinicialização do container.
---
## 2. Diagnóstico Técnico dos Pull Requests Upstream
Durante o segundo semestre de 2026, uma elevação do patamar de versão do WhatsApp causou a falha 405 generalizada. Quatro Pull Requests principais foram submetidos ao repositório oficial `evolution-foundation/evolution-go`:
### PR #226: `fix(deps): bump whatsmeow to fix "Client outdated (405)"`
- **Autor:** MayconVM
- **Modificações:**
- Atualizou o `whatsmeow` para `v0.0.0-20261102152715-54038813c47f`.
- Atualizou o Go para 1.26 (`go.mod` e `Dockerfile`).
- Corrigiu quebras de API em `user_service.go` (`UpdateBlocklist`, `GetBlocklist`, `SetStatusMessage`).
- **Limitação:** Não adicionou documentação nem tratou a injeção dinâmica de versão de handshake em runtime.
### PR #229: `fix(whatsmeow): apply store.SetWAVersion to update WhatsApp client handshake version`
- **Autor:** Comunidade
- **Modificações:**
- Identificou que o Evolution Go apenas alterava `store.DeviceProps.Version`, o que **não atualiza** o handshake do `whatsmeow`.
- Adicionou chamada explícita a `store.SetWAVersion(...)`.
- Adicionou User-Agent Chrome e timeout de 10s no `fetchWhatsAppWebVersion()` em `sw.js`.
- Adicionou fallback seguro de versão (`2.3000.1052812464`).
- **Limitação:** Feito sobre o código antigo com whatsmeow desatualizado.
### PR #230: `fix: apply fetched WhatsApp version to the handshake (Client outdated 405)`
- **Autor:** Comunidade
- **Modificações:**
- Reforçou a injeção chamando `store.SetWAVersion(next)` e `store.BaseClientPayload.UserAgent.AppVersion = next.ProtoAppVersion()`.
- Adicionou lock de mutex (`waVersionMu`) e comparação `isNewerWAVersion`.
### PR #233: `deps: bump whatsmeow to 2026-11-02 (fix 405 client outdated)`
- **Autor:** MayconVM
- **Modificações:**
- Evolução consolidada do PR #226.
- Atualizou `whatsmeow` para `2026-11-02`.
- Incluiu notas completas no `CHANGELOG.md` documentando a migração do schema SQLite de v14 para v16 e a mudança na resposta do blocklist (`Items` vs `Modifications`).
- Atualizou `Makefile`, `Dockerfile` (`golang:1.26.10-alpine`) e documentação de API (`api-user.md`).
---
## 3. Estratégia Adotada no EvoGO (`fix/client-outdated-405`)
Para garantir uma solução definitiva, robusta e que não quebre novamente na próxima atualização do WhatsApp Web, a branch `fix/client-outdated-405` combina:
1. **A base do PR #233:**
- Biblioteca `whatsmeow` atualizada para `2026-11-02`.
- Toolchain Go 1.26.
- Ajustes de API em `user_service.go`.
- Documentação e migração automática de schema.
2. **As melhorias de runtime dos PRs #229 e #230:**
- Adição de User-Agent e timeout no `fetchWhatsAppWebVersion` para evitar bloqueios ao consultar `web.whatsapp.com/sw.js`.
- Chamada a `store.SetWAVersion` e sincronização de `store.BaseClientPayload.UserAgent.AppVersion` durante o `StartClient`.
Desta forma, mesmo que novos patamares de versão do WhatsApp sejam exigidos antes de um novo rebuild do EvoGO, a aplicação busca e injeta a versão mais recente em tempo de execução automaticamente.
---
## 4. Checklist Obrigatório de Testes de Compatibilidade
Antes de promover qualquer atualização relacionada ao WhatsApp para `maintained-stable`, o seguinte checklist deve ser executado e validado em ambiente de homologação (staging):
- [ ] **1. Inicialização da Aplicação:** O container inicializa limpo, conecta ao banco e sobe o servidor HTTP sem erros de dependência ou biblioteca.
- [ ] **2. Conexão e Handshake:** A instância inicia e o handshake é aceito pelo WhatsApp com log `Applied WhatsApp handshake version`.
- [ ] **3. Geração de QR Code:** O endpoint `/instance/connect/:instance` gera o QR Code em base64 e exibe no console manager.
- [ ] **4. Pareamento por Código (Pairing Code):** O endpoint `/instance/pair/:instance` retorna o código numérico de 8 dígitos para vinculação de aparelho.
- [ ] **5. Persistência de Sessão:** As chaves de criptografia e metadados de sessão são gravados corretamente no banco de dados (`whatsmeow_device`).
- [ ] **6. Reinicialização de Container:** Ao reiniciar o container (`docker restart`), a instância reconecta automaticamente sem exigir nova leitura de QR Code.
- [ ] **7. Envio de Mensagem de Texto:** O endpoint `/message/sendText/:instance` entrega a mensagem com status de sucesso.
- [ ] **8. Envio de Mídias e Áudio:** O endpoint `/message/sendMedia/:instance` entrega imagem e áudio com conversão de formato correta.
- [ ] **9. Recebimento de Mensagens e Webhooks:** Mensagens enviadas de volta para o número pareado disparam eventos no webhook configurado.
- [ ] **10. Compatibilidade de Banco Existente:** Nenhuma instância ou histórico é perdido ao subir uma versão com schema atualizado do whatsmeow (v14 -> v16).
+18 -13
View File
@@ -404,12 +404,13 @@ Bloqueia um contato no WhatsApp.
{ {
"message": "success", "message": "success",
"data": { "data": {
"AddressingMode": "lid",
"DHash": "abc123", "DHash": "abc123",
"PrevDHash": "def456", "Items": [
"Modifications": [
{ {
"JID": "[email protected]", "LID": "123456789012345@lid",
"Action": "block" "PN": "[email protected]",
"Active": true
} }
] ]
} }
@@ -452,12 +453,13 @@ Desbloqueia um contato previamente bloqueado.
{ {
"message": "success", "message": "success",
"data": { "data": {
"AddressingMode": "lid",
"DHash": "abc123", "DHash": "abc123",
"PrevDHash": "def456", "Items": [
"Modifications": [
{ {
"JID": "[email protected]", "LID": "123456789012345@lid",
"Action": "unblock" "PN": "[email protected]",
"Active": true
} }
] ]
} }
@@ -492,15 +494,18 @@ apikey: SUA-CHAVE-API
{ {
"message": "success", "message": "success",
"data": { "data": {
"AddressingMode": "lid",
"DHash": "abc123", "DHash": "abc123",
"Modifications": [ "Items": [
{ {
"JID": "[email protected]", "LID": "123456789012345@lid",
"Action": "block" "PN": "[email protected]",
"Active": true
}, },
{ {
"JID": "[email protected]", "LID": "987654321098765@lid",
"Action": "block" "PN": "[email protected]",
"Active": true
} }
] ]
} }
+12 -12
View File
@@ -1,6 +1,6 @@
module github.com/evolution-foundation/evolution-go module github.com/evolution-foundation/evolution-go
go 1.25.0 go 1.26.0
require ( require (
github.com/DATA-DOG/go-sqlmock v1.5.2 github.com/DATA-DOG/go-sqlmock v1.5.2
@@ -21,11 +21,11 @@ require (
github.com/swaggo/gin-swagger v1.6.0 github.com/swaggo/gin-swagger v1.6.0
github.com/swaggo/swag v1.16.3 github.com/swaggo/swag v1.16.3
github.com/vincent-petithory/dataurl v1.0.0 github.com/vincent-petithory/dataurl v1.0.0
go.mau.fi/whatsmeow v0.0.0-20260630180629-b572e5bcb92b go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f
golang.org/x/exp v0.0.0-20260611194520-c48552f49976 golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 golang.org/x/image v0.0.0-20211028202545-6944b10bf410
golang.org/x/net v0.56.0 golang.org/x/net v0.61.0
google.golang.org/protobuf v1.36.11 google.golang.org/protobuf v1.36.12
gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/natefinch/lumberjack.v2 v2.2.1
gorm.io/driver/postgres v1.5.9 gorm.io/driver/postgres v1.5.9
gorm.io/gorm v1.25.10 gorm.io/gorm v1.25.10
@@ -75,7 +75,7 @@ require (
github.com/nats-io/nuid v1.0.1 // indirect github.com/nats-io/nuid v1.0.1 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/rs/xid v1.6.0 // indirect github.com/rs/xid v1.6.0 // indirect
@@ -84,13 +84,13 @@ require (
github.com/ugorji/go/codec v1.2.12 // indirect github.com/ugorji/go/codec v1.2.12 // indirect
github.com/vektah/gqlparser/v2 v2.5.27 // indirect github.com/vektah/gqlparser/v2 v2.5.27 // indirect
go.mau.fi/libsignal v0.2.2 // indirect go.mau.fi/libsignal v0.2.2 // indirect
go.mau.fi/util v0.9.10 // indirect go.mau.fi/util v0.11.0 // indirect
golang.org/x/arch v0.10.0 // indirect golang.org/x/arch v0.10.0 // indirect
golang.org/x/crypto v0.53.0 // indirect golang.org/x/crypto v0.58.0 // indirect
golang.org/x/sync v0.21.0 // indirect golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.46.0 // indirect golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.38.0 // indirect golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.46.0 // indirect golang.org/x/tools v0.52.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
modernc.org/libc v1.55.3 // indirect modernc.org/libc v1.55.3 // indirect
+28 -28
View File
@@ -111,8 +111,8 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.45 h1:6KA/spDguL3KV8rnybG7ezSaE4SeMR3KC9VbUoAQaIk= github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdog8U=
github.com/mattn/go-sqlite3 v1.14.45/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= 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 h1:2mdUHXEykRdY/BigLt3Iuu1otL0JTogT0Nmltg0wujk=
@@ -134,8 +134,8 @@ github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaR
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= 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 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 h1:WDsQxOJDy0N1VRAjXLpi8sCEZRSGarLWQevDxpTBRrM= github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b h1:OzNsuVdSWGwXvWKTtChx9ve89k4cFJ6NxYM4Aw4/f+E=
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
@@ -160,8 +160,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.1/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.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.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= 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 h1:y8sxvQ3E20/RCyrXeFfg60r6H0Z+SwpTjMYsMm+zy8M=
@@ -179,35 +179,35 @@ github.com/vincent-petithory/dataurl v1.0.0/go.mod h1:FHafX5vmDzyP+1CQATJn7WFKc9
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mau.fi/libsignal v0.2.2 h1:QV+XdzQkm3x3aSG7FcqfGSZuFXz83pRZPBFaPygHbOU= go.mau.fi/libsignal v0.2.2 h1:QV+XdzQkm3x3aSG7FcqfGSZuFXz83pRZPBFaPygHbOU=
go.mau.fi/libsignal v0.2.2/go.mod h1:CRlIQg2J8uYTfDFvNoO8/KcZjs5cey0vbc6oj/bssY0= go.mau.fi/libsignal v0.2.2/go.mod h1:CRlIQg2J8uYTfDFvNoO8/KcZjs5cey0vbc6oj/bssY0=
go.mau.fi/util v0.9.10 h1:wzvz5iDHyqDXB8vgisD4d3SzucLXNM3iNY+1O1RoHtg= go.mau.fi/util v0.11.0 h1:JNEpkVRxfTdJUC0DIGKiRlLKzl4G/qLX/eVzoP7QuwY=
go.mau.fi/util v0.9.10/go.mod h1:YQOxySn+ZE3qSYqNxvyX7Yi3suA8YK17PS6QqBREW7A= go.mau.fi/util v0.11.0/go.mod h1:04AEFVsc4zNdIkDC1gkdqbg/nZFolHY50pyXh2DSy7s=
go.mau.fi/whatsmeow v0.0.0-20260630180629-b572e5bcb92b h1:ZUk1ErarDNpnbosXR/MeOz2gkqA4S1bh8zjaSRj7N+Y= go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f h1:UFm189GiALMSjhuywDHDQhRdhH6y8AD+eaGn5C75B1w=
go.mau.fi/whatsmeow v0.0.0-20260630180629-b572e5bcb92b/go.mod h1:9dmNTYZ/1pHjPw/bz+azBsGjAkcrZbqzMrKcvG5bJ8U= go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f/go.mod h1:iY4lm61nTLWsNiIE1EmHUZwhKGBeoV4dhnVE2uMtNoQ=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= 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 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8=
golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= 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-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.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20260611194520-c48552f49976 h1:X8Hz2ImujgbmetVuW+w2YkyZChE3cBpZi2P158rTG9M= golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A=
golang.org/x/exp v0.0.0-20260611194520-c48552f49976/go.mod h1:vnf4pv9iKZXY58sQE1L86zmNWJ4159e1RkcWiLCkeEY= golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ= golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= 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.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-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-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.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.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-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.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-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-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-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -215,8 +215,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-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.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/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -225,16 +225,16 @@ 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.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.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.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-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.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.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.46.0 h1:7jTurBkPZu4moS/Uy4OQT1M+QBlsj3wejyZwsT8Z7rk= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.46.0/go.mod h1:FrD85F8l+NWL+9XWBSyVSHO6Ne4jutsfIFba7AWQ5Ys= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 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.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 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 h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+5 -4
View File
@@ -3,6 +3,7 @@ package call_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -18,7 +19,7 @@ type CallService interface {
} }
type callService struct { type callService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -29,7 +30,7 @@ type RejectCallStruct struct {
} }
func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId] client := c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -43,7 +44,7 @@ func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId] client = c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -83,7 +84,7 @@ func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_mode
} }
func NewCallService( func NewCallService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) CallService { ) CallService {
+5 -4
View File
@@ -3,6 +3,7 @@ package chat_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -25,7 +26,7 @@ type ChatService interface {
} }
type chatService struct { type chatService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -40,7 +41,7 @@ type HistorySyncRequestStruct struct {
} }
func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId] client := c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -54,7 +55,7 @@ func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId] client = c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -244,7 +245,7 @@ func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instanc
} }
func NewChatService( func NewChatService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) ChatService { ) ChatService {
+5 -4
View File
@@ -3,6 +3,7 @@ package community_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -21,7 +22,7 @@ type CommunityService interface {
} }
type communityService struct { type communityService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -36,7 +37,7 @@ type AddParticipantStruct struct {
} }
func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId] client := c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -50,7 +51,7 @@ func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId] client = c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -157,7 +158,7 @@ func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance
} }
func NewCommunityService( func NewCommunityService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) CommunityService { ) CommunityService {
+10
View File
@@ -5,6 +5,7 @@ import (
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger" logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/gomessguii/logger" "github.com/gomessguii/logger"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"strings"
) )
type natsProducer struct { type natsProducer struct {
@@ -20,6 +21,15 @@ func NewNatsProducer(
natsGlobalEvents []string, natsGlobalEvents []string,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) producer_interfaces.Producer { ) producer_interfaces.Producer {
if strings.TrimSpace(url) == "" {
return &natsProducer{
conn: nil,
natsGlobalEnabled: false,
natsGlobalEvents: nil,
loggerWrapper: loggerWrapper,
}
}
conn, err := nats.Connect(url) conn, err := nats.Connect(url)
if err != nil { if err != nil {
logger.LogError("Failed to connect to NATS: %v", err) logger.LogError("Failed to connect to NATS: %v", err)
+31
View File
@@ -0,0 +1,31 @@
package nats_producer
import "testing"
func TestNewNatsProducerDoesNotConnectWithoutURL(t *testing.T) {
tests := []struct {
name string
url string
}{
{"Empty URL", ""},
{"Whitespace URL", " "},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
producer, ok := NewNatsProducer(tt.url, true, []string{"event1"}, nil).(*natsProducer)
if !ok {
t.Fatal("constructor returned an unexpected producer type")
}
if producer.conn != nil {
t.Fatal("NATS connection must stay nil when NATS_URL is empty")
}
if producer.natsGlobalEnabled {
t.Fatal("NATS global publishing must stay disabled without a URL")
}
if producer.natsGlobalEvents != nil {
t.Fatal("natsGlobalEvents must be nil when NATS_URL is empty")
}
})
}
}
+111 -58
View File
@@ -14,92 +14,131 @@ var upgrader = websocket.Upgrader{
ReadBufferSize: 1024, ReadBufferSize: 1024,
WriteBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
logger.LogInfo("Verificando origem da conexão WebSocket")
return true return true
}, },
} }
// client wraps a connection together with its own write mutex.
//
// gorilla/websocket permits only one concurrent writer per connection, and
// events are dispatched from independent goroutines (see the `go CallWebhook`
// calls in the whatsmeow event handler), so two events arriving at once used to
// race on the same socket. Serialising per connection removes that.
type client struct {
conn *websocket.Conn
mu sync.Mutex
}
func (c *client) writeJSON(v interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.conn.WriteJSON(v)
}
type websocketProducer struct { type websocketProducer struct {
clients map[string]*websocket.Conn // conexões específicas por instância // clients holds every connection subscribed to a given instance. This is a
broadcast []*websocket.Conn // conexões que recebem todos os eventos // slice, not a single connection: previously a second subscriber replaced the
// first, so opening the UI in two tabs silently cut delivery to the older one,
// and either tab disconnecting removed the whole instance entry.
clients map[string][]*client
broadcast []*client
clientsMux sync.RWMutex clientsMux sync.RWMutex
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer { func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {
return &websocketProducer{ return &websocketProducer{
clients: make(map[string]*websocket.Conn), clients: make(map[string][]*client),
broadcast: make([]*websocket.Conn, 0), broadcast: make([]*client, 0),
clientsMux: sync.RWMutex{},
loggerWrapper: loggerWrapper, loggerWrapper: loggerWrapper,
} }
} }
// ServeWs lida com as requisições de upgrade para websocket // ServeWs upgrades an HTTP request and registers it for the lifetime of the
// connection. An empty instanceId subscribes to every instance's events.
func ServeWs(w http.ResponseWriter, r *http.Request, instanceId string, producer *websocketProducer) { 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) conn, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err) logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)
return return
} }
logger.LogInfo("Conexão WebSocket estabelecida com sucesso") c := &client{conn: conn}
if instanceId == "" { if instanceId == "" {
producer.AddBroadcastClient(conn) producer.addBroadcastClient(c)
} else { } else {
producer.AddClient(instanceId, conn) producer.addClient(instanceId, c)
} }
// Goroutine para limpar conexão quando fechada // The read loop exists purely to notice a closed socket; inbound frames are
// ignored. Deregistration is keyed on this exact connection so sibling
// subscribers of the same instance keep receiving events.
go func() { go func() {
for { defer func() {
_, _, err := conn.ReadMessage()
if err != nil {
if instanceId == "" { if instanceId == "" {
producer.RemoveBroadcastClient(conn) producer.removeBroadcastClient(c)
} else { } else {
producer.RemoveClient(instanceId) producer.removeClient(instanceId, c)
} }
conn.Close() _ = conn.Close()
break }()
for {
if _, _, err := conn.ReadMessage(); err != nil {
return
} }
} }
}() }()
} }
func (p *websocketProducer) AddBroadcastClient(conn *websocket.Conn) { func (p *websocketProducer) addBroadcastClient(c *client) {
p.clientsMux.Lock() p.clientsMux.Lock()
defer p.clientsMux.Unlock() p.broadcast = append(p.broadcast, c)
p.broadcast = append(p.broadcast, conn) n := len(p.broadcast)
logger.LogInfo("Cliente broadcast websocket adicionado") p.clientsMux.Unlock()
logger.LogInfo("Cliente broadcast websocket adicionado (total: %d)", n)
} }
func (p *websocketProducer) RemoveBroadcastClient(conn *websocket.Conn) { func (p *websocketProducer) removeBroadcastClient(c *client) {
p.clientsMux.Lock() p.clientsMux.Lock()
defer p.clientsMux.Unlock() p.broadcast = drop(p.broadcast, c)
for i, c := range p.broadcast { n := len(p.broadcast)
if c == conn { p.clientsMux.Unlock()
p.broadcast = append(p.broadcast[:i], p.broadcast[i+1:]...) logger.LogInfo("Cliente broadcast websocket removido (total: %d)", n)
break
}
}
logger.LogInfo("Cliente broadcast websocket removido")
} }
func (p *websocketProducer) AddClient(instanceID string, conn *websocket.Conn) { func (p *websocketProducer) addClient(instanceID string, c *client) {
p.clientsMux.Lock() p.clientsMux.Lock()
defer p.clientsMux.Unlock() p.clients[instanceID] = append(p.clients[instanceID], c)
p.clients[instanceID] = conn n := len(p.clients[instanceID])
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket adicionado para instância: %s", instanceID) p.clientsMux.Unlock()
p.loggerWrapper.GetLogger(instanceID).LogInfo(
"Cliente websocket adicionado para instância: %s (total: %d)", instanceID, n)
} }
func (p *websocketProducer) RemoveClient(instanceID string) { func (p *websocketProducer) removeClient(instanceID string, c *client) {
p.clientsMux.Lock() p.clientsMux.Lock()
defer p.clientsMux.Unlock() remaining := drop(p.clients[instanceID], c)
if len(remaining) == 0 {
delete(p.clients, instanceID) delete(p.clients, instanceID)
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket removido para instância: %s", instanceID) } else {
p.clients[instanceID] = remaining
}
p.clientsMux.Unlock()
p.loggerWrapper.GetLogger(instanceID).LogInfo(
"Cliente websocket removido para instância: %s (restantes: %d)", instanceID, len(remaining))
}
// drop returns a new slice without target. It allocates rather than filtering in
// place, so a snapshot taken by a concurrent Produce can never observe a mutated
// backing array.
func drop(list []*client, target *client) []*client {
out := make([]*client, 0, len(list))
for _, c := range list {
if c != target {
out = append(out, c)
}
}
return out
} }
func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error { func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error {
@@ -108,29 +147,43 @@ func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID
"payload": string(payload), "payload": string(payload),
} }
// Snapshot under the lock, then write outside it: a slow or half-open socket
// must not block other instances' deliveries.
p.clientsMux.RLock() p.clientsMux.RLock()
defer p.clientsMux.RUnlock() targets := append([]*client(nil), p.clients[instanceID]...)
targets = append(targets, p.broadcast...)
p.clientsMux.RUnlock()
// Envia para cliente específico da instância var failed []*client
if client, exists := p.clients[instanceID]; exists { for _, c := range targets {
err := client.WriteJSON(message) if err := c.writeJSON(message); err != nil {
if err != nil { p.loggerWrapper.GetLogger(instanceID).LogError(
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem websocket para %s: %v", instanceID, err) "Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
// Não remove o cliente aqui pois estamos com o RLock failed = append(failed, c)
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
} }
} }
if len(failed) > 0 {
p.clientsMux.Lock()
for _, c := range failed {
if remaining := drop(p.clients[instanceID], c); len(remaining) == 0 {
delete(p.clients, instanceID)
} else {
p.clients[instanceID] = remaining
}
p.broadcast = drop(p.broadcast, c)
}
p.clientsMux.Unlock()
}
if n := len(targets) - len(failed); n > 0 {
p.loggerWrapper.GetLogger(instanceID).LogInfo(
"Mensagem websocket enviada para %d cliente(s) da instância %s na fila %s", n, instanceID, queueName)
}
// Deliberately nil even when a write failed. sendToQueueOrWebhook aborts the
// remaining producers on error, so reporting a dead browser tab here would
// silently suppress RabbitMQ/NATS/webhook delivery for the same event.
return nil return nil
} }
+5 -4
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"io" "io"
"net/http" "net/http"
"strings" "strings"
@@ -37,7 +38,7 @@ type GroupService interface {
} }
type groupService struct { type groupService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -117,7 +118,7 @@ type UpdateGroupRequestParticipantsStruct struct {
} }
func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := g.clientPointer[instanceId] client := g.clientPointer.Get(instanceId)
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -131,7 +132,7 @@ func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Clie
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = g.clientPointer[instanceId] client = g.clientPointer.Get(instanceId)
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -641,7 +642,7 @@ func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestPa
} }
func NewGroupService( func NewGroupService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) GroupService { ) GroupService {
+49 -55
View File
@@ -7,6 +7,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"os" "os"
"path/filepath" "path/filepath"
"slices" "slices"
@@ -50,8 +51,8 @@ type InstanceService interface {
type instances struct { type instances struct {
instanceRepository instance_repository.InstanceRepository instanceRepository instance_repository.InstanceRepository
config *config.Config config *config.Config
killChannel map[string](chan bool) killChannel *safemap.Map[chan bool]
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -124,7 +125,7 @@ type ForceReconnectStruct struct {
func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
logger := i.loggerWrapper.GetLogger(instanceId) logger := i.loggerWrapper.GetLogger(instanceId)
client := i.clientPointer[instanceId] client := i.clientPointer.Get(instanceId)
logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -138,7 +139,7 @@ func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client,
logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = i.clientPointer[instanceId] client = i.clientPointer.Get(instanceId)
logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -242,7 +243,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
} }
// Verifica se a instância já está rodando // Verifica se a instância já está rodando
isInstanceRunning := i.clientPointer[instance.Id] != nil isInstanceRunning := i.clientPointer.Get(instance.Id) != nil
// Sincroniza as configurações na instância em execução (se já estiver conectada) // Sincroniza as configurações na instância em execução (se já estiver conectada)
err = i.whatsmeowService.UpdateInstanceSettings(instance.Id) err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)
@@ -258,7 +259,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
if !isInstanceRunning { if !isInstanceRunning {
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)
i.killChannel[instance.Id] = make(chan bool) i.killChannel.Set(instance.Id, make(chan bool))
clientData := &whatsmeow_service.ClientData{ clientData := &whatsmeow_service.ClientData{
Instance: instance, Instance: instance,
@@ -288,8 +289,8 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
// logger.LogInfo("Waiting 1 seconds") // logger.LogInfo("Waiting 1 seconds")
// time.Sleep(1000 * time.Millisecond) // time.Sleep(1000 * time.Millisecond)
// if i.clientPointer[instance.Id] != nil { // if i.clientPointer.Get(instance.Id) != nil {
// if !i.clientPointer[instance.Id].IsConnected() { // if !i.clientPointer.Get(instance.Id).IsConnected() {
// return instance, "", "", fmt.Errorf("failed to connect") // return instance, "", "", fmt.Errorf("failed to connect")
// } // }
// } else { // } else {
@@ -317,12 +318,14 @@ func (i instances) Disconnect(instance *instance_model.Instance) (*instance_mode
if client.IsConnected() { if client.IsConnected() {
if client.IsLoggedIn() { if client.IsLoggedIn() {
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
i.killChannel[instance.Id] <- true safemap.TrySend(i.killChannel.Get(instance.Id), true)
instance.Events = "" // Do not clear instance.Events on disconnect (upstream PR #187): an
// empty events string makes CallWebhook drop every webhook after the
err := i.instanceRepository.Update(instance) // instance reconnects.
if err != nil { instance.Connected = false
instance.DisconnectReason = "Disconnected by API"
if err := i.instanceRepository.UpdateConnected(instance.Id, false, instance.DisconnectReason); err != nil {
return instance, err return instance, err
} }
@@ -352,13 +355,10 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
return instance, err return instance, err
} }
select { safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)
return instance, nil return instance, nil
@@ -367,13 +367,10 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
if client.IsConnected() { if client.IsConnected() {
client.Disconnect() client.Disconnect()
select { safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
return instance, nil return instance, nil
@@ -384,7 +381,7 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
} }
func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) { func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
if client == nil { if client == nil {
return &StatusStruct{ return &StatusStruct{
@@ -413,7 +410,7 @@ func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, err
func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) { func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {
logger := i.loggerWrapper.GetLogger(instance.Id) logger := i.loggerWrapper.GetLogger(instance.Id)
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
// Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente // 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() {
@@ -435,7 +432,7 @@ func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, erro
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
// Verificar novamente se há cliente // Verificar novamente se há cliente
client = i.clientPointer[instance.Id] client = i.clientPointer.Get(instance.Id)
if client != nil && client.IsLoggedIn() { if client != nil && client.IsLoggedIn() {
return nil, fmt.Errorf("session already logged in") return nil, fmt.Errorf("session already logged in")
} }
@@ -511,7 +508,7 @@ func buildPasskeyOpenURL(token string) string {
func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) { func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {
logger := i.loggerWrapper.GetLogger(instance.Id) logger := i.loggerWrapper.GetLogger(instance.Id)
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
if client == nil || !client.IsConnected() { if client == nil || !client.IsConnected() {
if client != nil && client.IsLoggedIn() { if client != nil && client.IsLoggedIn() {
@@ -525,7 +522,7 @@ func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*P
// Wait for the WA websocket connection and initial QR generation to establish. // Wait for the WA websocket connection and initial QR generation to establish.
// PairPhone must be called after the QR event is received per whatsmeow docs. // PairPhone must be called after the QR event is received per whatsmeow docs.
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
client = i.clientPointer[instance.Id] client = i.clientPointer.Get(instance.Id)
if client == nil { if client == nil {
return nil, fmt.Errorf("failed to initialize client for pairing") return nil, fmt.Errorf("failed to initialize client for pairing")
} }
@@ -551,7 +548,7 @@ func (i instances) GetAll() ([]*instance_model.Instance, error) {
} }
for _, instance := range instances { for _, instance := range instances {
if client := i.clientPointer[instance.Id]; client != nil { if client := i.clientPointer.Get(instance.Id); client != nil {
instance.Connected = client.IsLoggedIn() instance.Connected = client.IsLoggedIn()
} else { } else {
instance.Connected = false instance.Connected = false
@@ -570,7 +567,7 @@ func (i instances) Info(instanceId string) (*instance_model.Instance, error) {
} }
// Atualiza o status connected com base no estado real do cliente // Atualiza o status connected com base no estado real do cliente
if client := i.clientPointer[instance.Id]; client != nil { if client := i.clientPointer.Get(instance.Id); client != nil {
instance.Connected = client.IsLoggedIn() instance.Connected = client.IsLoggedIn()
} else { } else {
instance.Connected = false instance.Connected = false
@@ -587,18 +584,18 @@ func (i instances) Delete(id string) error {
return err return err
} }
if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() { if i.clientPointer.Get(instance.Id) != nil && i.clientPointer.Get(instance.Id).IsConnected() {
if i.clientPointer[instance.Id].IsLoggedIn() { if i.clientPointer.Get(instance.Id).IsLoggedIn() {
i.clientPointer[instance.Id].Logout(context.Background()) i.clientPointer.Get(instance.Id).Logout(context.Background())
} }
i.clientPointer[instance.Id].Disconnect() i.clientPointer.Get(instance.Id).Disconnect()
} }
// Limpar todos os recursos da instância antes de deletar // Limpar todos os recursos da instância antes de deletar
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
if i.killChannel[instance.Id] != nil { if i.killChannel.Get(instance.Id) != nil {
close(i.killChannel[instance.Id]) close(i.killChannel.Get(instance.Id))
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
} }
// Limpar cache via whatsmeow service // Limpar cache via whatsmeow service
@@ -697,7 +694,7 @@ func (i instances) RemoveProxy(id string) error {
} }
func (i instances) ForceReconnect(instanceId string, number string) error { func (i instances) ForceReconnect(instanceId string, number string) error {
if i.clientPointer[instanceId].IsConnected() && i.clientPointer[instanceId].IsLoggedIn() { if i.clientPointer.Get(instanceId).IsConnected() && i.clientPointer.Get(instanceId).IsLoggedIn() {
return fmt.Errorf("client already connected") return fmt.Errorf("client already connected")
} }
@@ -713,7 +710,7 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
subscribedEvents := strings.Split(instance.Events, ",") subscribedEvents := strings.Split(instance.Events, ",")
i.killChannel[instance.Id] = make(chan bool) i.killChannel.Set(instance.Id, make(chan bool))
clientData := &whatsmeow_service.ClientData{ clientData := &whatsmeow_service.ClientData{
Instance: instance, Instance: instance,
@@ -735,29 +732,26 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
} }
} }
if i.clientPointer[instance.Id] != nil { if i.clientPointer.Get(instance.Id) != nil {
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
client.Disconnect() client.Disconnect()
select { safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
} }
go i.whatsmeowService.StartClient(clientData) go i.whatsmeowService.StartClient(clientData)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
if i.clientPointer[instance.Id] != nil { if i.clientPointer.Get(instance.Id) != nil {
if !i.clientPointer[instance.Id].IsConnected() { if !i.clientPointer.Get(instance.Id).IsConnected() {
return fmt.Errorf("failed to connect") return fmt.Errorf("failed to connect")
} }
if !i.clientPointer[instance.Id].IsLoggedIn() { if !i.clientPointer.Get(instance.Id).IsLoggedIn() {
return fmt.Errorf("failed to login") return fmt.Errorf("failed to login")
} }
} else { } else {
@@ -912,8 +906,8 @@ func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_
func NewInstanceService( func NewInstanceService(
instanceRepository instance_repository.InstanceRepository, instanceRepository instance_repository.InstanceRepository,
killChannel map[string](chan bool), killChannel *safemap.Map[chan bool],
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
config *config.Config, config *config.Config,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+5 -4
View File
@@ -3,6 +3,7 @@ package label_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -25,7 +26,7 @@ type LabelService interface {
} }
type labelService struct { type labelService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
labelRepository label_repository.LabelRepository labelRepository label_repository.LabelRepository
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
@@ -50,7 +51,7 @@ type EditLabelStruct struct {
} }
func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := l.clientPointer[instanceId] client := l.clientPointer.Get(instanceId)
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -64,7 +65,7 @@ func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Clie
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = l.clientPointer[instanceId] client = l.clientPointer.Get(instanceId)
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -226,7 +227,7 @@ func (l *labelService) GetLabels(instance *instance_model.Instance) ([]label_mod
} }
func NewLabelService( func NewLabelService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
labelRepository label_repository.LabelRepository, labelRepository label_repository.LabelRepository,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+5 -4
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@@ -35,7 +36,7 @@ type MessageService interface {
} }
type messageService struct { type messageService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
messageRepository message_repository.MessageRepository messageRepository message_repository.MessageRepository
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
@@ -95,7 +96,7 @@ type MessageSendStruct struct {
} }
func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := m.clientPointer[instanceId] client := m.clientPointer.Get(instanceId)
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -109,7 +110,7 @@ func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Cl
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = m.clientPointer[instanceId] client = m.clientPointer.Get(instanceId)
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -526,7 +527,7 @@ func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance
} }
func NewMessageService( func NewMessageService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
messageRepository message_repository.MessageRepository, messageRepository message_repository.MessageRepository,
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+5 -4
View File
@@ -3,6 +3,7 @@ package newsletter_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -22,7 +23,7 @@ type NewsletterService interface {
} }
type newsletterService struct { type newsletterService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -47,7 +48,7 @@ type GetNewsletterMessagesStruct struct {
} }
func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := n.clientPointer[instanceId] client := n.clientPointer.Get(instanceId)
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -61,7 +62,7 @@ func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = n.clientPointer[instanceId] client = n.clientPointer.Get(instanceId)
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -195,7 +196,7 @@ func (n *newsletterService) GetNewsletterMessages(data *GetNewsletterMessagesStr
} }
func NewNewsletterService( func NewNewsletterService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) NewsletterService { ) NewsletterService {
+150
View File
@@ -0,0 +1,150 @@
// Package safemap holds the process-wide maps that are shared across goroutines.
//
// # WHY THIS EXISTS
//
// The three state maps of the process (clientPointer, myClientPointer and
// killChannel) are created once at startup and passed BY REFERENCE into eleven
// packages. Every one of them read and wrote those maps directly, from different
// goroutines, with no synchronisation at all.
//
// Go does not tolerate that. Concurrent writes do not corrupt silently: the
// runtime kills the process with
//
// fatal error: concurrent map writes
//
// and a fatal error is NOT recoverable — a deferred recover() does not catch it.
//
// Measured in production: a process died at StartClient while five instances
// were connecting at the same time. The container orchestrator brought it back
// within seconds, but every number was offline in the meantime, and it repeats
// on every restart that brings up more than a couple of instances at once.
//
// # WHY A SEPARATE PACKAGE, AND WHY GENERICS
//
// MyClient lives in pkg/whatsmeow/service. If the safe type lived there, the
// other ten packages would have to import that package and an import cycle
// would appear. This package has no internal dependencies — only the standard
// library — so anything can use it.
package safemap
import (
"sync"
"time"
)
// Map is a map[string]T guarded by a read/write mutex.
//
// Always use the pointer (*Map[T]): copying the struct would copy the mutex,
// and a copied mutex stops protecting the original — two owners, one lock each,
// and the race comes back silently.
type Map[T any] struct {
mu sync.RWMutex
m map[string]T
}
// New returns an empty map, ready to use.
func New[T any]() *Map[T] {
return &Map[T]{m: make(map[string]T)}
}
// Get returns the value, or the zero value of T when the key is absent —
// exactly like the m[k] it replaces, so swapping call sites changes no
// behaviour.
func (s *Map[T]) Get(k string) T {
s.mu.RLock()
defer s.mu.RUnlock()
return s.m[k]
}
// Lookup is the v, ok := m[k] form.
func (s *Map[T]) Lookup(k string) (T, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.m[k]
return v, ok
}
// Set is the m[k] = v form.
func (s *Map[T]) Set(k string, v T) {
s.mu.Lock()
defer s.mu.Unlock()
s.m[k] = v
}
// Delete is the delete(m, k) form.
func (s *Map[T]) Delete(k string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.m, k)
}
// Len is the len(m) form.
func (s *Map[T]) Len() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.m)
}
// Snapshot returns a copy for range loops.
//
// Ranging over the map from the inside would hold the lock for the whole loop,
// and the loop bodies here talk to WhatsApp — the lock would be held across
// network calls. The snapshot costs one copy of the pointers and releases the
// lock immediately.
func (s *Map[T]) Snapshot() map[string]T {
s.mu.RLock()
defer s.mu.RUnlock()
out := make(map[string]T, len(s.m))
for k, v := range s.m {
out[k] = v
}
return out
}
// TrySend delivers v on ch and reports whether it was delivered.
//
// The kill channels are closed when an instance is deleted, and a goroutine
// that still holds a reference (QR timeout, Disconnected handler) used to
// panic with "send on closed channel", taking the whole process down
// (upstream issue #222). A nil channel (instance already removed from the map)
// would block forever, so it is reported as not delivered instead.
func TrySend[T any](ch chan T, v T) (ok bool) {
if ch == nil {
return false
}
defer func() {
if recover() != nil {
ok = false
}
}()
ch <- v
return true
}
// TrySendTimeout is TrySend bounded by d. A d of zero makes it non-blocking.
func TrySendTimeout[T any](ch chan T, v T, d time.Duration) (ok bool) {
if ch == nil {
return false
}
defer func() {
if recover() != nil {
ok = false
}
}()
if d <= 0 {
select {
case ch <- v:
return true
default:
return false
}
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case ch <- v:
return true
case <-timer.C:
return false
}
}
+71
View File
@@ -0,0 +1,71 @@
package safemap
import (
"sync"
"testing"
)
// TestPlainMapRaces is the calibration test: it proves the detector can see the
// bug in the first place.
//
// It drives a plain Go map the way this code used to — N goroutines writing the
// same key. Under -race the detector flags it. Without -race the runtime kills
// the process with "fatal error: concurrent map writes", which is exactly the
// failure this package exists to prevent.
//
// Skipped by default precisely because that failure is not recoverable and
// would take the whole suite down. Run it on purpose to confirm the detector is
// not blind:
//
// go test -race -run TestPlainMapRaces ./pkg/safemap/
func TestPlainMapRaces(t *testing.T) {
t.Skip("calibration: run by hand — see the comment above")
m := map[string]int{}
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
m["key"] = n // <- the race
}(i)
}
wg.Wait()
}
// TestConcurrentAccess runs the same exercise through the guarded map: fifty
// goroutines writing, reading and ranging over the same key at once — the shape
// of a startup where several instances connect simultaneously.
func TestConcurrentAccess(t *testing.T) {
m := New[int]()
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(3)
go func(n int) { defer wg.Done(); m.Set("key", n) }(i)
go func() { defer wg.Done(); _ = m.Get("key") }()
go func() {
defer wg.Done()
_, _ = m.Lookup("key")
_ = m.Len()
for range m.Snapshot() {
}
}()
}
wg.Wait()
if _, ok := m.Lookup("key"); !ok {
t.Fatal("key should still be in the map")
}
}
// TestGetMissingKeyReturnsZero pins the behaviour the call sites relied on:
// m[k] on an absent key yields the zero value, and Get must do the same —
// otherwise swapping the call sites would have changed logic silently.
func TestGetMissingKeyReturnsZero(t *testing.T) {
if v := New[*int]().Get("absent"); v != nil {
t.Fatalf("want nil, got %v", v)
}
if n := New[int]().Get("absent"); n != 0 {
t.Fatalf("want 0, got %d", n)
}
}
+95 -15
View File
@@ -8,6 +8,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"image" "image"
"image/jpeg" "image/jpeg"
"image/png" "image/png"
@@ -53,7 +54,7 @@ type SendService interface {
} }
type sendService struct { type sendService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
config *config.Config config *config.Config
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
@@ -380,7 +381,7 @@ type MessageSendStruct struct {
} }
func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := s.clientPointer[instanceId] client := s.clientPointer.Get(instanceId)
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -394,7 +395,7 @@ func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = s.clientPointer[instanceId] client = s.clientPointer.Get(instanceId)
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -530,11 +531,30 @@ func (s *sendService) validateAndCheckUserExists(phone string, formatJid *bool,
return types.NewJID("", types.DefaultUserServer), fmt.Errorf("failed to connect client: %v", err) return types.NewJID("", types.DefaultUserServer), fmt.Errorf("failed to connect client: %v", err)
} }
// Brazilian mobiles: ask WhatsApp for both forms (with and without the 9th
// digit) and use the one that is registered.
if variants := utils.BRPhoneVariants(phone); len(variants) > 1 {
if remoteJID, found := s.checkBRPhoneVariants(client, variants, instance.Id); found {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s verified as valid WhatsApp user, using remoteJID: %s", instance.Id, phone, remoteJID)
formatJidFalse := false
return validateMessageFields(remoteJID, &formatJidFalse, messageID, participant)
}
}
// Use CheckUser approach: formatJid=false by default // Use CheckUser approach: formatJid=false by default
formatJidForCheck := false formatJidForCheck := false
// First attempt with formatJid=false // First attempt with formatJid=false
remoteJID, found, err := s.checkSingleUserExists(client, phone, formatJidForCheck, instance.Id) remoteJID, found, err := s.checkSingleUserExists(client, phone, formatJidForCheck, instance.Id)
if err != nil || !found {
// Integrations often store the contact's LID as if it were a phone
// number. If it is a LID this device already knows, send to it directly.
if lid, ok := s.knownLID(client, phone, instance.Id); ok {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s is a known LID, sending to %s", instance.Id, phone, lid)
formatJidFalse := false
return validateMessageFields(lid.String(), &formatJidFalse, messageID, participant)
}
}
if err != nil { if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to check user existence: %v", instance.Id, err) s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to check user existence: %v", instance.Id, err)
// Continue with sending even if check fails (network issues, etc.) // Continue with sending even if check fails (network issues, etc.)
@@ -591,6 +611,66 @@ func (s *sendService) checkSingleUserExists(client *whatsmeow.Client, phone stri
return remoteJID, true, nil return remoteJID, true, nil
} }
// knownLID reports whether phone is actually a LID with a phone number mapping
// in the local store, returning it as a @lid JID.
func (s *sendService) knownLID(client *whatsmeow.Client, phone string, instanceId string) (types.JID, bool) {
if client.Store == nil || client.Store.LIDs == nil {
return types.JID{}, false
}
user := utils.LIDCandidate(phone)
if user == "" {
return types.JID{}, false
}
lid := types.NewJID(user, types.HiddenUserServer)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
pn, err := client.Store.LIDs.GetPNForLID(ctx, lid)
if err != nil {
s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to look up LID %s: %v", instanceId, lid, err)
return types.JID{}, false
}
if pn.IsEmpty() {
return types.JID{}, false
}
return lid, true
}
// checkBRPhoneVariants queries every variant in a single IsOnWhatsApp call and
// returns the JID of the first one that is registered, in the given order.
// Errors are logged and reported as not found so the regular check still runs.
func (s *sendService) checkBRPhoneVariants(client *whatsmeow.Client, variants []string, instanceId string) (string, bool) {
phones := make([]string, len(variants))
for i, v := range variants {
phones[i] = "+" + v
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
resp, err := client.IsOnWhatsApp(ctx, phones)
if err != nil {
s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to check BR number variants %v: %v", instanceId, variants, err)
return "", false
}
for _, v := range variants {
for _, r := range resp {
if r.IsIn && strings.TrimPrefix(r.Query, "+") == v {
return r.JID.String(), true
}
}
}
// Query not echoed back as sent: any registered result is one of our variants.
for _, r := range resp {
if r.IsIn {
return r.JID.String(), true
}
}
return "", false
}
func findURL(text string) string { func findURL(text string) string {
urlRegex := `http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+` urlRegex := `http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+`
re := regexp.MustCompile(urlRegex) re := regexp.MustCompile(urlRegex)
@@ -2360,7 +2440,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
var message string var message string
if data.Id == "" { if data.Id == "" {
message = s.clientPointer[instance.Id].GenerateMessageID() message = s.clientPointer.Get(instance.Id).GenerateMessageID()
} else { } else {
message = data.Id message = data.Id
} }
@@ -2371,14 +2451,14 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
media = "audio" media = "audio"
} }
err := s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(media)) err := s.clientPointer.Get(instance.Id).SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(media))
if err != nil { if err != nil {
return nil, err return nil, err
} }
time.Sleep(time.Duration(data.Delay) * time.Millisecond) time.Sleep(time.Duration(data.Delay) * time.Millisecond)
err = s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(media)) err = s.clientPointer.Get(instance.Id).SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(media))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -2631,7 +2711,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
// Only try to get participants for actual groups, not newsletters // Only try to get participants for actual groups, not newsletters
if isGroup && !isNewsletter { if isGroup && !isNewsletter {
if data.MentionAll { if data.MentionAll {
groupInfo, err := s.clientPointer[instance.Id].GetGroupInfo(context.Background(), recipient) groupInfo, err := s.clientPointer.Get(instance.Id).GetGroupInfo(context.Background(), recipient)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -2770,7 +2850,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
sendExtra.AdditionalNodes = data.AdditionalNodes sendExtra.AdditionalNodes = data.AdditionalNodes
} }
response, err := s.clientPointer[instance.Id].SendMessage(context.Background(), recipient, msg, sendExtra) response, err := s.clientPointer.Get(instance.Id).SendMessage(context.Background(), recipient, msg, sendExtra)
if err != nil { if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending message: %v", instance.Id, err) s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending message: %v", instance.Id, err)
return nil, err return nil, err
@@ -2781,7 +2861,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
messageInfo := types.MessageInfo{ messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{ MessageSource: types.MessageSource{
Chat: recipient, Chat: recipient,
Sender: *s.clientPointer[instance.Id].Store.ID, Sender: *s.clientPointer.Get(instance.Id).Store.ID,
IsFromMe: true, IsFromMe: true,
IsGroup: isGroup, IsGroup: isGroup,
}, },
@@ -2835,15 +2915,15 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
sticker := msg.GetStickerMessage() sticker := msg.GetStickerMessage()
if img != nil { if img != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), img) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), img)
} else if audio != nil { } else if audio != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), audio) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), audio)
} else if document != nil { } else if document != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), document) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), document)
} else if video != nil { } else if video != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), video) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), video)
} else if sticker != nil { } else if sticker != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), sticker) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), sticker)
webpReader := bytes.NewReader(data) webpReader := bytes.NewReader(data)
img, err := webp.Decode(webpReader) img, err := webp.Decode(webpReader)
@@ -3366,7 +3446,7 @@ func (s *sendService) sendStatusWebhook(messageSent *MessageSendStruct, instance
} }
func NewSendService( func NewSendService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
config *config.Config, config *config.Config,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+4 -2
View File
@@ -7,15 +7,17 @@ type ServerHandler interface {
} }
type serverHandler struct { type serverHandler struct {
version string
} }
// ServerOk implements ServerHandler. // ServerOk implements ServerHandler.
func (s *serverHandler) ServerOk(ctx *gin.Context) { func (s *serverHandler) ServerOk(ctx *gin.Context) {
ctx.JSON(200, gin.H{ ctx.JSON(200, gin.H{
"status": "ok", "status": "ok",
"version": s.version,
}) })
} }
func NewServerHandler() ServerHandler { func NewServerHandler(version string) ServerHandler {
return &serverHandler{} return &serverHandler{version: version}
} }
+11 -8
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"io" "io"
"net/http" "net/http"
"time" "time"
@@ -33,7 +34,7 @@ type UserService interface {
} }
type userService struct { type userService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -109,7 +110,7 @@ type PrivacyStruct struct {
} }
func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := u.clientPointer[instanceId] client := u.clientPointer.Get(instanceId)
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -123,7 +124,7 @@ func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = u.clientPointer[instanceId] client = u.clientPointer.Get(instanceId)
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -444,7 +445,7 @@ func (u *userService) BlockContact(data *BlockStruct, instance *instance_model.I
return nil, errors.New("invalid phone number") return nil, errors.New("invalid phone number")
} }
resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionBlock) resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionBlock, "")
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -463,7 +464,7 @@ func (u *userService) UnlockContact(data *BlockStruct, instance *instance_model.
return nil, errors.New("invalid phone number") return nil, errors.New("invalid phone number")
} }
resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionUnblock) resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionUnblock, "")
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -477,7 +478,7 @@ func (u *userService) GetBlockList(instance *instance_model.Instance) (*types.Bl
return nil, err return nil, err
} }
resp, err := client.GetBlocklist(context.Background()) resp, err := client.GetBlocklist(context.Background(), "")
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -532,7 +533,9 @@ func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *i
return false, err return false, err
} }
err = client.SetStatusMessage(context.Background(), data.Status) err = client.SetStatusMessage(context.Background(), types.SetStatusInput{
Text: &data.Status,
})
if err != nil { if err != nil {
return false, err return false, err
} }
@@ -541,7 +544,7 @@ func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *i
} }
func NewUserService( func NewUserService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) UserService { ) UserService {
+72
View File
@@ -187,6 +187,71 @@ func formatBRNumber(jid string) string {
return jid return jid
} }
// BRPhoneVariants returns both forms of a Brazilian mobile number — with and
// without the 9th digit — with the received form first, or nil when the number
// is not a Brazilian mobile.
//
// Accounts created before the 9th digit rollout are still registered without
// it (e.g. 554291389691), newer ones with it (5542991389691). No fixed rule
// derived from the DDD is right for every account, so callers should ask
// WhatsApp which of the two exists.
func BRPhoneVariants(number string) []string {
if strings.Contains(number, "@") {
if !strings.HasSuffix(number, "@"+whatsmeow_types.DefaultUserServer) {
return nil
}
number = strings.Split(number, "@")[0]
}
number = strings.Split(number, ":")[0]
digits := strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return r
}
return -1
}, number)
// 55 + DDD (11-99, never starting with 0) + subscriber
if !strings.HasPrefix(digits, "55") || len(digits) < 12 || digits[2] == '0' {
return nil
}
switch len(digits) {
case 13:
if digits[4] == '9' {
return []string{digits, digits[:4] + digits[5:]}
}
case 12:
// 8-digit mobile numbers start with 6, 7, 8 or 9; landlines with 2-5
if digits[4] >= '6' {
return []string{digits, digits[:4] + "9" + digits[4:]}
}
}
return nil
}
// LIDCandidate returns the user part of number when it could be a LID sent as
// a phone number ("255284433936406", "[email protected]"), or ""
// when it has another server, a device suffix or non-digit characters.
func LIDCandidate(number string) string {
if strings.Contains(number, "@") {
if !strings.HasSuffix(number, "@"+whatsmeow_types.DefaultUserServer) {
return ""
}
number = strings.Split(number, "@")[0]
}
number = strings.TrimPrefix(strings.TrimSpace(number), "+")
if len(number) < 8 {
return ""
}
for _, r := range number {
if r < '0' || r > '9' {
return ""
}
}
return number
}
// ParseJID parses a number string into a WhatsApp JID with validation // ParseJID parses a number string into a WhatsApp JID with validation
func ParseJID(arg string) (whatsmeow_types.JID, bool) { func ParseJID(arg string) (whatsmeow_types.JID, bool) {
if arg == "" { if arg == "" {
@@ -207,6 +272,13 @@ func ParseJID(arg string) (whatsmeow_types.JID, bool) {
return recipient, false return recipient, false
} }
// CreateJID keeps the "+" prefix for IsOnWhatsApp, but it is not part of a
// user JID. WhatsApp does not answer queries addressed to "+<number>", so
// they hang until the IQ timeout (upstream #223 / PR #224).
if recipient.Server == whatsmeow_types.DefaultUserServer {
recipient.User = strings.TrimPrefix(recipient.User, "+")
}
if recipient.User == "" && !strings.Contains(jidString, "@broadcast") { if recipient.User == "" && !strings.Contains(jidString, "@broadcast") {
logger.LogError("Invalid JID. No user specified: %s", jidString) logger.LogError("Invalid JID. No user specified: %s", jidString)
return recipient, false return recipient, false
+53 -2
View File
@@ -284,13 +284,13 @@ func TestParseJID(t *testing.T) {
name: "Valid phone number", name: "Valid phone number",
input: "15551234567", input: "15551234567",
expectOk: true, expectOk: true,
expectJID: "+[email protected]", expectJID: "[email protected]",
}, },
{ {
name: "Valid BR number", name: "Valid BR number",
input: "5531987654321", input: "5531987654321",
expectOk: true, expectOk: true,
expectJID: "+[email protected]", expectJID: "[email protected]",
}, },
{ {
name: "Valid group ID", name: "Valid group ID",
@@ -384,3 +384,54 @@ func TestCanonicalJID(t *testing.T) {
}) })
} }
} }
func TestBRPhoneVariants(t *testing.T) {
tests := []struct {
name string
input string
want []string
}{
{"13 digits with 9", "5542991389691", []string{"5542991389691", "554291389691"}},
{"12 digits without 9", "554291389691", []string{"554291389691", "5542991389691"}},
{"plus and JID suffix", "[email protected]", []string{"5511987654321", "551187654321"}},
{"formatted", "+55 (42) 99138-9691", []string{"5542991389691", "554291389691"}},
{"landline", "554232221234", nil},
{"not Brazil", "15551234567", nil},
{"group", "[email protected]", nil},
{"lid", "255284433936406@lid", nil},
{"13 digits without 9 after DDD", "5542891389691", nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := BRPhoneVariants(tt.input)
if len(got) != len(tt.want) {
t.Fatalf("BRPhoneVariants(%q) = %v, want %v", tt.input, got, tt.want)
}
for i := range got {
if got[i] != tt.want[i] {
t.Fatalf("BRPhoneVariants(%q) = %v, want %v", tt.input, got, tt.want)
}
}
})
}
}
func TestLIDCandidate(t *testing.T) {
tests := []struct {
input string
want string
}{
{"255284433936406", "255284433936406"},
{"[email protected]", "255284433936406"},
{"255284433936406@lid", ""},
{"[email protected]", ""},
{"255284433936406:[email protected]", ""},
{"+55 (42) 99138-9691", ""},
{"1234", ""},
}
for _, tt := range tests {
if got := LIDCandidate(tt.input); got != tt.want {
t.Errorf("LIDCandidate(%q) = %q, want %q", tt.input, got, tt.want)
}
}
}
+299 -73
View File
@@ -7,6 +7,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"image/png" "image/png"
"io" "io"
"math/rand" "math/rand"
@@ -28,6 +29,7 @@ import (
"go.mau.fi/whatsmeow/appstate" "go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/proto/waCompanionReg" "go.mau.fi/whatsmeow/proto/waCompanionReg"
"go.mau.fi/whatsmeow/proto/waE2E" "go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/proto/waWa6"
"go.mau.fi/whatsmeow/store" "go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore" "go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types" "go.mau.fi/whatsmeow/types"
@@ -83,10 +85,10 @@ type whatsmeowService struct {
labelRepository label_repository.LabelRepository labelRepository label_repository.LabelRepository
pollService poll_service.PollService // NOVO: Serviço de enquetes pollService poll_service.PollService // NOVO: Serviço de enquetes
config *config.Config config *config.Config
killChannel map[string](chan bool) killChannel *safemap.Map[chan bool]
userInfoCache *cache.Cache userInfoCache *cache.Cache
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
myClientPointer map[string]*MyClient myClientPointer *safemap.Map[*MyClient]
rabbitmqProducer producer_interfaces.Producer rabbitmqProducer producer_interfaces.Producer
webhookProducer producer_interfaces.Producer webhookProducer producer_interfaces.Producer
websocketProducer producer_interfaces.Producer websocketProducer producer_interfaces.Producer
@@ -97,8 +99,18 @@ type whatsmeowService struct {
natsProducer producer_interfaces.Producer natsProducer producer_interfaces.Producer
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
passkeyCeremony *ceremony.Store passkeyCeremony *ceremony.Store
// authStore is heap-allocated so sync.Once works with value-receiver methods like StartClient.
authStore *sharedSQLStore
} }
// sharedSQLStore holds the process-wide whatsmeow sqlstore.Container for PostgresAuthDB
// (or the sqlite fallback). One Upgrade per process; never Close on instance disconnect.
type sharedSQLStore struct {
once sync.Once
container *sqlstore.Container
err error
sqliteDB *sql.DB // kept alive when not using PostgresAuthDB
}
type MyClient struct { type MyClient struct {
service WhatsmeowService service WhatsmeowService
WAClient *whatsmeow.Client WAClient *whatsmeow.Client
@@ -115,9 +127,9 @@ type MyClient struct {
messageRepository message_repository.MessageRepository messageRepository message_repository.MessageRepository
labelRepository label_repository.LabelRepository labelRepository label_repository.LabelRepository
pollService poll_service.PollService // NOVO: Serviço de enquetes pollService poll_service.PollService // NOVO: Serviço de enquetes
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
myClientPointer map[string]*MyClient myClientPointer *safemap.Map[*MyClient]
killChannel map[string](chan bool) killChannel *safemap.Map[chan bool]
userInfoCache *cache.Cache userInfoCache *cache.Cache
config *config.Config config *config.Config
historySyncID int32 historySyncID int32
@@ -171,11 +183,22 @@ type ProxyConfig struct {
Username string `json:"username"` Username string `json:"username"`
} }
// reconnectsInProgress holds the instance IDs with a ReconnectClient running. Two Disconnected events for
// the same instance in the same second used to run two reconnects concurrently and dereference a client the
// other one had just removed, killing the whole process (upstream issue #188).
var reconnectsInProgress sync.Map
func (w whatsmeowService) ReconnectClient(instanceId string) error { func (w whatsmeowService) ReconnectClient(instanceId string) error {
if _, running := reconnectsInProgress.LoadOrStore(instanceId, struct{}{}); running {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Reconnection already in progress, skipping duplicate request", instanceId)
return nil
}
defer reconnectsInProgress.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId)
// Passo 1: Limpar conexão existente se houver // Passo 1: Limpar conexão existente se houver
if client, exists := w.clientPointer[instanceId]; exists { if client, exists := w.clientPointer.Lookup(instanceId); exists && client != nil {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)
// Desconectar o cliente WebSocket // Desconectar o cliente WebSocket
@@ -185,7 +208,7 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
} }
// Remover event handler se existir // Remover event handler se existir
if mycli, ok := w.myClientPointer[instanceId]; ok { if mycli, ok := w.myClientPointer.Lookup(instanceId); ok {
if mycli.eventHandlerID != 0 { if mycli.eventHandlerID != 0 {
client.RemoveEventHandler(mycli.eventHandlerID) client.RemoveEventHandler(mycli.eventHandlerID)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Event handler removed", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Event handler removed", instanceId)
@@ -197,19 +220,16 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Cleaning up resources", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Cleaning up resources", instanceId)
// Enviar sinal de kill se o canal existir // Enviar sinal de kill se o canal existir
if killChan, exists := w.killChannel[instanceId]; exists { if killChan, exists := w.killChannel.Lookup(instanceId); exists {
select { if safemap.TrySendTimeout(killChan, true, 0) {
case killChan <- true:
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId)
default:
// Canal pode estar bloqueado, continua
} }
} }
// Remover das estruturas // Remover das estruturas
delete(w.clientPointer, instanceId) w.clientPointer.Delete(instanceId)
delete(w.myClientPointer, instanceId) w.myClientPointer.Delete(instanceId)
delete(w.killChannel, instanceId) w.killChannel.Delete(instanceId)
// Limpar cache de userInfo para esta instância // Limpar cache de userInfo para esta instância
if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil { if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil {
@@ -301,38 +321,181 @@ func (w whatsmeowService) ForceUpdateJid(instanceId string, number string) error
return nil return nil
} }
// getSharedSQLStoreContainer returns the process-wide whatsmeow sqlstore.Container.
// PostgresAuthDB reuses the pooled authDB from initPostgresAuthDB (Upgrade once).
// The Users/GORM database is intentionally separate and never passed here.
func (w whatsmeowService) getSharedSQLStoreContainer() (*sqlstore.Container, error) {
if w.authStore == nil {
return nil, fmt.Errorf("shared sqlstore not initialized")
}
w.authStore.once.Do(func() {
var dbLog waLog.Logger
if w.config.WaDebug != "" {
dbLog = waLog.Stdout("Database", w.config.WaDebug, true)
}
ctx := context.Background()
if w.config.PostgresAuthDB != "" {
if w.authDB == nil {
w.authStore.err = fmt.Errorf("postgres auth DB handle is nil")
return
}
container := sqlstore.NewWithDB(w.authDB, "postgres", dbLog)
if err := container.Upgrade(ctx); err != nil {
// Do not Close authDB — owned by main.
w.authStore.err = fmt.Errorf("failed to upgrade database: %w", err)
return
}
w.authStore.container = container
return
}
dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath)
db, err := sql.Open("sqlite", dsn)
if err != nil {
w.authStore.err = fmt.Errorf("failed to open sqlite auth store: %w", err)
return
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
db.SetConnMaxIdleTime(1 * time.Minute)
container := sqlstore.NewWithDB(db, "sqlite", dbLog)
if err := container.Upgrade(ctx); err != nil {
_ = db.Close()
w.authStore.err = fmt.Errorf("failed to upgrade database: %w", err)
return
}
w.authStore.sqliteDB = db
w.authStore.container = container
})
return w.authStore.container, w.authStore.err
}
// ============================================================================
// Backoff for the reconnect loop.
//
// THE LOOP: an instance whose device was logged out from the phone spins
// forever. Disconnected -> ReconnectClient -> the instance comes up with no
// session -> emits a QR -> nobody scans -> max QR count -> forced logout ->
// Disconnected again. Measured in production: 110 reconnects and 1135 QR codes
// in 50 minutes from a single instance, and it only stopped when a human looked.
//
// Nothing in the current code counts those restarts, because from
// ReconnectClient's point of view every turn SUCCEEDS — the instance really does
// come up. What fails afterwards is the pairing, which nobody was measuring.
//
// THE SHAPE: the first reconnectFreeAttempts restarts inside the window go
// straight through — that is the good case, a healthy instance that lost its
// websocket and must come back within seconds. Past that the loop turns into a
// growing wait, and the instance keeps trying: this is a backoff, not a
// give-up. An instance with a valid session still heals on its own; what is
// lost is the hammering.
//
// NOTE: only one goroutine waits per instance (the scheduled flag). Without it
// every Disconnected arriving during the wait would stack another one, and the
// backoff would become the very loop it was written to stop.
// ============================================================================
const (
reconnectWindow = 15 * time.Minute // restarts inside this window count together
reconnectFreeAttempts = 5 // how many go through with no wait
)
// The ladder of waits. The last step repeats indefinitely.
var reconnectBackoff = []time.Duration{5 * time.Minute, 15 * time.Minute, 30 * time.Minute}
type reconnectState struct {
restarts int
since time.Time
step int
scheduled bool
}
var (
reconnectMu sync.Mutex
reconnectTrack = map[string]*reconnectState{}
)
// reconnectAllowed reports whether this instance may restart right now.
//
// (true, 0) — go ahead, normal path
// (false, d) — wait d and then try; this goroutine owns the wait
// (false, -1) — another goroutine is already waiting for this instance; give up
func reconnectAllowed(instanceID string) (bool, time.Duration) {
reconnectMu.Lock()
defer reconnectMu.Unlock()
now := time.Now()
st := reconnectTrack[instanceID]
if st == nil || now.Sub(st.since) > reconnectWindow {
reconnectTrack[instanceID] = &reconnectState{restarts: 1, since: now}
return true, 0
}
if st.scheduled {
return false, -1
}
st.restarts++
if st.restarts <= reconnectFreeAttempts {
return true, 0
}
d := reconnectBackoff[len(reconnectBackoff)-1]
if st.step < len(reconnectBackoff) {
d = reconnectBackoff[st.step]
st.step++
}
st.scheduled = true
return false, d
}
// reconnectWaitDone puts the instance back in line once its wait is over.
func reconnectWaitDone(instanceID string) {
reconnectMu.Lock()
if st := reconnectTrack[instanceID]; st != nil {
st.scheduled = false
}
reconnectMu.Unlock()
}
// reconnectSucceeded clears the state — called when the instance actually
// connects. Without it the backoff would inherit the count of a problem that is
// already solved.
func reconnectSucceeded(instanceID string) {
reconnectMu.Lock()
delete(reconnectTrack, instanceID)
reconnectMu.Unlock()
}
// clientsStarting holds the instance IDs whose StartClient is between entry and registering the new client in
// clientPointer. Without it, a second StartClient in that window (e.g. GET /instance/qr right after
// POST /instance/connect, which starts the client in a goroutine) sees no client and starts another one
// (upstream PR #239).
var clientsStarting sync.Map
func (w whatsmeowService) StartClient(cd *ClientData) { func (w whatsmeowService) StartClient(cd *ClientData) {
if _, starting := clientsStarting.LoadOrStore(cd.Instance.Id, struct{}{}); starting {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Client start already in progress, skipping duplicate start", cd.Instance.Id)
return
}
registered := false
defer func() {
if !registered {
clientsStarting.Delete(cd.Instance.Id)
}
}()
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id)
var deviceStore *store.Device var deviceStore *store.Device
var err error var err error
if w.clientPointer[cd.Instance.Id] != nil { if w.clientPointer.Get(cd.Instance.Id) != nil {
if w.clientPointer[cd.Instance.Id].IsConnected() { if w.clientPointer.Get(cd.Instance.Id).IsConnected() {
return return
} }
} }
var container *sqlstore.Container container, err := w.getSharedSQLStoreContainer()
if w.config.WaDebug != "" {
dbLog := waLog.Stdout("Database", w.config.WaDebug, true)
if w.config.PostgresAuthDB != "" {
container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, dbLog)
} else {
dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath)
container, err = sqlstore.New(context.Background(), "sqlite", dsn, dbLog)
}
} else {
if w.config.PostgresAuthDB != "" {
container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, nil)
} else {
dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath)
container, err = sqlstore.New(context.Background(), "sqlite", dsn, nil)
}
}
if err != nil { if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to create container: %v", cd.Instance.Id, err) w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to create container: %v", cd.Instance.Id, err)
return return
@@ -376,19 +539,10 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
store.DeviceProps.RequireFullSync = proto.Bool(true) store.DeviceProps.RequireFullSync = proto.Bool(true)
if w.config.WhatsappVersionMajor != 0 && w.config.WhatsappVersionMinor != 0 && w.config.WhatsappVersionPatch != 0 { if w.config.WhatsappVersionMajor != 0 && w.config.WhatsappVersionMinor != 0 && w.config.WhatsappVersionPatch != 0 {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version to %d.%d.%d", cd.Instance.Id, w.config.WhatsappVersionMajor, w.config.WhatsappVersionMinor, w.config.WhatsappVersionPatch) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version from config to %d.%d.%d", cd.Instance.Id, w.config.WhatsappVersionMajor, w.config.WhatsappVersionMinor, w.config.WhatsappVersionPatch)
version.Major = w.config.WhatsappVersionMajor version.Major = w.config.WhatsappVersionMajor
if err == nil {
store.DeviceProps.Version.Primary = proto.Uint32(uint32(version.Major))
}
version.Minor = w.config.WhatsappVersionMinor version.Minor = w.config.WhatsappVersionMinor
if err == nil {
store.DeviceProps.Version.Secondary = proto.Uint32(uint32(version.Minor))
}
version.Patch = w.config.WhatsappVersionPatch version.Patch = w.config.WhatsappVersionPatch
if err == nil {
store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(version.Patch))
}
} else { } else {
// Try to fetch version from WhatsApp Web // Try to fetch version from WhatsApp Web
webVersion, err := fetchWhatsAppWebVersion() webVersion, err := fetchWhatsAppWebVersion()
@@ -397,11 +551,24 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
} else { } else {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version from web to %d.%d.%d", cd.Instance.Id, webVersion.Major, webVersion.Minor, webVersion.Patch) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version from web to %d.%d.%d", cd.Instance.Id, webVersion.Major, webVersion.Minor, webVersion.Patch)
version = *webVersion version = *webVersion
}
}
if version.Major != 0 && version.Minor != 0 && version.Patch != 0 {
store.DeviceProps.Version.Primary = proto.Uint32(uint32(version.Major)) store.DeviceProps.Version.Primary = proto.Uint32(uint32(version.Major))
store.DeviceProps.Version.Secondary = proto.Uint32(uint32(version.Minor)) store.DeviceProps.Version.Secondary = proto.Uint32(uint32(version.Minor))
store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(version.Patch)) store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(version.Patch))
waVer := store.WAVersionContainer{uint32(version.Major), uint32(version.Minor), uint32(version.Patch)}
store.SetWAVersion(waVer)
if store.BaseClientPayload != nil && store.BaseClientPayload.UserAgent != nil {
store.BaseClientPayload.UserAgent.AppVersion = &waWa6.ClientPayload_UserAgent_AppVersion{
Primary: proto.Uint32(uint32(version.Major)),
Secondary: proto.Uint32(uint32(version.Minor)),
Tertiary: proto.Uint32(uint32(version.Patch)),
} }
} }
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Applied WhatsApp handshake version %d.%d.%d", cd.Instance.Id, version.Major, version.Minor, version.Patch)
}
// 🔒 FIX: Sempre criar logger, mesmo que WaDebug esteja vazio // 🔒 FIX: Sempre criar logger, mesmo que WaDebug esteja vazio
// Usar "INFO" como nível mínimo para garantir que logs importantes apareçam // Usar "INFO" como nível mínimo para garantir que logs importantes apareçam
@@ -412,7 +579,10 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
clientLog := waLog.Stdout("Client", minLevel, true) clientLog := waLog.Stdout("Client", minLevel, true)
client := whatsmeow.NewClient(deviceStore, clientLog) client := whatsmeow.NewClient(deviceStore, clientLog)
w.clientPointer[cd.Instance.Id] = client w.clientPointer.Set(cd.Instance.Id, client)
// Registered: later callers see this client, and the restart below (which re-enters StartClient) must not be blocked.
clientsStarting.Delete(cd.Instance.Id)
registered = true
if cd.IsProxy { if cd.IsProxy {
var proxyConfig ProxyConfig var proxyConfig ProxyConfig
@@ -500,7 +670,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler) mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler)
// Armazena o MyClient no map para permitir atualizações posteriores // Armazena o MyClient no map para permitir atualizações posteriores
w.myClientPointer[cd.Instance.Id] = mycli w.myClientPointer.Set(cd.Instance.Id, mycli)
if client.Store.ID != nil { if client.Store.ID != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Already logged in with JID: %s", cd.Instance.Id, client.Store.ID.String()) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Already logged in with JID: %s", cd.Instance.Id, client.Store.ID.String())
@@ -574,12 +744,12 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
for { for {
select { select {
case <-w.killChannel[cd.Instance.Id]: case <-w.killChannel.Get(cd.Instance.Id):
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Received kill signal for user '%s'", cd.Instance.Id) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Received kill signal for user '%s'", cd.Instance.Id)
client.Disconnect() client.Disconnect()
delete(w.clientPointer, cd.Instance.Id) w.clientPointer.Delete(cd.Instance.Id)
delete(w.myClientPointer, cd.Instance.Id) w.myClientPointer.Delete(cd.Instance.Id)
// Limpar cache de userInfo para esta instância // Limpar cache de userInfo para esta instância
w.userInfoCache.Delete(cd.Instance.Token) w.userInfoCache.Delete(cd.Instance.Token)
@@ -624,6 +794,14 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID) go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)
} }
// Without a paired device (QR timed out, logged out, or the phone removed this device) a restart would
// only create a new device and cycle QR codes forever. Stop here; the next /instance/connect or
// /instance/qr starts a fresh client (upstream PR #240).
if client.Store.ID == nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] No paired device; not restarting client", cd.Instance.Id)
return
}
// restart client // restart client
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id)
w.StartClient(cd) w.StartClient(cd)
@@ -654,7 +832,7 @@ func schedulePresenceUpdates(mycli *MyClient) {
randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour
ticker = time.NewTicker(randomInterval) ticker = time.NewTicker(randomInterval)
case <-mycli.killChannel[mycli.userID]: case <-mycli.killChannel.Get(mycli.userID):
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received kill signal, stopping presence updates", mycli.userID) mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received kill signal, stopping presence updates", mycli.userID)
return // Encerra a goroutine quando receber sinal de kill return // Encerra a goroutine quando receber sinal de kill
} }
@@ -848,8 +1026,10 @@ func (mycli *MyClient) teardownQR(reason string, forceLogout bool) {
// maps (it is the single writer for this instance). Blocking send mirrors // maps (it is the single writer for this instance). Blocking send mirrors
// the original timeout branch so the signal is never dropped. // the original timeout branch so the signal is never dropped.
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID) mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID)
if killChan, exists := mycli.killChannel[instanceID]; exists { if killChan, exists := mycli.killChannel.Lookup(instanceID); exists {
killChan <- true if !safemap.TrySend(killChan, true) {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] Kill channel already closed (instance deleted)", instanceID)
}
} }
} }
@@ -875,6 +1055,9 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
} }
} }
case *events.Connected, *events.PushNameSetting: case *events.Connected, *events.PushNameSetting:
// A real connection ends the loop, so the backoff counter dies here.
// Without this, a drop tomorrow would inherit today's restarts.
reconnectSucceeded(mycli.userID)
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] events.Connected to Whatsapp for user '%s'", mycli.userID, mycli.WAClient.Store.PushName) mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] events.Connected to Whatsapp for user '%s'", mycli.userID, mycli.WAClient.Store.PushName)
if len(mycli.WAClient.Store.PushName) > 0 { if len(mycli.WAClient.Store.PushName) > 0 {
doWebhook = true doWebhook = true
@@ -907,7 +1090,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
// jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User) // jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User)
// if ok { // if ok {
// profilePicUrl, err := mycli.clientPointer[mycli.userID].GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{ // profilePicUrl, err := mycli.clientPointer.Get(mycli.userID).GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
// Preview: false, // Preview: false,
// }) // })
// if err != nil { // if err != nil {
@@ -1277,7 +1460,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
fmt.Printf("[POLL DEBUG] ✅ mycli.WAClient is initialized: %s\n", mycli.WAClient.Store.ID) fmt.Printf("[POLL DEBUG] ✅ mycli.WAClient is initialized: %s\n", mycli.WAClient.Store.ID)
} }
decrypted, err := mycli.clientPointer[mycli.userID].DecryptPollVote(context.Background(), evt) decrypted, err := mycli.clientPointer.Get(mycli.userID).DecryptPollVote(context.Background(), evt)
if err != nil { if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err) mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err)
} else { } else {
@@ -1817,6 +2000,27 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
doWebhook = true doWebhook = true
postMap["event"] = "Archive" postMap["event"] = "Archive"
// postMap["data"] still holds the raw event at this point, so the type
// assertion below panicked on every Archive event. Same marshal/unmarshal
// step every other case in this switch already does.
if postMap["data"] != nil {
jsonBytes, err := json.Marshal(postMap["data"])
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)
return
}
var parsed map[string]interface{}
if err := json.Unmarshal(jsonBytes, &parsed); err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)
return
}
postMap["data"] = parsed
} else {
postMap["data"] = make(map[string]interface{})
}
dataMap := postMap["data"].(map[string]interface{}) dataMap := postMap["data"].(map[string]interface{})
dataMap["JID"] = evt.JID dataMap["JID"] = evt.JID
dataMap["Timestamp"] = evt.Timestamp dataMap["Timestamp"] = evt.Timestamp
@@ -1897,7 +2101,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
} }
// Agora mata o canal DEPOIS de enviar o evento // Agora mata o canal DEPOIS de enviar o evento
mycli.killChannel[mycli.userID] <- true safemap.TrySend(mycli.killChannel.Get(mycli.userID), true)
case *events.ChatPresence: case *events.ChatPresence:
doWebhook = true doWebhook = true
postMap["event"] = "ChatPresence" postMap["event"] = "ChatPresence"
@@ -1984,6 +2188,20 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
// Trigger instance restart via websocket-capable service (non-blocking) // Trigger instance restart via websocket-capable service (non-blocking)
go func(instanceID string) { go func(instanceID string) {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] Disconnected detected, restarting instance", instanceID) mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] Disconnected detected, restarting instance", instanceID)
if allowed, wait := reconnectAllowed(instanceID); !allowed {
if wait < 0 {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] a reconnect is already scheduled — this event will not open another", instanceID)
return
}
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] reconnect loop detected: more than %d restarts in %s. Next attempt in %s. If the device was logged out from the phone, only a new QR scan will fix it.", instanceID, reconnectFreeAttempts, reconnectWindow, wait)
if err := mycli.instanceRepository.UpdateConnected(instanceID, false, fmt.Sprintf("Reconnect backing off — next attempt in %s", wait)); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] could not record the backoff reason: %v", instanceID, err)
}
time.Sleep(wait)
reconnectWaitDone(instanceID)
}
if err := mycli.service.ReconnectClient(instanceID); err != nil { if err := mycli.service.ReconnectClient(instanceID); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to restart instance: %v", instanceID, err) mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to restart instance: %v", instanceID, err)
} }
@@ -2382,7 +2600,7 @@ func (w whatsmeowService) StartInstance(instanceId string) error {
} }
} }
w.killChannel[instance.Id] = make(chan bool) w.killChannel.Set(instance.Id, make(chan bool))
clientData := &ClientData{ clientData := &ClientData{
Instance: instance, Instance: instance,
@@ -2618,7 +2836,14 @@ func fetchWhatsAppWebVersion() (*clientVersion, error) {
return cachedWebVersion, nil return cachedWebVersion, nil
} }
resp, err := http.Get("https://web.whatsapp.com/sw.js") req, err := http.NewRequest("GET", "https://web.whatsapp.com/sw.js", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request for WhatsApp Web version: %v", err)
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
httpClient := &http.Client{Timeout: 10 * time.Second}
resp, err := httpClient.Do(req)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to fetch WhatsApp Web version: %v", err) return nil, fmt.Errorf("failed to fetch WhatsApp Web version: %v", err)
} }
@@ -2683,7 +2908,7 @@ func (w whatsmeowService) UpdateInstanceSettings(instanceId string) error {
} }
// Verifica se o MyClient existe // Verifica se o MyClient existe
myClient, exists := w.myClientPointer[instanceId] myClient, exists := w.myClientPointer.Lookup(instanceId)
if !exists { if !exists {
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId) w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
return fmt.Errorf("instance %s not found in runtime", instanceId) return fmt.Errorf("instance %s not found in runtime", instanceId)
@@ -2742,7 +2967,7 @@ func (w whatsmeowService) UpdateInstanceAdvancedSettings(instanceId string) erro
} }
// Verifica se o MyClient existe // Verifica se o MyClient existe
myClient, exists := w.myClientPointer[instanceId] myClient, exists := w.myClientPointer.Lookup(instanceId)
if !exists { if !exists {
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId) w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
return fmt.Errorf("instance %s not found in runtime", instanceId) return fmt.Errorf("instance %s not found in runtime", instanceId)
@@ -2762,19 +2987,19 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
w.userInfoCache.Delete(token) w.userInfoCache.Delete(token)
// Limpar myClientPointer se existir // Limpar myClientPointer se existir
if _, exists := w.myClientPointer[instanceId]; exists { if _, exists := w.myClientPointer.Lookup(instanceId); exists {
delete(w.myClientPointer, instanceId) w.myClientPointer.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId)
} }
// Limpar clientPointer se existir // Limpar clientPointer se existir
if _, exists := w.clientPointer[instanceId]; exists { if _, exists := w.clientPointer.Lookup(instanceId); exists {
delete(w.clientPointer, instanceId) w.clientPointer.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId)
} }
// Limpar killChannel se existir // Limpar killChannel se existir
if killChan, exists := w.killChannel[instanceId]; exists { if killChan, exists := w.killChannel.Lookup(instanceId); exists {
select { select {
case killChan <- true: case killChan <- true:
// Canal recebeu o sinal // Canal recebeu o sinal
@@ -2782,7 +3007,7 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
// Canal pode estar bloqueado, apenas fecha // Canal pode estar bloqueado, apenas fecha
} }
close(killChan) close(killChan)
delete(w.killChannel, instanceId) w.killChannel.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId)
} }
@@ -2796,8 +3021,8 @@ func NewWhatsmeowService(
messageRepository message_repository.MessageRepository, messageRepository message_repository.MessageRepository,
labelRepository label_repository.LabelRepository, labelRepository label_repository.LabelRepository,
config *config.Config, config *config.Config,
killChannel map[string](chan bool), killChannel *safemap.Map[chan bool],
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
rabbitmqProducer producer_interfaces.Producer, rabbitmqProducer producer_interfaces.Producer,
webhookProducer producer_interfaces.Producer, webhookProducer producer_interfaces.Producer,
websocketProducer producer_interfaces.Producer, websocketProducer producer_interfaces.Producer,
@@ -2820,7 +3045,7 @@ func NewWhatsmeowService(
killChannel: killChannel, killChannel: killChannel,
userInfoCache: cache.New(5*time.Minute, 10*time.Minute), userInfoCache: cache.New(5*time.Minute, 10*time.Minute),
clientPointer: clientPointer, clientPointer: clientPointer,
myClientPointer: make(map[string]*MyClient), myClientPointer: safemap.New[*MyClient](),
rabbitmqProducer: rabbitmqProducer, rabbitmqProducer: rabbitmqProducer,
webhookProducer: webhookProducer, webhookProducer: webhookProducer,
websocketProducer: websocketProducer, websocketProducer: websocketProducer,
@@ -2831,6 +3056,7 @@ func NewWhatsmeowService(
natsProducer: natsProducer, natsProducer: natsProducer,
loggerWrapper: loggerWrapper, loggerWrapper: loggerWrapper,
passkeyCeremony: ceremony.NewStore(), passkeyCeremony: ceremony.NewStore(),
authStore: &sharedSQLStore{},
} }
} }
@@ -2848,7 +3074,7 @@ func (w *whatsmeowService) PasskeyCeremonyStore() *ceremony.Store {
// SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp // SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp
// for the given instance. Called by POST /passkey-ceremony/{token}/response. // for the given instance. Called by POST /passkey-ceremony/{token}/response.
func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error { func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error {
client, ok := w.clientPointer[instanceId] client, ok := w.clientPointer.Lookup(instanceId)
if !ok || client == nil { if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId) return fmt.Errorf("no active client for instance %s", instanceId)
} }
@@ -2867,7 +3093,7 @@ func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.
// ConfirmPasskey finishes the pairing after the user verified the code. // ConfirmPasskey finishes the pairing after the user verified the code.
// Called by POST /passkey-ceremony/{token}/confirm. // Called by POST /passkey-ceremony/{token}/confirm.
func (w *whatsmeowService) ConfirmPasskey(instanceId string) error { func (w *whatsmeowService) ConfirmPasskey(instanceId string) error {
client, ok := w.clientPointer[instanceId] client, ok := w.clientPointer.Lookup(instanceId)
if !ok || client == nil { if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId) return fmt.Errorf("no active client for instance %s", instanceId)
} }
+75
View File
@@ -0,0 +1,75 @@
# Script de Verificacao de Atualizacoes do Upstream (PowerShell)
param (
[string]$UpstreamUrl = "https://github.com/evolution-foundation/evolution-go.git"
)
$dateStr = Get-Date -Format "yyyy-MM-dd_HHmmss"
$reportFile = "relatorio_atualizacao_$dateStr.md"
Write-Host "=== Iniciando Auditoria de Atualizacoes do Upstream ($dateStr) ==="
$remotes = git remote
if ($remotes -notcontains "upstream") {
git remote add upstream $UpstreamUrl
}
git fetch upstream --tags
$localHead = (git rev-parse HEAD).Trim()
$upstreamMain = (git rev-parse upstream/main).Trim()
$newCommits = git log HEAD..upstream/main --oneline -n 15
$newCommitCount = (git rev-list --count HEAD..upstream/main).Trim()
$latestLocalTag = git describe --tags --abbrev=0 2>$null
if (-not $latestLocalTag) { $latestLocalTag = "0.7.2" }
$latestUpstreamTag = ((git tag -l --sort=-v:refname | Select-Object -First 1) + "").Trim()
$localWhatsmeow = ((Get-Content go.mod | Select-String "go.mau.fi/whatsmeow") -replace "^\s*go.mau.fi/whatsmeow\s+", "").Trim()
$impactNotice = if ([int]$newCommitCount -gt 0) {
"WARNING: Novidades detectadas no upstream ($newCommitCount novos commits). Recomenda-se abrir branch de teste em maintenance/sync-upstream."
} else {
"OK: Ambiente alinhado. Nao ha novos commits pendentes na branch principal do upstream."
}
$commitsBlock = if ($newCommits) { $newCommits -join "`r`n" } else { "Nenhum commit novo detectado." }
$sb = New-Object System.Text.StringBuilder
[void]$sb.AppendLine("# Relatorio de Monitoramento de Atualizacoes — Upstream EvoGO")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("- Data da Auditoria: $(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')")
[void]$sb.AppendLine("- Commit Local Base: $localHead")
[void]$sb.AppendLine("- Tag Local Recente: $latestLocalTag")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## 1. Estado da Branch Principal (Upstream Main)")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("- Commit Upstream Main: $upstreamMain")
[void]$sb.AppendLine("- Commits a frente no upstream: $newCommitCount")
[void]$sb.AppendLine("- Ultima Tag Upstream: $latestUpstreamTag")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("### Commits Recentes no Upstream:")
[void]$sb.AppendLine('```')
[void]$sb.AppendLine($commitsBlock)
[void]$sb.AppendLine('```')
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## 2. Dependencia Central (Whatsmeow)")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("- Versao Whatsmeow no go.mod local: $localWhatsmeow")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## 3. Analise de Impacto e Conflitos")
[void]$sb.AppendLine("")
[void]$sb.AppendLine($impactNotice)
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("*Relatorio gerado pelo script de monitoramento EvoGO.*")
[System.IO.File]::WriteAllText((Join-Path (Get-Location) $reportFile), $sb.ToString(), [System.Text.Encoding]::UTF8)
Write-Host "Relatorio gerado com sucesso em: $reportFile"
Get-Content $reportFile
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
set -euo pipefail
REPORT_DATE=$(date +%Y-%m-%d_%H%M%S)
REPORT_FILE="relatorio_atualizacao_${REPORT_DATE}.md"
echo "=== Iniciando Auditoria de Atualizacoes do Upstream (${REPORT_DATE}) ==="
# 1. Configurar ou garantir remoto upstream
if ! git remote | grep -q "^upstream$"; then
git remote add upstream https://github.com/evolution-foundation/evolution-go.git
fi
git fetch upstream --tags
LOCAL_HEAD=$(git rev-parse HEAD)
UPSTREAM_MAIN=$(git rev-parse upstream/main)
UPSTREAM_DEV=$(git rev-parse upstream/develop 2>/dev/null || echo "N/A")
NEW_COMMITS_COUNT=$(git rev-list --count HEAD..upstream/main 2>/dev/null || echo 0)
NEW_COMMITS_LIST=$(git log HEAD..upstream/main --oneline -n 15 2>/dev/null || echo "Nenhum commit novo.")
LATEST_LOCAL_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "nenhuma")
LATEST_UPSTREAM_TAG=$(git tag -l --sort=-v:refname | head -n 1)
# Whatsmeow version comparison
LOCAL_WHATSMEOW=$(grep "go.mau.fi/whatsmeow" go.mod | awk '{print $2}' || echo "N/A")
cat << EOF > "${REPORT_FILE}"
# Relatorio de Monitoramento de Atualizacoes — Upstream EvoGO
**Data da Auditoria:** $(date '+%d/%m/%Y %H:%M:%S')
**Commit Local Base:** \`${LOCAL_HEAD}\`
**Tag Local Recente:** \`${LATEST_LOCAL_TAG}\`
---
## 1. Estado da Branch Principal (Upstream Main)
- **Commit Upstream Main:** \`${UPSTREAM_MAIN}\`
- **Commits a frente do upstream:** ${NEW_COMMITS_COUNT}
- **Ultima Tag Upstream:** \`${LATEST_UPSTREAM_TAG}\`
### Commits Recentes no Upstream:
\`\`\`
${NEW_COMMITS_LIST}
\`\`\`
---
## 2. Dependencia Central (Whatsmeow)
- **Versao Whatsmeow no go.mod local:** \`${LOCAL_WHATSMEOW}\`
---
## 3. Analise de Impacto e Conflitos
$([ "$NEW_COMMITS_COUNT" -gt 0 ] && echo "⚠ **Novidades detectadas no upstream!** Recomenda-se abrir branch de analise em \`maintenance/sync-upstream\`." || echo "✓ **Ambiente alinhado.** Nao ha novos commits pendentes na branch principal do upstream.")
---
*Relatorio gerado automaticamente pelo pipeline de monitoramento EvoGO.*
EOF
echo "Relatorio gerado em: ${REPORT_FILE}"
cat "${REPORT_FILE}"
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env bash
# Incorpora o upstream oficial na nossa distribuicao SEM sobrescrever nada nosso.
#
# Fluxo (idempotente, seguro para rodar todo dia):
# 1. fetch upstream/main + tags
# 2. fast-forward de origin/upstream-sync (push sem force: se nao for ff, falha e abre issue)
# 3. merge upstream/main -> branch maintenance/sync-upstream-<sha> criada a partir de maintained-develop
# - conflito -> aborta, abre Issue listando os arquivos em conflito
# - limpo -> go build / vet / test, push da branch e PR para maintained-develop
# 4. verifica se ha versao mais nova do go.mau.fi/whatsmeow e abre Issue de aviso
#
# maintained-develop e maintained-stable NUNCA recebem push deste script.
# Opcional: AUTO_MERGE=true faz merge automatico do PR em maintained-develop quando
# build e testes passam (nunca em maintained-stable).
#
# Variaveis: GITEA_URL, REPO (owner/name), GITEA_TOKEN, UPSTREAM_URL, BASE_BRANCH, AUTO_MERGE
set -euo pipefail
GITEA_URL="${GITEA_URL:-https://git.jf.eng.br}"
REPO="${REPO:-jfeng/EvoGO}"
UPSTREAM_URL="${UPSTREAM_URL:-https://github.com/evolution-foundation/evolution-go.git}"
UPSTREAM_BRANCH="${UPSTREAM_BRANCH:-main}"
BASE_BRANCH="${BASE_BRANCH:-maintained-develop}"
MIRROR_BRANCH="${MIRROR_BRANCH:-upstream-sync}"
AUTO_MERGE="${AUTO_MERGE:-false}"
API="${GITEA_URL%/}/api/v1/repos/${REPO}"
log() { echo "[upstream-sync] $*"; }
api() { # api METHOD PATH [JSON]
local method="$1" path="$2" data="${3:-}"
if [ -z "${GITEA_TOKEN:-}" ]; then
log "GITEA_TOKEN ausente; chamada ${method} ${path} ignorada"
return 1
fi
if [ -n "$data" ]; then
curl -fsS -X "$method" -H "Authorization: token ${GITEA_TOKEN}" -H "Content-Type: application/json" \
--data "$data" "${API}${path}"
else
curl -fsS -X "$method" -H "Authorization: token ${GITEA_TOKEN}" "${API}${path}"
fi
}
json_payload() { # json_payload key=file|key=@string ... -> JSON object
python3 - "$@" <<'PY'
import json, sys
out = {}
for arg in sys.argv[1:]:
k, v = arg.split("=", 1)
if v.startswith("@"):
out[k] = v[1:]
else:
out[k] = open(v, encoding="utf-8").read()
print(json.dumps(out))
PY
}
open_issue_once() { # open_issue_once TITLE BODY_FILE
local title="$1" body_file="$2" existing
existing=$(api GET "/issues?state=open&type=issues&limit=50" | python3 -c "
import json,sys
t=sys.argv[1]
print(next((str(i['number']) for i in json.load(sys.stdin) if i['title']==t),''))" "$title" || true)
if [ -n "$existing" ]; then
log "Issue ja aberta (#${existing}): ${title}"
return 0
fi
api POST "/issues" "$(json_payload "title=@${title}" "body=${body_file}")" >/dev/null && log "Issue aberta: ${title}"
}
git config user.name >/dev/null || git config user.name "EvoGO Upstream Bot"
git config user.email >/dev/null || git config user.email "[email protected]"
git remote get-url upstream >/dev/null 2>&1 || git remote add upstream "$UPSTREAM_URL"
git fetch --quiet upstream "$UPSTREAM_BRANCH" --tags
git fetch --quiet origin
UP_SHA=$(git rev-parse "upstream/${UPSTREAM_BRANCH}")
UP_SHORT=$(git rev-parse --short=7 "$UP_SHA")
REPORT=$(mktemp)
# --- 1. espelho upstream-sync (fast-forward apenas) -----------------------------
if git rev-parse --verify --quiet "origin/${MIRROR_BRANCH}" >/dev/null; then
if git merge-base --is-ancestor "$UP_SHA" "origin/${MIRROR_BRANCH}"; then
log "${MIRROR_BRANCH} ja contem upstream ${UP_SHORT}"
elif git merge-base --is-ancestor "origin/${MIRROR_BRANCH}" "$UP_SHA"; then
git push origin "${UP_SHA}:refs/heads/${MIRROR_BRANCH}"
log "${MIRROR_BRANCH} avancada (fast-forward) para ${UP_SHORT}"
else
printf '%s\n' "A branch \`${MIRROR_BRANCH}\` divergiu de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT})." \
"" "Nao foi feito push forcado. Verifique se o upstream reescreveu historico antes de prosseguir." > "$REPORT"
open_issue_once "upstream-sync: ${MIRROR_BRANCH} divergiu do upstream" "$REPORT" || true
exit 1
fi
else
git push origin "${UP_SHA}:refs/heads/${MIRROR_BRANCH}"
fi
# Tags do upstream (sem force: tags locais com mesmo nome nunca sao sobrescritas)
git push --quiet origin --tags 2>/dev/null || log "algumas tags nao foram enviadas (ja existem com outro alvo)"
# --- 2. ha algo novo para incorporar? ----------------------------------------------
if git merge-base --is-ancestor "$UP_SHA" "origin/${BASE_BRANCH}"; then
log "${BASE_BRANCH} ja incorpora upstream ${UP_SHORT}; nada a fazer"
else
SYNC_BRANCH="maintenance/sync-upstream-${UP_SHORT}"
if git rev-parse --verify --quiet "origin/${SYNC_BRANCH}" >/dev/null; then
log "branch ${SYNC_BRANCH} ja existe (PR pendente); nada a fazer"
else
NEW_COMMITS=$(git log --oneline --no-merges "origin/${BASE_BRANCH}..${UP_SHA}" | head -50)
SENSITIVE=$(git diff --stat "$(git merge-base "origin/${BASE_BRANCH}" "$UP_SHA")" "$UP_SHA" -- \
Dockerfile docker-compose* .env.example go.mod pkg/core cmd LICENSE NOTICE TRADEMARKS.md || true)
git checkout --quiet -B "$SYNC_BRANCH" "origin/${BASE_BRANCH}"
if ! git merge --no-ff --no-edit -m "sync: merge upstream ${UPSTREAM_BRANCH} ${UP_SHORT} into ${BASE_BRANCH}" "$UP_SHA"; then
CONFLICTS=$(git diff --name-only --diff-filter=U)
git merge --abort
{
echo "O merge automatico de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT}) em \`${BASE_BRANCH}\` gerou conflitos."
echo; echo "## Arquivos em conflito"; echo '```'; echo "$CONFLICTS"; echo '```'
echo; echo "## Commits novos do upstream"; echo '```'; echo "$NEW_COMMITS"; echo '```'
echo; echo "## Como resolver"
echo '```bash'
echo "git fetch origin && git fetch upstream"
echo "git checkout -b ${SYNC_BRANCH} origin/${BASE_BRANCH}"
echo "git merge upstream/${UPSTREAM_BRANCH} # resolver conflitos preservando as correcoes EvoGO"
echo "go build ./... && go vet ./... && go test ./..."
echo "git push origin ${SYNC_BRANCH} # e abrir PR para ${BASE_BRANCH}"
echo '```'
echo; echo "Veja docs/maintenance/UPSTREAM_SYNC.md."
} > "$REPORT"
open_issue_once "upstream-sync: conflito ao incorporar upstream ${UP_SHORT}" "$REPORT" || true
exit 0
fi
TEST_STATUS="nao executado (Go indisponivel)"
TESTS_OK=false
if command -v go >/dev/null 2>&1; then
if go build ./... > /tmp/sync-build.log 2>&1 && go vet ./... >> /tmp/sync-build.log 2>&1 \
&& go test ./... >> /tmp/sync-build.log 2>&1; then
TEST_STATUS="OK (go build, go vet, go test)"
TESTS_OK=true
else
TEST_STATUS="FALHOU — ver log abaixo"
fi
fi
git push --quiet origin "$SYNC_BRANCH"
{
echo "Incorporacao automatica de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT}) em \`${BASE_BRANCH}\`."
echo
echo "O merge foi feito por cima da nossa branch: todas as correcoes EvoGO continuam presentes."
echo
echo "**Build/testes:** ${TEST_STATUS}"
echo; echo "## Commits novos do upstream"; echo '```'; echo "$NEW_COMMITS"; echo '```'
if [ -n "$SENSITIVE" ]; then
echo; echo "## Arquivos sensiveis alterados (revisar com atencao)"; echo '```'; echo "$SENSITIVE"; echo '```'
fi
if [ "$TESTS_OK" != true ] && [ -f /tmp/sync-build.log ]; then
echo; echo "## Log de build/testes (final)"; echo '```'; tail -60 /tmp/sync-build.log; echo '```'
fi
echo; echo "## Checklist antes do merge"
echo "- [ ] Revisar commits e arquivos sensiveis"
echo "- [ ] Verificar mudancas de schema (whatsmeow / SQLite / Postgres)"
echo "- [ ] Testar imagem de homologacao (docs/maintenance/WHATSAPP_COMPATIBILITY.md)"
} > "$REPORT"
PR_JSON=$(api POST "/pulls" "$(json_payload "title=@sync: incorporar upstream ${UP_SHORT}" \
"head=@${SYNC_BRANCH}" "base=@${BASE_BRANCH}" "body=${REPORT}")" || true)
PR_NUMBER=$(printf '%s' "$PR_JSON" | python3 -c "import json,sys
try: print(json.load(sys.stdin)['number'])
except Exception: print('')")
log "PR aberto: #${PR_NUMBER:-?}"
if [ "$AUTO_MERGE" = "true" ] && [ "$TESTS_OK" = true ] && [ -n "$PR_NUMBER" ]; then
api POST "/pulls/${PR_NUMBER}/merge" '{"Do":"merge","delete_branch_after_merge":true}' >/dev/null \
&& log "PR #${PR_NUMBER} mesclado automaticamente em ${BASE_BRANCH}"
fi
fi
fi
# --- 3. whatsmeow mais novo disponivel? -------------------------------------------
if command -v go >/dev/null 2>&1; then
git checkout --quiet "origin/${BASE_BRANCH}"
CUR_WM=$(awk '$1=="go.mau.fi/whatsmeow"{print $2}' go.mod)
LATEST_WM=$(GOFLAGS=-mod=mod go list -m -f '{{.Version}}' go.mau.fi/whatsmeow@latest 2>/dev/null || true)
if [ -n "$LATEST_WM" ] && [ -n "$CUR_WM" ] && [ "$LATEST_WM" != "$CUR_WM" ]; then
{
echo "Ha uma versao mais nova de \`go.mau.fi/whatsmeow\`."
echo
echo "- Atual (${BASE_BRANCH}): \`${CUR_WM}\`"
echo "- Mais recente: \`${LATEST_WM}\`"
echo
echo "Defasagem do whatsmeow e a principal causa do erro **Client outdated (405)**."
echo "Atualize em uma branch \`maintenance/whatsmeow-<data>\`:"
echo '```bash'
echo "go get go.mau.fi/whatsmeow@latest && go mod tidy"
echo "go build ./... && go vet ./... && go test ./..."
echo '```'
} > "$REPORT"
open_issue_once "whatsmeow: atualizacao disponivel (${LATEST_WM})" "$REPORT" || true
else
log "whatsmeow em dia (${CUR_WM})"
fi
fi
rm -f "$REPORT"
log "concluido"