Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd7fc29d11 | ||
|
|
406fcc2e52 | ||
|
|
b140fdb390 | ||
|
|
c9511a636e | ||
|
|
5b71495e93 | ||
|
|
03d619bb55 | ||
|
|
0379082181 | ||
|
|
e02441fc4e | ||
|
|
abaac8eb93 | ||
|
|
4998ab3d45 | ||
|
|
74389cc8de | ||
|
|
c33b4d98fd | ||
|
|
fc35d72029 | ||
|
|
3fce4dbcca | ||
|
|
0c4ac7d9a9 | ||
|
|
a5f7e1c98a | ||
|
|
a0c74485b8 | ||
|
|
a4add7cc5e | ||
|
|
3cc5192b7b | ||
|
|
87a354aee8 |
No files matched your search
@@ -1,11 +1,20 @@
|
|||||||
name: Docker - Build e Publicacao
|
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)
|
||||||
|
# Tags v* aprovadas em maintained-stable tambem promovem :latest apos o push
|
||||||
|
# das tags imutavel e semantica, evitando a corrida com promote-latest.yml.
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- maintained-stable
|
- maintained-stable
|
||||||
tags:
|
tags:
|
||||||
- 'v*.*.*'
|
- 'v*'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
publish_image:
|
publish_image:
|
||||||
@@ -14,61 +23,149 @@ on:
|
|||||||
default: false
|
default: false
|
||||||
required: true
|
required: true
|
||||||
target_tag:
|
target_tag:
|
||||||
description: 'Tag semantica para publicacao (ex: 0.7.2)'
|
description: 'Tag semantica para publicacao (ex: 0.7.2-evogo.1). Vazio = arquivo VERSION'
|
||||||
type: string
|
type: string
|
||||||
default: ''
|
default: ''
|
||||||
required: false
|
required: false
|
||||||
|
promote_latest:
|
||||||
|
description: 'Tambem atualizar :latest (somente versoes aprovadas em maintained-stable)'
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
required: false
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: promote-latest
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: git.jf.eng.br
|
||||||
|
IMAGE: git.jf.eng.br/jfeng/evogo
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build_docker:
|
build_docker:
|
||||||
name: Build e Verificacao Docker
|
name: Build, Scan e Publicacao
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout do Repositorio
|
- name: Checkout do Repositorio
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Validar origem da promocao latest
|
||||||
|
id: promotion
|
||||||
|
run: |
|
||||||
|
PROMOTE=false
|
||||||
|
if { [ "${{ github.event_name }}" = "push" ] && [ "${{ github.ref_type }}" = "tag" ]; } || [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
|
||||||
|
git fetch origin maintained-stable
|
||||||
|
if git merge-base --is-ancestor HEAD FETCH_HEAD; then
|
||||||
|
PROMOTE=true
|
||||||
|
elif [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
|
||||||
|
echo "Promocao recusada: commit nao aprovado em maintained-stable"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
echo "promote=${PROMOTE}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Configurar Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
|
||||||
|
- name: Validar codigo antes da publicacao
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y --no-install-recommends libjpeg-dev libwebp-dev poppler-utils ffmpeg
|
||||||
|
go mod verify
|
||||||
|
go vet ./...
|
||||||
|
go test -v ./...
|
||||||
|
|
||||||
- name: Obter Versao e Commit SHA
|
- name: Obter Versao e Commit SHA
|
||||||
id: meta
|
id: meta
|
||||||
run: |
|
run: |
|
||||||
VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
|
|
||||||
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||||
echo "commit_sha=${COMMIT_SHA}" >> $GITHUB_OUTPUT
|
VERSION="${{ github.ref_name }}"
|
||||||
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> $GITHUB_OUTPUT
|
VERSION="${VERSION#v}"
|
||||||
|
PUBLISH=true
|
||||||
- name: Configurar Docker Buildx
|
else
|
||||||
uses: docker/setup-buildx-action@v3
|
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
|
- name: Construir Imagem Docker Local
|
||||||
uses: docker/build-push-action@v5
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
load: true
|
|
||||||
tags: evogo:local
|
|
||||||
build-args: |
|
|
||||||
VERSION=${{ steps.meta.outputs.image_tag }}
|
|
||||||
|
|
||||||
- name: Testar Execucao Basica do Container
|
|
||||||
run: |
|
run: |
|
||||||
docker run --rm evogo:local --help || echo "Container executou verificacao inicial com sucesso"
|
docker build \
|
||||||
|
--build-arg VERSION=${{ steps.meta.outputs.image_tag }} \
|
||||||
|
-t evogo:ci-${{ steps.meta.outputs.commit_sha }} .
|
||||||
|
|
||||||
- name: Login no Gitea Package Registry (se aprovado)
|
- name: Testar Inicializacao do Container
|
||||||
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }}
|
run: |
|
||||||
uses: docker/login-action@v3
|
# O binario precisa subir e falhar apenas por falta de banco/config,
|
||||||
with:
|
# nunca por erro de link (CGO/libwebp/libjpeg) ou arquivo ausente.
|
||||||
registry: git.jf.eng.br
|
set +e
|
||||||
username: ${{ secrets.REGISTRY_USER || github.actor }}
|
timeout 20 docker run --rm evogo:ci-${{ steps.meta.outputs.commit_sha }} > /tmp/run.log 2>&1
|
||||||
password: ${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}
|
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: Publicar Imagens no Registry (apenas com aprovacao expressa)
|
- name: Verificar Vulnerabilidades (Trivy, nao bloqueante)
|
||||||
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }}
|
continue-on-error: true
|
||||||
uses: docker/build-push-action@v5
|
run: |
|
||||||
with:
|
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
|
||||||
context: .
|
image --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
|
||||||
push: true
|
evogo:ci-${{ steps.meta.outputs.commit_sha }}
|
||||||
tags: |
|
|
||||||
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.image_tag }}
|
- name: Login no Gitea Package Registry
|
||||||
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.version }}
|
if: steps.meta.outputs.publish == 'true'
|
||||||
build-args: |
|
run: |
|
||||||
VERSION=${{ steps.meta.outputs.image_tag }}
|
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 [ "${{ steps.promotion.outputs.promote }}" = "true" ]; then
|
||||||
|
docker tag "$SRC" "$IMAGE:latest"
|
||||||
|
push "$IMAGE:latest"
|
||||||
|
IMMUTABLE_DIGEST=$(docker buildx imagetools inspect "$IMAGE:${{ steps.meta.outputs.image_tag }}" --format '{{json .Manifest.Digest}}')
|
||||||
|
LATEST_DIGEST=$(docker buildx imagetools inspect "$IMAGE:latest" --format '{{json .Manifest.Digest}}')
|
||||||
|
[ -n "$IMMUTABLE_DIGEST" ] && [ "$IMMUTABLE_DIGEST" = "$LATEST_DIGEST" ]
|
||||||
|
echo "Publicado e verificado: $IMAGE:latest = $IMMUTABLE_DIGEST"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Limpeza
|
||||||
|
if: always()
|
||||||
|
run: docker image rm -f evogo:ci-${{ steps.meta.outputs.commit_sha }} >/dev/null 2>&1 || true
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
name: Docker - Promover latest
|
||||||
|
|
||||||
|
# :latest = ultimo release v* contido em maintained-stable.
|
||||||
|
# Nao recompila: baixa a imagem imutavel <versao>-<sha7> ja publicada pelo
|
||||||
|
# docker-build.yml para aquela tag e apenas a re-etiqueta, preservando o digest.
|
||||||
|
# So roda quando maintained-stable avanca (promocao aprovada) ou manualmente.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- maintained-stable
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: promote-latest
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: git.jf.eng.br
|
||||||
|
IMAGE: git.jf.eng.br/jfeng/evogo
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
promote:
|
||||||
|
name: Promover release para latest
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout do Repositorio
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Identificar release
|
||||||
|
id: rel
|
||||||
|
run: |
|
||||||
|
git fetch --tags --force
|
||||||
|
TAG=$(git describe --tags --abbrev=0 --match 'v*' HEAD)
|
||||||
|
SHA7=$(git rev-list -n1 "$TAG" | cut -c1-7)
|
||||||
|
VERSION="${TAG#v}"
|
||||||
|
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "source=${IMAGE}:${VERSION}-${SHA7}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "Release: ${TAG} -> ${IMAGE}:${VERSION}-${SHA7}"
|
||||||
|
|
||||||
|
- name: Login no Gitea Package Registry
|
||||||
|
run: |
|
||||||
|
USER="${{ secrets.REGISTRY_USER }}"
|
||||||
|
[ -n "$USER" ] || USER="${{ github.actor }}"
|
||||||
|
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
|
||||||
|
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
|
||||||
|
for n in 1 2 3 4 5; do
|
||||||
|
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
|
||||||
|
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
|
||||||
|
sleep $((n*15))
|
||||||
|
done
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Re-etiquetar como latest
|
||||||
|
run: |
|
||||||
|
retry() {
|
||||||
|
for n in 1 2 3 4 5; do
|
||||||
|
"$@" && return 0
|
||||||
|
echo "'$*' falhou (tentativa $n/5); nova tentativa em $((n*15))s"
|
||||||
|
sleep $((n*15))
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
SRC="${{ steps.rel.outputs.source }}"
|
||||||
|
retry docker pull "$SRC"
|
||||||
|
docker tag "$SRC" "$IMAGE:latest"
|
||||||
|
retry docker push "$IMAGE:latest"
|
||||||
|
echo "Publicado: $IMAGE:latest (mesmo digest de $SRC)"
|
||||||
@@ -1,29 +1,53 @@
|
|||||||
name: Monitoramento Diario do Upstream
|
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:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
# Executa diariamente as 04:00 UTC (01:00 BRT)
|
# Diariamente as 04:00 UTC (01:00 BRT)
|
||||||
- cron: '0 4 * * *'
|
- cron: '0 4 * * *'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: upstream-sync
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check_upstream:
|
sync:
|
||||||
name: Verificar Atualizacoes do Upstream e Whatsmeow
|
name: Incorporar upstream e verificar whatsmeow
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout do Repositorio
|
- name: Checkout do Repositorio
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
|
ref: maintained-develop
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
token: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
|
||||||
- name: Executar Script de Verificacao
|
- name: Configurar Go
|
||||||
id: check
|
uses: actions/setup-go@v5
|
||||||
run: |
|
|
||||||
bash scripts/check-upstream-updates.sh
|
|
||||||
|
|
||||||
- name: Salvar Relatorio como Artefato
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
with:
|
||||||
name: relatorio-upstream-${{ github.run_id }}
|
go-version-file: go.mod
|
||||||
path: relatorio_atualizacao_*.md
|
|
||||||
|
- 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
|
||||||
@@ -2,6 +2,16 @@
|
|||||||
|
|
||||||
## Não lançado
|
## Não lançado
|
||||||
|
|
||||||
|
### Manutenção da atualização 0.7.3
|
||||||
|
- Incorporadas seletivamente as melhorias do upstream 0.7.3: timeout de 60 s
|
||||||
|
no upgrade do banco de autenticação, nova tentativa após falha e registro
|
||||||
|
explícito do driver Postgres na configuração.
|
||||||
|
- SQLite de autenticação limitado a uma conexão compartilhada, evitando
|
||||||
|
concorrência de escrita; preservadas as correções próprias de envio e reconexão.
|
||||||
|
- Releases por tag aprovadas em `maintained-stable` passam a publicar `latest`
|
||||||
|
após as imagens versionadas, com conferência do digest e testes Go no pipeline.
|
||||||
|
- Sem alteração de dependências, schema ou contratos públicos nesta atualização.
|
||||||
|
|
||||||
### 🔧 Correções
|
### 🔧 Correções
|
||||||
- **whatsmeow atualizado para 2026-11-02** — a versão fixada na 0.7.2
|
- **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
|
(commit `b572e5bcb92b`, de 30/06/2026) ficou 125 dias atrás do upstream. O
|
||||||
@@ -18,6 +28,51 @@
|
|||||||
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe
|
- **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
|
de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
|
||||||
ao abrir o container; testado com banco SQLite v14 existente.
|
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
|
||||||
|
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -82,11 +82,75 @@ docker build \
|
|||||||
|
|
||||||
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
|
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
|
||||||
|
|
||||||
1. **Trigger em Pull Requests ou Push em develop:**
|
1. **Push em `maintained-stable`:** build da imagem (`linux/amd64`), teste de
|
||||||
- Executa `go vet` e `go test`.
|
inicialização do binário e scan Trivy (HIGH/CRITICAL, não bloqueante).
|
||||||
- Executa `docker build` para garantir que a imagem compila sem erros.
|
**Não publica.**
|
||||||
- **Não faz push** para o registry.
|
2. **Push de tag `v<versão>` (release aprovado):** mesmo build/teste/scan e
|
||||||
2. **Trigger em Tag ou Push em `maintained-stable`:**
|
publicação de:
|
||||||
- Constrói a imagem multiplataforma (`linux/amd64`, `linux/arm64`).
|
- `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
|
||||||
- Gera tag imutável associada ao commit.
|
- `git.jf.eng.br/jfeng/evogo:<versão>`
|
||||||
- Requer aprovação ou execução via `workflow_dispatch` para publicação em produção.
|
Se o commit já estiver em `maintained-stable`, promove também `latest`
|
||||||
|
e confere seu digest após publicar as imagens versionadas.
|
||||||
|
3. **`workflow_dispatch`:** publica apenas com `publish_image=true`; `:latest`
|
||||||
|
só com `promote_latest=true`.
|
||||||
|
|
||||||
|
### Gerar um release
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Após validar em maintained-develop e aprovar a promoção do commit:
|
||||||
|
git checkout maintained-stable
|
||||||
|
git pull --ff-only
|
||||||
|
# Integrar o commit validado pelo processo de revisão antes de criar a tag.
|
||||||
|
git tag -a v0.7.3-evogo.1 -m "EvoGO 0.7.3-evogo.1"
|
||||||
|
git push origin v0.7.3-evogo.1 # publica versão, tag imutável e latest
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
## Atualização seletiva 0.7.3-evogo.1
|
||||||
|
|
||||||
|
Esta release preserva o fork e incorpora apenas as melhorias de inicialização
|
||||||
|
SQL da 0.7.3. Não altera o whatsmeow, o schema, o licenciamento ou as APIs.
|
||||||
|
|
||||||
|
Ordem de publicação: validar a branch de manutenção, integrar em
|
||||||
|
`maintained-develop`, validar a imagem e sessões em homologação, promover o
|
||||||
|
commit validado a `maintained-stable` e então criar a tag
|
||||||
|
`v0.7.3-evogo.1` nesse commit. A publicação exige aprovação humana.
|
||||||
|
|
||||||
|
O workflow de build executa vet e testes antes de publicar. Para pushes de tags `v*`
|
||||||
|
cujo commit esteja em `maintained-stable`, publica as tags semântica e imutável,
|
||||||
|
promove `latest` e exige que o digest remoto seja igual ao da tag imutável.
|
||||||
|
A promoção e o build compartilham o grupo de concorrência `promote-latest`.
|
||||||
|
O workflow manual também exige essa ancestralidade para `promote_latest=true`.
|
||||||
|
Uma execução verde e a igualdade dos digests são a evidência da publicação;
|
||||||
|
a existência do YAML não comprova que uma imagem foi publicada.
|
||||||
|
|
||||||
|
Rollback: registrar o digest e a tag imutável anteriormente usados por `latest`
|
||||||
|
antes da promoção. Em caso de regressão, fixar essa imagem no Compose e seguir
|
||||||
|
[ROLLBACK.md](ROLLBACK.md). Esta alteração não requer migração adicional nem
|
||||||
|
restauração do banco. Manter o snapshot anterior para recuperação operacional.
|
||||||
@@ -26,7 +26,33 @@ git remote add upstream https://github.com/evolution-foundation/evolution-go.git
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Fluxo de Trabalho de Sincronização
|
## 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.
|
A sincronização **NUNCA** deve sobrescrever diretamente a branch `maintained-stable` ou branches ativas de desenvolvimento sem validação.
|
||||||
|
|
||||||
@@ -57,7 +83,7 @@ git push origin upstream-sync --tags
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Integração e Análise de Impacto
|
## 4. Integração e Análise de Impacto
|
||||||
|
|
||||||
### Etapa 4: Criar branch de teste e integração
|
### 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:
|
A partir de `maintained-develop`, crie uma branch de manutenção específica para a atualização:
|
||||||
@@ -80,7 +106,7 @@ Se houver conflitos:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Validação Pós-Sincronização
|
## 5. Validação Pós-Sincronização
|
||||||
|
|
||||||
Antes de propor a integração para as branches mantidas:
|
Antes de propor a integração para as branches mantidas:
|
||||||
|
|
||||||
@@ -102,7 +128,7 @@ Antes de propor a integração para as branches mantidas:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Promoção para as Branches Oficiais
|
## 6. Promoção para as Branches Oficiais
|
||||||
|
|
||||||
1. **Abra um Pull Request no Gitea:**
|
1. **Abra um Pull Request no Gitea:**
|
||||||
- Origem: `maintenance/sync-upstream-<nova-versao>`
|
- Origem: `maintenance/sync-upstream-<nova-versao>`
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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,6 +10,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gomessguii/logger"
|
"github.com/gomessguii/logger"
|
||||||
|
// Register the auth database driver independently of the WhatsApp service.
|
||||||
|
_ "github.com/lib/pq"
|
||||||
"gorm.io/driver/postgres"
|
"gorm.io/driver/postgres"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPostgresDriverRegistered(t *testing.T) {
|
||||||
|
if !slices.Contains(sql.Drivers(), "postgres") {
|
||||||
|
t.Fatalf("postgres driver not registered: %v", sql.Drivers())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -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}
|
||||||
}
|
}
|
||||||
@@ -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,
|
||||||
@@ -543,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 {
|
||||||
|
|||||||
@@ -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
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package whatsmeow_service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/evolution-foundation/evolution-go/pkg/config"
|
||||||
|
"go.mau.fi/whatsmeow/proto/waAdv"
|
||||||
|
"go.mau.fi/whatsmeow/store/sqlstore"
|
||||||
|
"go.mau.fi/whatsmeow/types"
|
||||||
|
_ "modernc.org/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSharedAuthContainerRetryAndConcurrentReuse(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
w := whatsmeowService{config: &config.Config{}, exPath: root, authStore: &sharedSQLStore{}}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if w.authStore.sqliteDB != nil {
|
||||||
|
if err := w.authStore.sqliteDB.Close(); err != nil {
|
||||||
|
t.Errorf("close auth store: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if _, err := w.getSharedSQLStoreContainer(); err == nil {
|
||||||
|
t.Fatal("expected failure before dbdata exists")
|
||||||
|
}
|
||||||
|
if err := os.Mkdir(filepath.Join(root, "dbdata"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
const callers = 16
|
||||||
|
containers := make([]*sqlstore.Container, callers)
|
||||||
|
errs := make([]error, callers)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := range callers {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
containers[i], errs[i] = w.getSharedSQLStoreContainer()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
for i := range callers {
|
||||||
|
if errs[i] != nil || containers[i] == nil {
|
||||||
|
t.Fatalf("caller %d could not retry: %v", i, errs[i])
|
||||||
|
}
|
||||||
|
if containers[i] != containers[0] {
|
||||||
|
t.Fatalf("caller %d opened a different container", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := w.authStore.sqliteDB.Stats().MaxOpenConnections; got != 1 {
|
||||||
|
t.Fatalf("SQLite connection limit = %d, want 1", got)
|
||||||
|
}
|
||||||
|
// Persist a paired-device record and reopen the existing schema as on restart.
|
||||||
|
device := containers[0].NewDevice()
|
||||||
|
jid := types.NewJID("5511999999999", types.DefaultUserServer)
|
||||||
|
device.ID = &jid
|
||||||
|
device.Account = &waAdv.ADVSignedDeviceIdentity{
|
||||||
|
Details: []byte("test device"),
|
||||||
|
AccountSignature: make([]byte, 64),
|
||||||
|
AccountSignatureKey: make([]byte, 32),
|
||||||
|
DeviceSignature: make([]byte, 64),
|
||||||
|
}
|
||||||
|
if err := device.Save(context.Background()); err != nil {
|
||||||
|
t.Fatalf("save session: %v", err)
|
||||||
|
}
|
||||||
|
if err := w.authStore.sqliteDB.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w.authStore = &sharedSQLStore{}
|
||||||
|
reopened, err := w.getSharedSQLStoreContainer()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reopen existing auth database: %v", err)
|
||||||
|
}
|
||||||
|
restored, err := reopened.GetDevice(context.Background(), jid)
|
||||||
|
if err != nil || restored == nil {
|
||||||
|
t.Fatalf("restore session: device=%v err=%v", restored, err)
|
||||||
|
}
|
||||||
|
if restored.RegistrationID != device.RegistrationID || *restored.NoiseKey.Pub != *device.NoiseKey.Pub {
|
||||||
|
t.Fatal("session keys changed after reopening")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
@@ -21,13 +22,13 @@ import (
|
|||||||
"golang.org/x/image/webp"
|
"golang.org/x/image/webp"
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
|
|
||||||
_ "github.com/lib/pq"
|
|
||||||
"github.com/patrickmn/go-cache"
|
"github.com/patrickmn/go-cache"
|
||||||
"github.com/skip2/go-qrcode"
|
"github.com/skip2/go-qrcode"
|
||||||
"go.mau.fi/whatsmeow"
|
"go.mau.fi/whatsmeow"
|
||||||
"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 +84,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 +98,17 @@ 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 its mutex is shared by value-receiver methods.
|
||||||
|
authStore *sharedSQLStore
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sharedSQLStore holds the process-wide whatsmeow sqlstore.Container for PostgresAuthDB
|
||||||
|
// (or the sqlite fallback). Cache only success; never Close on instance disconnect.
|
||||||
|
type sharedSQLStore struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
container *sqlstore.Container
|
||||||
|
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 +125,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 +181,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 +206,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 +218,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 +319,188 @@ 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.mu.Lock()
|
||||||
|
defer w.authStore.mu.Unlock()
|
||||||
|
if w.authStore.container != nil {
|
||||||
|
return w.authStore.container, nil
|
||||||
|
}
|
||||||
|
return w.createSharedSQLStoreContainer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called with authStore.mu held. A failed upgrade is retried by the next caller.
|
||||||
|
func (w whatsmeowService) createSharedSQLStoreContainer() (*sqlstore.Container, error) {
|
||||||
|
var dbLog waLog.Logger
|
||||||
|
if w.config.WaDebug != "" {
|
||||||
|
dbLog = waLog.Stdout("Database", w.config.WaDebug, true)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if w.config.PostgresAuthDB != "" {
|
||||||
|
if w.authDB == nil {
|
||||||
|
return nil, fmt.Errorf("postgres auth DB handle is nil")
|
||||||
|
}
|
||||||
|
container := sqlstore.NewWithDB(w.authDB, "postgres", dbLog)
|
||||||
|
if err := container.Upgrade(ctx); err != nil {
|
||||||
|
// Do not Close authDB — owned by main.
|
||||||
|
return nil, fmt.Errorf("failed to upgrade database: %w", err)
|
||||||
|
}
|
||||||
|
w.authStore.container = container
|
||||||
|
return container, nil
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
return nil, fmt.Errorf("failed to open sqlite auth store: %w", err)
|
||||||
|
}
|
||||||
|
db.SetMaxOpenConns(1)
|
||||||
|
db.SetMaxIdleConns(1)
|
||||||
|
db.SetConnMaxLifetime(5 * time.Minute)
|
||||||
|
db.SetConnMaxIdleTime(1 * time.Minute)
|
||||||
|
container := sqlstore.NewWithDB(db, "sqlite", dbLog)
|
||||||
|
if err := container.Upgrade(ctx); err != nil {
|
||||||
|
if closeErr := db.Close(); closeErr != nil {
|
||||||
|
return nil, fmt.Errorf("failed to upgrade database: %w; close sqlite auth store: %v", err, closeErr)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to upgrade database: %w", err)
|
||||||
|
}
|
||||||
|
w.authStore.sqliteDB = db
|
||||||
|
w.authStore.container = container
|
||||||
|
return container, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// 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
|
||||||
@@ -398,7 +566,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
|||||||
waVer := store.WAVersionContainer{uint32(version.Major), uint32(version.Minor), uint32(version.Patch)}
|
waVer := store.WAVersionContainer{uint32(version.Major), uint32(version.Minor), uint32(version.Patch)}
|
||||||
store.SetWAVersion(waVer)
|
store.SetWAVersion(waVer)
|
||||||
if store.BaseClientPayload != nil && store.BaseClientPayload.UserAgent != nil {
|
if store.BaseClientPayload != nil && store.BaseClientPayload.UserAgent != nil {
|
||||||
store.BaseClientPayload.UserAgent.AppVersion = &waProto.ClientPayload_UserAgent_AppVersion{
|
store.BaseClientPayload.UserAgent.AppVersion = &waWa6.ClientPayload_UserAgent_AppVersion{
|
||||||
Primary: proto.Uint32(uint32(version.Major)),
|
Primary: proto.Uint32(uint32(version.Major)),
|
||||||
Secondary: proto.Uint32(uint32(version.Minor)),
|
Secondary: proto.Uint32(uint32(version.Minor)),
|
||||||
Tertiary: proto.Uint32(uint32(version.Patch)),
|
Tertiary: proto.Uint32(uint32(version.Patch)),
|
||||||
@@ -416,7 +584,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
|
||||||
@@ -504,7 +675,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())
|
||||||
@@ -578,12 +749,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)
|
||||||
@@ -628,6 +799,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)
|
||||||
@@ -658,7 +837,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
|
||||||
}
|
}
|
||||||
@@ -852,8 +1031,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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -879,6 +1060,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
|
||||||
@@ -911,7 +1095,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 {
|
||||||
@@ -1281,7 +1465,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 {
|
||||||
@@ -1821,6 +2005,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
|
||||||
@@ -1901,7 +2106,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"
|
||||||
@@ -1988,6 +2193,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)
|
||||||
}
|
}
|
||||||
@@ -2386,7 +2605,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,
|
||||||
@@ -2694,7 +2913,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)
|
||||||
@@ -2753,7 +2972,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)
|
||||||
@@ -2773,19 +2992,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
|
||||||
@@ -2793,7 +3012,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2807,8 +3026,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,
|
||||||
@@ -2831,7 +3050,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,
|
||||||
@@ -2842,6 +3061,7 @@ func NewWhatsmeowService(
|
|||||||
natsProducer: natsProducer,
|
natsProducer: natsProducer,
|
||||||
loggerWrapper: loggerWrapper,
|
loggerWrapper: loggerWrapper,
|
||||||
passkeyCeremony: ceremony.NewStore(),
|
passkeyCeremony: ceremony.NewStore(),
|
||||||
|
authStore: &sharedSQLStore{},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2859,7 +3079,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)
|
||||||
}
|
}
|
||||||
@@ -2878,7 +3098,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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
Reference in new issue
Block a user