Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Use @trohitg/whatsapp-rpc as npm dependency
trohitgcc077c496fa5
diff --git a/.gitignore b/.gitignoreindex a78ddb65..43ee1e5d 100644--- a/.gitignore+++ b/.gitignore@@ -35,15 +35,8 @@ server/.env.***/*.p12**/*.pfx-# WhatsApp session data (contains auth tokens)-server/whatsapp-rpc/.wwebjs_*-server/whatsapp-rpc/.wwebjs_auth/-server/whatsapp-rpc/session/-server/whatsapp-rpc/*.db-server/whatsapp-rpc/data/-server/whatsapp-rpc/bin/-server/whatsapp-rpc/*.exe-server/whatsapp-rpc/qr_*.png+# WhatsApp RPC is now an npm dependency (@anthropic/whatsapp-rpc)+# Session data is stored in node_modules/@anthropic/whatsapp-rpc/data/# =============================================================================# Database files (may contain sensitive user data)diff --git a/.npmignore b/.npmignoreindex 4451fd33..9e776c6e 100644--- a/.npmignore+++ b/.npmignore@@ -82,17 +82,8 @@ server/experiments/# Duplicate folderMachinaOS/-# WhatsApp session/temp data-server/whatsapp-rpc/.wwebjs_*/-server/whatsapp-rpc/session/-server/whatsapp-rpc/qr_*.png-server/whatsapp-rpc/data/-# server/whatsapp-rpc/bin/ - INCLUDED (pre-built binaries)--# Built binaries - INCLUDED in npm package (pre-built for each platform)-# The bin/ directory has the pre-built binary, exclude the old build location-server/whatsapp-rpc/server-server/whatsapp-rpc/server.exe+# WhatsApp RPC is now an npm dependency (@anthropic/whatsapp-rpc)+# No local whatsapp-rpc directory to exclude# Temporary files*.tmpdiff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlindex c17fdd86..944d3fbf 100644--- a/docker-compose.prod.yml+++ b/docker-compose.prod.yml@@ -72,12 +72,14 @@ services:depends_on:- backend- # WhatsApp RPC Service (Go API only)+ # WhatsApp RPC Service (npm package with pre-built binaries)whatsapp:build:- context: ./server/whatsapp-rpc- dockerfile: Dockerfile+ context: ./docker+ dockerfile: Dockerfile.whatsappcontainer_name: machina-whatsapp+ ports:+ - "${WHATSAPP_RPC_PORT:-9400}:${WHATSAPP_RPC_PORT:-9400}"volumes:- whatsapp-data:/app/datanetworks:@@ -86,13 +88,14 @@ services:# Privileged mode for proper SQLite WAL mmap supportprivileged: truehealthcheck:- test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9400/health"]+ test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:${WHATSAPP_RPC_PORT:-9400}/health"]interval: 30stimeout: 10sretries: 3start_period: 15senvironment:- TZ=UTC+ - PORT=${WHATSAPP_RPC_PORT:-9400}networks:app-network:diff --git a/docker-compose.yml b/docker-compose.ymlindex 3fd1a9db..ff3af05a 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -68,11 +68,11 @@ services:depends_on:- backend- # WhatsApp RPC Service (Go API)+ # WhatsApp RPC Service (npm package with pre-built binaries)whatsapp:build:- context: ./server/whatsapp-rpc- dockerfile: Dockerfile+ context: ./docker+ dockerfile: Dockerfile.whatsappcontainer_name: machina-whatsappports:- "${WHATSAPP_RPC_PORT:-9400}:${WHATSAPP_RPC_PORT:-9400}"diff --git a/docker/Dockerfile.whatsapp b/docker/Dockerfile.whatsappnew file mode 100644index 00000000..5291eaa6--- /dev/null+++ b/docker/Dockerfile.whatsapp@@ -0,0 +1,23 @@+# WhatsApp RPC Dockerfile+# Uses the npm package @anthropic/whatsapp-rpc with pre-built binaries++FROM node:20-alpine++WORKDIR /app++# Install the whatsapp-rpc package+RUN npm init -y && npm install @trohitg/whatsapp-rpc++# Create data directory for SQLite and QR codes+RUN mkdir -p /app/data++# Set environment variables+ENV NODE_ENV=production+ENV TZ=UTC+ENV PORT=9400++# Expose the RPC port (configurable via PORT env var)+EXPOSE ${PORT}++# Run the RPC server+CMD ["npx", "whatsapp-rpc", "api", "--foreground"]diff --git a/package.json b/package.jsonindex 5c6425a7..d430ee73 100644--- a/package.json+++ b/package.json@@ -48,10 +48,6 @@"!server/.venv/","!server/**/__pycache__/","!server/data/",- "!server/whatsapp-rpc/node_modules/",- "!server/whatsapp-rpc/data/",- "!server/whatsapp-rpc/server",- "!server/whatsapp-rpc/server.exe","!**/node_modules/","!**/.vite/",".env.template",@@ -68,11 +64,10 @@"client:start": "cd client && npm run start","python:start": "cd server && uv run uvicorn main:app --host 127.0.0.1 --port 3010 --reload --reload-dir . --reload-exclude \"*.pyc\" --reload-exclude \"__pycache__\" --log-level warning","temporal:worker": "cd server && uv run python -m services.temporal.worker",- "whatsapp:start": "cd server/whatsapp-rpc && npm start",- "whatsapp:stop": "cd server/whatsapp-rpc && npm stop",- "whatsapp:status": "cd server/whatsapp-rpc && npm run status",- "whatsapp:api": "cd server/whatsapp-rpc && npm run api",- "whatsapp:build": "cd server/whatsapp-rpc && npm run build",+ "whatsapp:start": "whatsapp-rpc start",+ "whatsapp:stop": "whatsapp-rpc stop",+ "whatsapp:status": "whatsapp-rpc status",+ "whatsapp:api": "whatsapp-rpc api --foreground","build": "node scripts/build.js","clean": "node scripts/clean.js","stop": "node scripts/stop.js",@@ -91,6 +86,7 @@"postinstall": "node scripts/postinstall.js"},"dependencies": {+ "@trohitg/whatsapp-rpc": "^0.0.2","concurrently": "^9.2.1","cross-env": "^7.0.3","rimraf": "^6.0.1"diff --git a/scripts/build.js b/scripts/build.jsindex 0ad0b2b7..9c9f15c1 100644--- a/scripts/build.js+++ b/scripts/build.js@@ -111,37 +111,7 @@ function installUv() {}}-function installGo() {- console.log(' Installing Go...');- if (isWindows) {- if (runSilent('winget --version')) {- run('winget install GoLang.Go --accept-package-agreements --accept-source-agreements');- } else if (runSilent('choco --version')) {- run('choco install golang -y');- } else {- console.log(' Error: Please install Go manually from https://go.dev/dl/');- process.exit(1);- }- } else if (isMac) {- if (runSilent('brew --version')) {- run('brew install go');- } else {- console.log(' Error: Please install Homebrew first: https://brew.sh/');- process.exit(1);- }- } else {- if (runSilent('apt --version')) {- run('sudo apt update && sudo apt install -y golang-go');- } else if (runSilent('dnf --version')) {- run('sudo dnf install -y golang');- } else if (runSilent('pacman --version')) {- run('sudo pacman -S --noconfirm go');- } else {- console.log(' Error: Please install Go manually from https://go.dev/dl/');- process.exit(1);- }- }-}+// Go is no longer required - whatsapp-rpc is an npm package with pre-built binaries// ============================================================================// Check and Install Dependencies@@ -197,22 +167,13 @@ if (uvVersion) {}}-// Go-let goVersionFull = getVersion('go version');+// Go is optional (whatsapp-rpc uses pre-built binaries)+const goVersionFull = getVersion('go version');if (goVersionFull) {const goVersion = goVersionFull.match(/go\d+\.\d+(\.\d+)?/)?.[0] || 'go';- console.log(` Go: ${goVersion}`);+ console.log(` Go: ${goVersion} (optional)`);} else {- installGo();- goVersionFull = getVersion('go version');- if (goVersionFull) {- const goVersion = goVersionFull.match(/go\d+\.\d+(\.\d+)?/)?.[0] || 'go';- console.log(` Go: ${goVersion}`);- } else {- console.log(' Error: Failed to install Go. Please install manually.');- console.log(' https://go.dev/dl/');- process.exit(1);- }+ console.log(' Go: not installed (optional - whatsapp-rpc uses pre-built binaries)');}console.log('\nAll dependencies ready.\n');@@ -232,35 +193,27 @@ try {// Step 1: Install root dependencies (skip if postinstall - npm already did this)if (!isPostInstall) {- console.log('[1/6] Installing root dependencies...');+ console.log('[1/4] Installing root dependencies...');npmInstall(ROOT);} else {- console.log('[1/6] Root dependencies already installed by npm');+ console.log('[1/4] Root dependencies already installed by npm');}// Step 2: Install client dependencies- console.log('[2/6] Installing client dependencies...');+ console.log('[2/4] Installing client dependencies...');npmInstall(resolve(ROOT, 'client'));// Step 3: Build client- console.log('[3/6] Building client...');+ console.log('[3/4] Building client...');run('npm run build', resolve(ROOT, 'client'));// Step 4: Install Python dependencies- console.log('[4/6] Installing Python dependencies...');+ console.log('[4/4] Installing Python dependencies...');const serverDir = resolve(ROOT, 'server');run('uv venv', serverDir);run('uv sync', serverDir);- // Step 5: Install WhatsApp dependencies- console.log('[5/6] Installing WhatsApp dependencies...');- const whatsappDir = resolve(ROOT, 'server/whatsapp-rpc');- npmInstall(whatsappDir);-- // Step 6: Build WhatsApp server (Go binary)- console.log('[6/6] Building WhatsApp server...');- run('npm run build', whatsappDir);-+ // WhatsApp is now an npm dependency - binary downloaded via postinstallconsole.log('\nBuild complete.');} catch (err) {diff --git a/scripts/clean.js b/scripts/clean.jsindex 6df45e4d..dfad4815 100644--- a/scripts/clean.js+++ b/scripts/clean.js@@ -15,12 +15,10 @@ const targets = ['client/node_modules','client/dist','client/.vite',- 'server/whatsapp-rpc/node_modules',- 'server/whatsapp-rpc/bin',- 'server/whatsapp-rpc/data','server/data','server/.venv',];+// Note: whatsapp-rpc is now an npm dependency, not a local directoryconsole.log('Cleaning...');diff --git a/scripts/download-binaries.js b/scripts/download-binaries.jsdeleted file mode 100644index 4a017190..00000000--- a/scripts/download-binaries.js+++ /dev/null@@ -1,178 +0,0 @@-#!/usr/bin/env node-/**- * Optional binary download script for MachinaOS.- * Downloads pre-built WhatsApp RPC server binary from GitHub Releases.- *- * Skipped if:- * - MACHINAOS_SKIP_BINARY_DOWNLOAD=1- * - CI environment (CI=true)- * - Go is installed (can build from source)- *- * Force download even if Go installed:- * - MACHINAOS_FORCE_BINARY_DOWNLOAD=1- */-import { execSync } from 'child_process';-import { createWriteStream, existsSync, mkdirSync, chmodSync, readFileSync } from 'fs';-import { resolve, dirname } from 'path';-import { fileURLToPath } from 'url';-import https from 'https';--const __dirname = dirname(fileURLToPath(import.meta.url));-const ROOT = resolve(__dirname, '..');-const WHATSAPP_BIN_DIR = resolve(ROOT, 'server/whatsapp-rpc/bin');--// Read version from package.json-const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf-8'));-const VERSION = pkg.version;--// GitHub release URL-const GITHUB_REPO = 'trohitg/MachinaOS';-const BASE_URL = `https://github.com/${GITHUB_REPO}/releases/download/v${VERSION}`;--// Platform detection-function getPlatformInfo() {- const osMap = { 'win32': 'windows', 'darwin': 'darwin', 'linux': 'linux' };- const archMap = { 'x64': 'amd64', 'arm64': 'arm64' };-- const os = osMap[process.platform];- const goarch = archMap[process.arch];-- if (!os || !goarch) {- return null;- }-- const ext = process.platform === 'win32' ? '.exe' : '';- return { os, goarch, ext };-}--// Check if Go is installed-function hasGo() {- try {- execSync('go version', { stdio: 'ignore' });- return true;- } catch {- return false;- }-}--// Download file with redirect handling-function downloadFile(url, dest) {- return new Promise((resolve, reject) => {- const request = (currentUrl, redirectCount = 0) => {- if (redirectCount > 5) {- reject(new Error('Too many redirects'));- return;- }-- const client = currentUrl.startsWith('https') ? https : require('http');-- client.get(currentUrl, (response) => {- // Handle redirects (GitHub releases redirect to CDN)- if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {- request(response.headers.location, redirectCount + 1);- return;- }-- if (response.statusCode !== 200) {- reject(new Error(`HTTP ${response.statusCode}`));- return;- }-- const file = createWriteStream(dest);- const totalBytes = parseInt(response.headers['content-length'], 10);- let downloadedBytes = 0;-- response.on('data', (chunk) => {- downloadedBytes += chunk.length;- if (totalBytes) {- const percent = ((downloadedBytes / totalBytes) * 100).toFixed(1);- process.stdout.write(`\r Downloading: ${percent}%`);- }- });-- response.pipe(file);- file.on('finish', () => {- file.close();- console.log(' Done');- resolve();- });- file.on('error', (err) => {- file.close();- reject(err);- });- }).on('error', reject);- };-- request(url);- });-}--// Main-async function main() {- // Skip conditions- if (process.env.MACHINAOS_SKIP_BINARY_DOWNLOAD === '1') {- console.log('Skipping binary download (MACHINAOS_SKIP_BINARY_DOWNLOAD=1)');- return;- }-- if (process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true') {- console.log('Skipping binary download (CI environment)');- return;- }-- // Check if Go is installed - prefer source build- if (hasGo()) {- if (process.env.MACHINAOS_FORCE_BINARY_DOWNLOAD !== '1') {- console.log('Go is installed - will build from source');- return;- }- console.log('Go is installed but MACHINAOS_FORCE_BINARY_DOWNLOAD=1, downloading anyway');- }-- const platformInfo = getPlatformInfo();- if (!platformInfo) {- console.log(`Unsupported platform: ${process.platform}/${process.arch}`);- return;- }-- const { os, goarch, ext } = platformInfo;- const binaryName = `whatsapp-rpc-server-${os}-${goarch}${ext}`;- const downloadUrl = `${BASE_URL}/${binaryName}`;- const destPath = resolve(WHATSAPP_BIN_DIR, `whatsapp-rpc-server${ext}`);-- console.log(`\nDownloading pre-built WhatsApp RPC binary...`);- console.log(` Version: v${VERSION}`);- console.log(` Platform: ${os}/${goarch}`);-- // Create bin directory- if (!existsSync(WHATSAPP_BIN_DIR)) {- mkdirSync(WHATSAPP_BIN_DIR, { recursive: true });- }-- // Check if binary already exists- if (existsSync(destPath)) {- console.log(` Binary already exists: ${destPath}`);- return;- }-- // Download binary- try {- await downloadFile(downloadUrl, destPath);- } catch (error) {- console.error(`\nFailed to download binary: ${error.message}`);- console.log('Will attempt to build from source instead.');- return;- }-- // Set executable permission (Unix only)- if (process.platform !== 'win32') {- chmodSync(destPath, 0o755);- }-- console.log(`Binary downloaded: ${destPath}`);-}--main().catch((err) => {- // Don't fail the install - just log and continue- console.error('Binary download error:', err.message);-});diff --git a/scripts/install.js b/scripts/install.jsindex 27c62201..2b036590 100644--- a/scripts/install.js+++ b/scripts/install.js@@ -3,13 +3,20 @@* MachinaOS Installation Script** Called by postinstall.js after npm install.- * Installs all dependencies including Python, uv, and builds the project.+ * Installs all dependencies including Python and uv.+ * WhatsApp RPC is now an npm dependency with pre-built binaries.*/import { execSync } from 'child_process';import { existsSync, copyFileSync } from 'fs';import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';+// Prevent recursive execution when npm install runs in subdirectories+if (process.env.MACHINAOS_INSTALLING === 'true') {+ process.exit(0);+}+process.env.MACHINAOS_INSTALLING = 'true';+const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');@@ -19,7 +26,13 @@ const isMac = process.platform === 'darwin';process.env.PYTHONUTF8 = '1';function run(cmd, cwd = ROOT, timeoutMs = 300000) {- execSync(cmd, { cwd, stdio: 'inherit', shell: true, timeout: timeoutMs });+ execSync(cmd, {+ cwd,+ stdio: 'inherit',+ shell: true,+ timeout: timeoutMs,+ env: { ...process.env, MACHINAOS_INSTALLING: 'true' }+ });}function runSilent(cmd) {@@ -59,11 +72,6 @@ function checkUv() {return getVersion('uv --version');}-function checkGo() {- const version = getVersion('go version');- return version ? { version } : null;-}-function installPython() {console.log('Installing Python 3.11+...');if (isWindows) {@@ -159,12 +167,12 @@ if (uvVersion) {}}-// Check Go (optional)-const go = checkGo();-if (go) {- console.log(` Go: ${go.version}`);+// Go is optional (whatsapp-rpc uses pre-built binaries via npm)+const goVersion = getVersion('go version');+if (goVersion) {+ console.log(` Go: ${goVersion.match(/go\d+\.\d+(\.\d+)?/)?.[0] || 'installed'} (optional)`);} else {- console.log(' Go: not found (using pre-built binary)');+ console.log(' Go: not installed (optional - whatsapp-rpc uses pre-built binaries)');}console.log('');@@ -174,16 +182,12 @@ console.log('');try {const clientDir = resolve(ROOT, 'client');const serverDir = resolve(ROOT, 'server');- const whatsappDir = resolve(ROOT, 'server/whatsapp-rpc');const clientDistExists = existsSync(resolve(clientDir, 'dist', 'index.html'));- const binPath = resolve(whatsappDir, 'bin', isWindows ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server');- const binExists = existsSync(binPath);// Calculate total stepslet totalSteps = 1; // .env alwaysif (!clientDistExists) totalSteps += 2; // client deps + buildtotalSteps += 1; // Python deps always- if (!binExists) totalSteps += 1; // WhatsApp setup if no binarylet step = 0;// Create .env if needed@@ -218,26 +222,11 @@ try {run('uv venv', serverDir); // 5 min defaultrun('uv sync', serverDir, 600000); // 10 min timeout- // WhatsApp service - skip if binary already exists (pre-built in npm package)- if (binExists) {- console.log(`[SKIP] WhatsApp binary already exists`);- } else {- step++;- console.log(`[${step}/${totalSteps}] Setting up WhatsApp service...`);- run('npm install', whatsappDir); // 5 min default-- // Try to build from source if Go is available- if (go) {- console.log(' Building WhatsApp from source...');- run('npm run build', whatsappDir);- } else {- console.log(' WhatsApp binary not found and Go not available');- console.log(' WhatsApp features will not work until binary is provided');- }- }-+ // WhatsApp RPC is now an npm dependency - binary downloaded via postinstallconsole.log('');console.log('Done!');+ console.log('');+ console.log('WhatsApp RPC installed as npm dependency (@trohitg/whatsapp-rpc)');} catch (err) {console.log('');diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 0beadc18..b3f6d0a5 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -2,9 +2,8 @@/*** Postinstall script for MachinaOS.*- * Runs:- * 1. download-binaries.js (download pre-built WhatsApp binary)- * 2. install.js (check deps, install npm/Python packages, build)+ * Runs install.js to check deps, install npm/Python packages, build.+ * WhatsApp RPC is now an npm dependency - binary downloaded by its own postinstall.*/import { spawn } from 'child_process';import { resolve, dirname } from 'path';@@ -47,17 +46,8 @@ function runScript(scriptPath) {async function main() {try {- // Download pre-built binaries (optional, non-fatal)- console.log('[1/2] Downloading pre-built binaries...');- try {- await runScript(resolve(__dirname, 'download-binaries.js'));- } catch (e) {- console.log(' Skipped (will build from source if Go available)');- }-// Run full installation- console.log('');- console.log('[2/2] Installing...');+ console.log('Installing dependencies...');await runScript(resolve(__dirname, 'install.js'));console.log('');diff --git a/server/whatsapp-rpc/.dockerignore b/server/whatsapp-rpc/.dockerignoredeleted file mode 100644index 87bf5fb7..00000000--- a/server/whatsapp-rpc/.dockerignore+++ /dev/null@@ -1,30 +0,0 @@-# Git-.git-.gitignore--# Build artifacts-bin/-*.exe--# Data (mounted as volume)-data/--# Node modules-node_modules/--# Python cache-__pycache__/-*.pyc-*.pyo-.pytest_cache/--# IDE-.vscode/-.idea/--# Docs-*.md-!README.md--# Plans-.claude/diff --git a/server/whatsapp-rpc/.gitignore b/server/whatsapp-rpc/.gitignoredeleted file mode 100644index 42cd6a2e..00000000--- a/server/whatsapp-rpc/.gitignore+++ /dev/null@@ -1,35 +0,0 @@-# Build artifacts-*.exe-whatsapp-rpc--# Runtime data-data/--# Node-node_modules/-package-lock.json--# Python-__pycache__/-*.pyc-*.pyo-.venv/-venv/-.env--# IDE-.idea/-.vscode/-*.swp-*.swo--# OS-.DS_Store-Thumbs.db--# Logs-*.log--# Claude-CLAUDE.md-.claude/diff --git a/server/whatsapp-rpc/Dockerfile b/server/whatsapp-rpc/Dockerfiledeleted file mode 100644index 356452ab..00000000--- a/server/whatsapp-rpc/Dockerfile+++ /dev/null@@ -1,44 +0,0 @@-# Build stage-FROM golang:1.24-alpine AS builder--WORKDIR /app--# Install build dependencies-RUN apk add --no-cache git--# Copy go mod files-COPY go.mod go.sum ./-RUN go mod download--# Copy source code-COPY src/go/ ./src/go/--# Build binary-RUN CGO_ENABLED=0 GOOS=linux go build -o whatsapp-rpc-server ./src/go/cmd/server--# Runtime stage-FROM alpine:latest--WORKDIR /app--# Install ca-certificates for HTTPS-RUN apk add --no-cache ca-certificates tzdata--# Create data directories-RUN mkdir -p /app/data/qr /app/configs--# Copy binary from builder-COPY --from=builder /app/whatsapp-rpc-server .--# Copy config if exists-COPY configs/config.yaml ./configs/--# Expose WebSocket port-EXPOSE 9400--# Health check-HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \- CMD wget --no-verbose --tries=1 --spider http://localhost:9400/health || exit 1--# Run server-CMD ["./whatsapp-rpc-server"]diff --git a/server/whatsapp-rpc/Dockerfile.web b/server/whatsapp-rpc/Dockerfile.webdeleted file mode 100644index c6dc2d7c..00000000--- a/server/whatsapp-rpc/Dockerfile.web+++ /dev/null@@ -1,17 +0,0 @@-# Python Web UI-FROM python:3.11-slim--WORKDIR /app--# Install dependencies-COPY web/requirements.txt ./-RUN pip install --no-cache-dir -r requirements.txt--# Copy web app-COPY web/ ./--# Expose port-EXPOSE 5000--# Run Flask app-CMD ["python", "app.py"]diff --git a/server/whatsapp-rpc/README.md b/server/whatsapp-rpc/README.mddeleted file mode 100644index 3a79bae7..00000000--- a/server/whatsapp-rpc/README.md+++ /dev/null@@ -1,139 +0,0 @@-# WhatsApp RPC--WebSocket JSON-RPC 2.0 API for WhatsApp.--<img width="1280" height="676" alt="image" src="https://github.com/user-attachments/assets/ddc7324a-8c4d-4557-ac6f-cb091a8ce31f" />--## Architecture--```-┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐-│ Your App │ │ Web UI │ │ Python Client │-│ (Any Language) │ │ (Flask) │ │ Library │-└────────┬────────┘ └────────┬────────┘ └────────┬────────┘- │ │ │- │ WebSocket │ HTTP │- │ JSON-RPC 2.0 │ :5000 │- │ │ │- └───────────┬───────────┴───────────────────────┘- │- ▼- ┌───────────────────────┐- │ Go WebSocket API │- │ :9400 │- │ ┌─────────────────┐ │- │ │ RPC Handler │ │- │ │ Rate Limiter │ │- │ │ Event Emitter │ │- │ └────────┬────────┘ │- └───────────┼───────────┘- │- ▼- ┌───────────────────────┐- │ WhatsApp Service │- │ ┌─────────────────┐ │- │ │ whatsmeow │ │- │ │ (Go Library) │ │- │ └────────┬────────┘ │- └───────────┼───────────┘- │- ▼- ┌───────────────────────┐- │ WhatsApp Servers │- └───────────────────────┘--Data Storage:-┌─────────────────────────────────┐-│ data/ │-│ ├── whatsapp.db (SQLite) │-│ ├── qr/*.png (QR codes) │-│ └── groups.json (Group cache)│-└─────────────────────────────────┘-```--## Setup--### Native-```bash-npm start # Start API + Web UI-npm stop # Stop all-npm run restart # Restart all-npm run status # Check if running-npm run api # Start API only-npm run web # Start Web UI only-npm run build # Build Go binary-npm run clean # Full cleanup (bin, data, node_modules)-```--All commands auto-install dependencies if missing.--### Docker-```bash-docker-compose up -d # Start-docker-compose down # Stop-docker-compose logs -f # View logs-```--## Endpoints--| Port | Service |-|------|---------|-| 9400 | WebSocket API - `ws://localhost:9400/ws/rpc` |-| 5000 | Web UI - `http://localhost:5000` |--## API--Connect via WebSocket and send JSON-RPC 2.0 requests:--```json-{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {"phone": "1234567890", "type": "text", "message": "Hello"}}-```--### Methods--| Method | Params | Description |-|--------|--------|-------------|-| `status` | - | Connection status |-| `start` | - | Start WhatsApp |-| `stop` | - | Stop WhatsApp |-| `restart` | - | Full reset (logout, delete DB, new QR) |-| `qr` | - | Get QR code (base64 PNG) |-| `send` | `phone/group_id`, `type`, `message/media_data` | Send message |-| `media` | `message_id` | Download received media |-| `groups` | - | List all groups |-| `group_info` | `group_id` | Get group details |-| `contact_check` | `phones[]` | Check if numbers are on WhatsApp |--Full schema: [schema.json](schema.json)--## Events--Server pushes events as JSON-RPC notifications (no `id`):--```json-{"jsonrpc": "2.0", "method": "event.message_received", "params": {...}}-```--Events: `connected`, `disconnected`, `qr_code`, `message_received`, `message_sent`--## Data Files--- `data/whatsapp.db` - SQLite database (session, contacts)-- `data/qr/*.png` - QR code images-- `data/groups.json` - Auto-generated on connection (indexed group data)--## Structure--```-src/go/ # Go backend-src/python/ # Python client library-web/ # Flask web UI-scripts/ # CLI tools-configs/ # YAML config-```--## Requirements--- Go 1.21+-- Python 3.8+-- Node.js 16+diff --git a/server/whatsapp-rpc/cli.js b/server/whatsapp-rpc/cli.jsdeleted file mode 100644index 03c346ce..00000000--- a/server/whatsapp-rpc/cli.js+++ /dev/null@@ -1,95 +0,0 @@-#!/usr/bin/env node-import { program } from 'commander';-import chalk from 'chalk';-import { execa } from 'execa';-import killPort from 'kill-port';-import { Socket } from 'net';-import { execSync, spawn } from 'child_process';-import { existsSync, statSync, unlinkSync, readdirSync } from 'fs';-import { dirname, join } from 'path';-import { fileURLToPath } from 'url';--const __dirname = dirname(fileURLToPath(import.meta.url));-const API_PORT = 9400, WEB_PORT = 5000;-const BIN = process.platform === 'win32' ? 'whatsapp-rpc.exe' : 'whatsapp-rpc';--const log = (m, c = 'blue') => console.log(chalk[c](m));-const sleep = ms => new Promise(r => setTimeout(r, ms));--const portUp = port => new Promise(r => {- const s = new Socket();- s.setTimeout(2000);- s.on('connect', () => { s.destroy(); r(true); });- s.on('timeout', () => { s.destroy(); r(false); });- s.on('error', () => r(false));- s.connect(port, '127.0.0.1');-});--const wait = async (port, ms = 10000) => {- const t = Date.now();- while (Date.now() - t < ms) { if (await portUp(port)) return true; await sleep(500); }- return false;-};--const kill = async (port, name) => {- try { await killPort(port); log(`${name} stopped`, 'green'); }- catch { log(`${name} not running`, 'yellow'); }-};--const py = () => {- try { execSync('python --version', { stdio: 'ignore' }); return 'python'; }- catch { try { execSync('python3 --version', { stdio: 'ignore' }); return 'python3'; } catch { return null; } }-};--async function api() {- if (await portUp(API_PORT)) { log(`API already on ${API_PORT}`, 'yellow'); return; }- const bin = join(__dirname, BIN);- if (!existsSync(bin)) { log('Building...', 'yellow'); await build(); }- spawn(bin, [], { cwd: __dirname, detached: true, stdio: 'ignore' }).unref();- if (await wait(API_PORT)) log(`API: ws://localhost:${API_PORT}/ws/rpc`, 'green');- else log('API failed to start', 'red');-}--async function web() {- if (await portUp(WEB_PORT)) { log(`Web already on ${WEB_PORT}`, 'yellow'); return; }- const p = py(); if (!p) { log('Python not found', 'red'); return; }- if (!await portUp(API_PORT)) log('Warning: API not running', 'yellow');- spawn(p, ['app.py'], { cwd: join(__dirname, 'web'), detached: true, stdio: 'ignore' }).unref();- if (await wait(WEB_PORT)) log(`Web: http://localhost:${WEB_PORT}`, 'green');- else log('Web failed to start', 'red');-}--async function start() { await api(); await sleep(1000); await web(); }-async function stop() { await kill(API_PORT, 'API'); await kill(WEB_PORT, 'Web'); }--async function status() {- const a = await portUp(API_PORT), w = await portUp(WEB_PORT);- log(`API (${API_PORT}): ${a ? 'UP' : 'DOWN'}`, a ? 'green' : 'red');- log(`Web (${WEB_PORT}): ${w ? 'UP' : 'DOWN'}`, w ? 'green' : 'red');-}--async function build() {- const bin = join(__dirname, BIN);- if (existsSync(bin)) unlinkSync(bin);- await execa('go', ['build', '-o', BIN, '.'], { cwd: __dirname, stdio: 'inherit' });- log(`Built: ${BIN} (${(statSync(bin).size / 1024 / 1024).toFixed(1)}MB)`, 'green');-}--async function clean() {- const bin = join(__dirname, BIN);- if (existsSync(bin)) { unlinkSync(bin); log(`Removed ${BIN}`, 'green'); }- readdirSync(__dirname).filter(f => f.startsWith('qr_') && f.endsWith('.png')).forEach(f => {- unlinkSync(join(__dirname, f)); log(`Removed ${f}`, 'green');- });-}--program.name('wa').version('1.0.0');-program.command('start').description('Start all').action(start);-program.command('stop').description('Stop all').action(stop);-program.command('restart').description('Restart all').action(async () => { await stop(); await sleep(1000); await start(); });-program.command('status').description('Status').action(status);-program.command('api').description('Start API only').action(api);-program.command('web').description('Start Web only').action(web);-program.command('build').description('Build binary').action(build);-program.command('clean').description('Clean artifacts').action(clean);-program.parse();diff --git a/server/whatsapp-rpc/configs/config.yaml b/server/whatsapp-rpc/configs/config.yamldeleted file mode 100644index 88491512..00000000--- a/server/whatsapp-rpc/configs/config.yaml+++ /dev/null@@ -1,7 +0,0 @@-environment: "development"-log_level: 4-server:- port: 9400- host: "0.0.0.0"-database:- path: "data/whatsapp.db"\ No newline at end of filediff --git a/server/whatsapp-rpc/docker-compose.yml b/server/whatsapp-rpc/docker-compose.ymldeleted file mode 100644index f24bb078..00000000--- a/server/whatsapp-rpc/docker-compose.yml+++ /dev/null@@ -1,35 +0,0 @@-services:- api:- build: .- container_name: whatsapp-rpc-api- ports:- - "9400:9400"- volumes:- - ./data:/app/data- - ./configs:/app/configs- environment:- - WA_SERVER_PORT=9400- - WA_DATABASE_PATH=data/whatsapp.db- restart: unless-stopped- healthcheck:- test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9400/health"]- interval: 30s- timeout: 10s- retries: 3-- web:- build:- context: .- dockerfile: Dockerfile.web- container_name: whatsapp-rpc-web- ports:- - "5000:5000"- environment:- - GO_WS_RPC_URL=ws://api:9400/ws/rpc- depends_on:- api:- condition: service_healthy- restart: unless-stopped--volumes:- data:diff --git a/server/whatsapp-rpc/docs/API.md b/server/whatsapp-rpc/docs/API.mddeleted file mode 100644index cbdfc261..00000000--- a/server/whatsapp-rpc/docs/API.md+++ /dev/null@@ -1,410 +0,0 @@-# WhatsApp RPC API--## Connection--```-ws://localhost:9400/ws/rpc-```--All requests use JSON-RPC 2.0 format:-```json-{"jsonrpc": "2.0", "id": 1, "method": "METHOD_NAME", "params": {...}}-```--## Quick Examples--### Send Text Message-```json-{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {- "phone": "919876543210",- "type": "text",- "message": "Hello!"-}}-```--### Send to Group-```json-{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {- "group_id": "[email protected]",- "type": "text",- "message": "Hello group!"-}}-```--### Send Image-```json-{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {- "phone": "919876543210",- "type": "image",- "media_data": {- "data": "BASE64_IMAGE_DATA",- "mime_type": "image/jpeg",- "caption": "Check this out"- }-}}-```--### Send Document-```json-{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {- "phone": "919876543210",- "type": "document",- "media_data": {- "data": "BASE64_FILE_DATA",- "mime_type": "application/pdf",- "filename": "report.pdf"- }-}}-```--### Send Location-```json-{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {- "phone": "919876543210",- "type": "location",- "location": {- "latitude": 37.7749,- "longitude": -122.4194,- "name": "San Francisco",- "address": "California, USA"- }-}}-```--### Reply to Message-```json-{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {- "phone": "919876543210",- "type": "text",- "message": "This is a reply",- "reply": {- "message_id": "ABC123",- "sender": "[email protected]",- "content": "Original message text"- }-}}-```-------## All Methods--### Connection--#### `status`-Get connection status.-```json-{"jsonrpc": "2.0", "id": 1, "method": "status", "params": {}}-```-Response:-```json-{- "connected": true,- "has_session": true,- "running": true,- "pairing": false,- "device_id": "[email protected]"-}-```--#### `start`-Start WhatsApp service.-```json-{"jsonrpc": "2.0", "id": 1, "method": "start", "params": {}}-```--#### `stop`-Stop WhatsApp service.-```json-{"jsonrpc": "2.0", "id": 1, "method": "stop", "params": {}}-```--#### `restart`-Full reset: logout, delete database, generate new QR.-```json-{"jsonrpc": "2.0", "id": 1, "method": "restart", "params": {}}-```--#### `qr`-Get QR code for pairing.-```json-{"jsonrpc": "2.0", "id": 1, "method": "qr", "params": {}}-```-Response:-```json-{- "has_qr": true,- "code": "QR_STRING",- "filename": "data/qr/qr_123.png",- "image_data": "BASE64_PNG"-}-```-------### Messaging--#### `send`-Send message (text, image, video, audio, document, sticker, location, contact).--| Param | Type | Required | Description |-|-------|------|----------|-------------|-| `phone` | string | * | Phone number (without +) |-| `group_id` | string | * | Group JID (e.g., `[email protected]`) |-| `type` | string | Yes | `text`, `image`, `video`, `audio`, `document`, `sticker`, `location`, `contact` |-| `message` | string | For text | Text content |-| `media_data` | object | For media | `{data, mime_type, filename?, caption?, thumbnail?}` |-| `location` | object | For location | `{latitude, longitude, name?, address?}` |-| `contact` | object | For contact | `{display_name, vcard}` |-| `reply` | object | Optional | `{message_id, sender, content}` |--*Either `phone` or `group_id` required.--#### `media`-Download media from received message.-```json-{"jsonrpc": "2.0", "id": 1, "method": "media", "params": {- "message_id": "ABC123DEF456"-}}-```-Response:-```json-{- "data": "BASE64_MEDIA_DATA",- "mime_type": "image/jpeg"-}-```-------### Groups--#### `groups`-List all groups.-```json-{"jsonrpc": "2.0", "id": 1, "method": "groups", "params": {}}-```--#### `group_info`-Get group details.-```json-{"jsonrpc": "2.0", "id": 1, "method": "group_info", "params": {- "group_id": "[email protected]"-}}-```-Response:-```json-{- "jid": "[email protected]",- "name": "Group Name",- "topic": "Description",- "owner": "[email protected]",- "size": 25,- "participants": [- {"jid": "...", "phone": "919876543210", "is_admin": true, "is_super_admin": true}- ]-}-```--#### `group_participants_add`-Add members to group.-```json-{"jsonrpc": "2.0", "id": 1, "method": "group_participants_add", "params": {- "group_id": "[email protected]",- "participants": ["919876543210", "918765432109"]-}}-```--#### `group_participants_remove`-Remove members from group.-```json-{"jsonrpc": "2.0", "id": 1, "method": "group_participants_remove", "params": {- "group_id": "[email protected]",- "participants": ["919876543210"]-}}-```--#### `group_invite_link`-Get group invite link.-```json-{"jsonrpc": "2.0", "id": 1, "method": "group_invite_link", "params": {- "group_id": "[email protected]"-}}-```-------### Contacts--#### `contact_check`-Check if numbers are on WhatsApp.-```json-{"jsonrpc": "2.0", "id": 1, "method": "contact_check", "params": {- "phones": ["919876543210", "918765432109"]-}}-```-Response:-```json-[- {"query": "919876543210", "jid": "[email protected]", "is_registered": true, "is_business": false},- {"query": "918765432109", "is_registered": false}-]-```--#### `contact_profile_pic`-Get profile picture.-```json-{"jsonrpc": "2.0", "id": 1, "method": "contact_profile_pic", "params": {- "jid": "[email protected]"-}}-```-------### Presence--#### `typing`-Send typing indicator.-```json-{"jsonrpc": "2.0", "id": 1, "method": "typing", "params": {- "jid": "[email protected]",- "state": "composing"-}}-```-States: `composing`, `paused`--#### `presence`-Set online status.-```json-{"jsonrpc": "2.0", "id": 1, "method": "presence", "params": {- "status": "available"-}}-```-Status: `available`, `unavailable`--#### `mark_read`-Mark messages as read.-```json-{"jsonrpc": "2.0", "id": 1, "method": "mark_read", "params": {- "message_ids": ["ABC123", "DEF456"],- "chat_jid": "[email protected]"-}}-```-------### Rate Limiting--#### `rate_limit_get`-Get rate limit config and stats.-```json-{"jsonrpc": "2.0", "id": 1, "method": "rate_limit_get", "params": {}}-```--#### `rate_limit_set`-Update rate limit config.-```json-{"jsonrpc": "2.0", "id": 1, "method": "rate_limit_set", "params": {- "enabled": true,- "min_delay_ms": 3000,- "max_messages_per_hour": 60,- "simulate_typing": true-}}-```-------## Events--Server pushes events as JSON-RPC notifications (no `id` field):--### `event.connected`-```json-{"jsonrpc": "2.0", "method": "event.connected", "params": {- "status": "connected",- "device_id": "[email protected]"-}}-```--### `event.disconnected`-```json-{"jsonrpc": "2.0", "method": "event.disconnected", "params": {- "status": "disconnected",- "reason": "..."-}}-```--### `event.qr_code`-```json-{"jsonrpc": "2.0", "method": "event.qr_code", "params": {- "code": "QR_STRING",- "filename": "data/qr/qr_123.png",- "image_data": "BASE64_PNG"-}}-```--### `event.message_received`-```json-{"jsonrpc": "2.0", "method": "event.message_received", "params": {- "message_id": "ABC123",- "sender": "[email protected]",- "chat_id": "[email protected]",- "is_from_me": false,- "is_group": false,- "message_type": "text",- "text": "Hello!",- "timestamp": "2025-01-15T10:30:00Z"-}}-```--### `event.message_sent`-```json-{"jsonrpc": "2.0", "method": "event.message_sent", "params": {- "message_id": "XYZ789",- "to": "[email protected]",- "type": "text",- "timestamp": "2025-01-15T10:30:00Z"-}}-```-------## Error Codes--| Code | Description |-|------|-------------|-| -32700 | Parse error - Invalid JSON |-| -32600 | Invalid Request |-| -32601 | Method not found |-| -32602 | Invalid params |-| -32000 | Server error (WhatsApp operation failed) |-| -32001 | No QR available |-------## Data Files--| File | Description |-|------|-------------|-| `data/whatsapp.db` | SQLite database (session, messages) |-| `data/qr/*.png` | QR code images |-| `data/groups.json` | Auto-generated group data (on connection) |--The `groups.json` file is indexed for fast lookups:-```json-{- "generated_at": "2025-01-15T10:30:00Z",- "device_id": "[email protected]",- "groups": {- "[email protected]": {- "name": "Group Name",- "participants": {- "919876543210": {"phone": "919876543210", "is_admin": true}- }- }- },- "phone_to_groups": {- "919876543210": ["[email protected]", "[email protected]"]- }-}-```diff --git a/server/whatsapp-rpc/go.mod b/server/whatsapp-rpc/go.moddeleted file mode 100644index 753e0add..00000000--- a/server/whatsapp-rpc/go.mod+++ /dev/null@@ -1,67 +0,0 @@-module whatsapp-rpc--go 1.24.0--require (- github.com/gin-gonic/gin v1.9.1- github.com/gorilla/websocket v1.5.3- github.com/sirupsen/logrus v1.9.3- github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e- github.com/spf13/viper v1.21.0- go.mau.fi/whatsmeow v0.0.0-20251120135021-071293c6b9f0- google.golang.org/protobuf v1.36.10- modernc.org/sqlite v1.40.1-)--require (- filippo.io/edwards25519 v1.1.0 // indirect- github.com/beeper/argo-go v1.1.2 // indirect- github.com/bytedance/sonic v1.9.1 // indirect- github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect- github.com/coder/websocket v1.8.14 // indirect- github.com/dustin/go-humanize v1.0.1 // indirect- github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect- github.com/fsnotify/fsnotify v1.9.0 // indirect- github.com/gabriel-vasile/mimetype v1.4.2 // indirect- github.com/gin-contrib/sse v0.1.0 // indirect- github.com/go-playground/locales v0.14.1 // indirect- github.com/go-playground/universal-translator v0.18.1 // indirect- github.com/go-playground/validator/v10 v10.14.0 // indirect- github.com/go-viper/mapstructure/v2 v2.4.0 // indirect- github.com/goccy/go-json v0.10.2 // indirect- github.com/google/uuid v1.6.0 // indirect- github.com/json-iterator/go v1.1.12 // indirect- github.com/klauspost/cpuid/v2 v2.2.4 // indirect- github.com/leodido/go-urn v1.2.4 // indirect- github.com/mattn/go-colorable v0.1.14 // indirect- github.com/mattn/go-isatty v0.0.20 // indirect- github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect- github.com/modern-go/reflect2 v1.0.2 // indirect- github.com/ncruces/go-strftime v0.1.9 // indirect- github.com/pelletier/go-toml/v2 v2.2.4 // indirect- github.com/petermattis/goid v0.0.0-20250904145737-900bdf8bb490 // indirect- github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect- github.com/rs/zerolog v1.34.0 // indirect- github.com/sagikazarmark/locafero v0.11.0 // indirect- github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect- github.com/spf13/afero v1.15.0 // indirect- github.com/spf13/cast v1.10.0 // indirect- github.com/spf13/pflag v1.0.10 // indirect- github.com/subosito/gotenv v1.6.0 // indirect- github.com/twitchyliquid64/golang-asm v0.15.1 // indirect- github.com/ugorji/go/codec v1.2.11 // indirect- github.com/vektah/gqlparser/v2 v2.5.27 // indirect- go.mau.fi/libsignal v0.2.1 // indirect- go.mau.fi/util v0.9.3 // indirect- go.yaml.in/yaml/v3 v3.0.4 // indirect- golang.org/x/arch v0.3.0 // indirect- golang.org/x/crypto v0.44.0 // indirect- golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect- golang.org/x/net v0.47.0 // indirect- golang.org/x/sys v0.38.0 // indirect- golang.org/x/text v0.31.0 // indirect- gopkg.in/yaml.v3 v3.0.1 // indirect- modernc.org/libc v1.66.10 // indirect- modernc.org/mathutil v1.7.1 // indirect- modernc.org/memory v1.11.0 // indirect-)diff --git a/server/whatsapp-rpc/go.sum b/server/whatsapp-rpc/go.sumdeleted file mode 100644index d3909828..00000000--- a/server/whatsapp-rpc/go.sum+++ /dev/null@@ -1,203 +0,0 @@-filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=-filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=-github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=-github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=-github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=-github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=-github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=-github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=-github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs=-github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4=-github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=-github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=-github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=-github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=-github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=-github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=-github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=-github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=-github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=-github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=-github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg=-github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=-github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=-github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=-github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=-github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=-github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=-github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=-github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=-github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=-github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=-github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=-github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=-github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=-github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=-github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=-github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=-github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=-github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=-github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=-github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=-github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=-github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=-github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=-github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=-github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=-github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=-github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=-github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=-github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=-github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=-github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=-github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=-github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=-github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=-github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=-github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=-github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=-github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=-github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=-github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=-github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=-github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=-github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=-github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=-github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=-github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=-github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=-github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=-github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=-github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=-github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=-github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=-github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=-github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=-github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=-github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=-github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=-github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=-github.com/petermattis/goid v0.0.0-20250904145737-900bdf8bb490 h1:QTvNkZ5ylY0PGgA+Lih+GdboMLY/G9SEGLMEGVjTVA4=-github.com/petermattis/goid v0.0.0-20250904145737-900bdf8bb490/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=-github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=-github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=-github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=-github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=-github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=-github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=-github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=-github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=-github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=-github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=-github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=-github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=-github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=-github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=-github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=-github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=-github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=-github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=-github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=-github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=-github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=-github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=-github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=-github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=-github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=-github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=-github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=-github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=-github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=-github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=-github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=-github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=-github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=-github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=-github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=-github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=-github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=-github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=-github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=-github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=-github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=-github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s=-github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo=-go.mau.fi/libsignal v0.2.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0=-go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU=-go.mau.fi/util v0.9.3 h1:aqNF8KDIN8bFpFbybSk+mEBil7IHeBwlujfyTnvP0uU=-go.mau.fi/util v0.9.3/go.mod h1:krWWfBM1jWTb5f8NCa2TLqWMQuM81X7TGQjhMjBeXmQ=-go.mau.fi/whatsmeow v0.0.0-20251120135021-071293c6b9f0 h1:ZDDLaG7VZ3peRWOsJMCxIhoeYuRGc937DzoUtnShqd0=-go.mau.fi/whatsmeow v0.0.0-20251120135021-071293c6b9f0/go.mod h1:5aYaEa3FF5e5XWsA8Xa80ttUXZvb6HyaBGgo2SfzUkE=-go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=-go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=-golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=-golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=-golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=-golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=-golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=-golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0=-golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0=-golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=-golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=-golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=-golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=-golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=-golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=-golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=-golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=-golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=-golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=-golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=-golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=-google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=-google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=-gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=-gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=-modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=-modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=-modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=-modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=-modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=-modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=-modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=-modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=-modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=-modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=-modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=-modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=-modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=-modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=-modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=-modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=-modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=-modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=-modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=-modernc.org/sqlite v1.40.1 h1:VfuXcxcUWWKRBuP8+BR9L7VnmusMgBNNnBYGEe9w/iY=-modernc.org/sqlite v1.40.1/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE=-modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=-modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=-modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=-modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=-rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=diff --git a/server/whatsapp-rpc/package-lock.json b/server/whatsapp-rpc/package-lock.jsondeleted file mode 100644index d59e77b2..00000000--- a/server/whatsapp-rpc/package-lock.json+++ /dev/null@@ -1,272 +0,0 @@-{- "name": "whatsapp-rpc",- "version": "1.0.0",- "lockfileVersion": 3,- "requires": true,- "packages": {- "": {- "name": "whatsapp-rpc",- "version": "1.0.0",- "dependencies": {- "chalk": "^5.3.0",- "commander": "^11.1.0",- "execa": "^8.0.1",- "kill-port": "^2.0.1"- },- "bin": {- "wa": "scripts/cli.js"- }- },- "node_modules/chalk": {- "version": "5.6.2",- "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",- "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",- "license": "MIT",- "engines": {- "node": "^12.17.0 || ^14.13 || >=16.0.0"- },- "funding": {- "url": "https://github.com/chalk/chalk?sponsor=1"- }- },- "node_modules/commander": {- "version": "11.1.0",- "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz",- "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==",- "license": "MIT",- "engines": {- "node": ">=16"- }- },- "node_modules/cross-spawn": {- "version": "7.0.6",- "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",- "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",- "license": "MIT",- "dependencies": {- "path-key": "^3.1.0",- "shebang-command": "^2.0.0",- "which": "^2.0.1"- },- "engines": {- "node": ">= 8"- }- },- "node_modules/execa": {- "version": "8.0.1",- "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz",- "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==",- "license": "MIT",- "dependencies": {- "cross-spawn": "^7.0.3",- "get-stream": "^8.0.1",- "human-signals": "^5.0.0",- "is-stream": "^3.0.0",- "merge-stream": "^2.0.0",- "npm-run-path": "^5.1.0",- "onetime": "^6.0.0",- "signal-exit": "^4.1.0",- "strip-final-newline": "^3.0.0"- },- "engines": {- "node": ">=16.17"- },- "funding": {- "url": "https://github.com/sindresorhus/execa?sponsor=1"- }- },- "node_modules/get-stream": {- "version": "8.0.1",- "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz",- "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==",- "license": "MIT",- "engines": {- "node": ">=16"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/get-them-args": {- "version": "1.3.2",- "resolved": "https://registry.npmjs.org/get-them-args/-/get-them-args-1.3.2.tgz",- "integrity": "sha512-LRn8Jlk+DwZE4GTlDbT3Hikd1wSHgLMme/+7ddlqKd7ldwR6LjJgTVWzBnR01wnYGe4KgrXjg287RaI22UHmAw==",- "license": "MIT"- },- "node_modules/human-signals": {- "version": "5.0.0",- "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",- "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==",- "license": "Apache-2.0",- "engines": {- "node": ">=16.17.0"- }- },- "node_modules/is-stream": {- "version": "3.0.0",- "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz",- "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==",- "license": "MIT",- "engines": {- "node": "^12.20.0 || ^14.13.1 || >=16.0.0"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/isexe": {- "version": "2.0.0",- "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",- "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",- "license": "ISC"- },- "node_modules/kill-port": {- "version": "2.0.1",- "resolved": "https://registry.npmjs.org/kill-port/-/kill-port-2.0.1.tgz",- "integrity": "sha512-e0SVOV5jFo0mx8r7bS29maVWp17qGqLBZ5ricNSajON6//kmb7qqqNnml4twNE8Dtj97UQD+gNFOaipS/q1zzQ==",- "license": "MIT",- "dependencies": {- "get-them-args": "1.3.2",- "shell-exec": "1.0.2"- },- "bin": {- "kill-port": "cli.js"- }- },- "node_modules/merge-stream": {- "version": "2.0.0",- "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",- "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",- "license": "MIT"- },- "node_modules/mimic-fn": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz",- "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==",- "license": "MIT",- "engines": {- "node": ">=12"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/npm-run-path": {- "version": "5.3.0",- "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz",- "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==",- "license": "MIT",- "dependencies": {- "path-key": "^4.0.0"- },- "engines": {- "node": "^12.20.0 || ^14.13.1 || >=16.0.0"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/npm-run-path/node_modules/path-key": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz",- "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==",- "license": "MIT",- "engines": {- "node": ">=12"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/onetime": {- "version": "6.0.0",- "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz",- "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==",- "license": "MIT",- "dependencies": {- "mimic-fn": "^4.0.0"- },- "engines": {- "node": ">=12"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/path-key": {- "version": "3.1.1",- "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",- "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",- "license": "MIT",- "engines": {- "node": ">=8"- }- },- "node_modules/shebang-command": {- "version": "2.0.0",- "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",- "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",- "license": "MIT",- "dependencies": {- "shebang-regex": "^3.0.0"- },- "engines": {- "node": ">=8"- }- },- "node_modules/shebang-regex": {- "version": "3.0.0",- "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",- "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",- "license": "MIT",- "engines": {- "node": ">=8"- }- },- "node_modules/shell-exec": {- "version": "1.0.2",- "resolved": "https://registry.npmjs.org/shell-exec/-/shell-exec-1.0.2.tgz",- "integrity": "sha512-jyVd+kU2X+mWKMmGhx4fpWbPsjvD53k9ivqetutVW/BQ+WIZoDoP4d8vUMGezV6saZsiNoW2f9GIhg9Dondohg==",- "license": "MIT"- },- "node_modules/signal-exit": {- "version": "4.1.0",- "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",- "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",- "license": "ISC",- "engines": {- "node": ">=14"- },- "funding": {- "url": "https://github.com/sponsors/isaacs"- }- },- "node_modules/strip-final-newline": {- "version": "3.0.0",- "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz",- "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==",- "license": "MIT",- "engines": {- "node": ">=12"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/which": {- "version": "2.0.2",- "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",- "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",- "license": "ISC",- "dependencies": {- "isexe": "^2.0.0"- },- "bin": {- "node-which": "bin/node-which"- },- "engines": {- "node": ">= 8"- }- }- }-}diff --git a/server/whatsapp-rpc/package.json b/server/whatsapp-rpc/package.jsondeleted file mode 100644index 10c518ff..00000000--- a/server/whatsapp-rpc/package.json+++ /dev/null@@ -1,30 +0,0 @@-{- "name": "whatsapp-rpc",- "version": "1.0.0",- "type": "module",- "description": "WhatsApp WebSocket RPC Server",- "bin": { "wa": "scripts/cli.js" },- "scripts": {- "prestart": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",- "start": "node scripts/cli.js start",- "prestop": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",- "stop": "node scripts/cli.js stop",- "prerestart": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",- "restart": "node scripts/cli.js restart",- "prestatus": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",- "status": "node scripts/cli.js status",- "preapi": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",- "api": "node scripts/cli.js api --foreground",- "preweb": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",- "web": "node scripts/cli.js web",- "prebuild": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",- "build": "node -e \"const fs=require('fs'),p=process.platform==='win32'?'.exe':'',d='bin';fs.existsSync(d)||fs.mkdirSync(d);require('child_process').execSync('go build -v -o '+d+'/whatsapp-rpc-server'+p+' ./src/go/cmd/server',{stdio:'inherit'});console.log('Build complete: '+d+'/whatsapp-rpc-server'+p)\"",- "clean": "node scripts/clean.cjs"- },- "dependencies": {- "chalk": "^5.3.0",- "commander": "^11.1.0",- "execa": "^8.0.1",- "kill-port": "^2.0.1"- }-}diff --git a/server/whatsapp-rpc/schema.json b/server/whatsapp-rpc/schema.jsondeleted file mode 100644index 876aa29e..00000000--- a/server/whatsapp-rpc/schema.json+++ /dev/null@@ -1,1294 +0,0 @@-{- "openrpc": "1.3.2",- "info": {- "title": "WhatsApp RPC API",- "version": "1.0.0",- "description": "JSON-RPC 2.0 API over WebSocket for WhatsApp messaging"- },- "servers": [- {- "name": "default",- "url": "ws://localhost:9400/ws/rpc"- }- ],- "methods": [- {- "name": "status",- "summary": "Get WhatsApp connection status",- "params": [],- "result": {- "name": "StatusResult",- "schema": {- "type": "object",- "properties": {- "connected": { "type": "boolean", "description": "Whether WhatsApp is connected" },- "has_session": { "type": "boolean", "description": "Whether a session exists" },- "running": { "type": "boolean", "description": "Whether the service is running" },- "pairing": { "type": "boolean", "description": "Whether pairing is in progress" },- "device_id": { "type": "string", "description": "Device JID if connected" },- "timestamp": { "type": "string", "format": "date-time" }- },- "required": ["connected", "has_session", "running", "pairing", "timestamp"]- }- }- },- {- "name": "start",- "summary": "Start WhatsApp service",- "params": [],- "result": {- "name": "StartResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Started"] }- }- }- }- },- {- "name": "stop",- "summary": "Stop WhatsApp service",- "params": [],- "result": {- "name": "StopResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Stopped"] }- }- }- }- },- {- "name": "restart",- "summary": "Full reset: logout, delete DB, cleanup QR, reinit, start fresh",- "description": "Performs a complete reset: 1) Logout from WhatsApp servers, 2) Shutdown service, 3) Delete device session, 4) Delete database files, 5) Delete QR code files, 6) Reinitialize client, 7) Start pairing",- "params": [],- "result": {- "name": "RestartResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Restarted (session cleared)"] }- }- }- }- },- {- "name": "reset",- "summary": "Reset WhatsApp session (logout and delete credentials)",- "params": [],- "result": {- "name": "ResetResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Reset"] }- }- }- }- },- {- "name": "diagnostics",- "summary": "Get detailed diagnostics information",- "params": [],- "result": {- "name": "DiagnosticsResult",- "schema": {- "type": "object",- "properties": {- "client_connected": { "type": "boolean" },- "client_logged_in": { "type": "boolean" },- "store_has_id": { "type": "boolean" },- "service_running": { "type": "boolean" },- "service_pairing": { "type": "boolean" },- "service_shutdown": { "type": "boolean" },- "events_channel_open": { "type": "boolean" },- "device_store": {- "type": "object",- "properties": {- "device_id": { "type": "string" },- "user": { "type": "string" },- "device": { "type": "integer" },- "server": { "type": "string" }- }- },- "timestamp": { "type": "string", "format": "date-time" }- }- }- }- },- {- "name": "qr",- "summary": "Get current QR code for pairing",- "params": [],- "result": {- "name": "QRResult",- "schema": {- "type": "object",- "properties": {- "has_qr": { "type": "boolean", "enum": [true] },- "code": { "type": "string", "description": "QR code content string" },- "filename": { "type": "string", "description": "PNG file path" },- "image_data": { "type": "string", "description": "Base64-encoded PNG data (for Docker/remote access)" }- },- "required": ["has_qr", "code", "filename"]- }- },- "errors": [- {- "code": -32001,- "message": "No QR available"- }- ]- },- {- "name": "send",- "summary": "Send a WhatsApp message",- "params": [- {- "name": "phone",- "description": "Recipient phone number (without + prefix)",- "schema": { "type": "string" },- "required": false- },- {- "name": "group_id",- "description": "Group JID (e.g., [email protected])",- "schema": { "type": "string" },- "required": false- },- {- "name": "type",- "description": "Message type",- "schema": {- "type": "string",- "enum": ["text", "image", "video", "audio", "document", "sticker", "location", "contact"]- },- "required": true- },- {- "name": "message",- "description": "Text content (for text messages)",- "schema": { "type": "string" },- "required": false- },- {- "name": "media_data",- "description": "Media content (for media messages)",- "schema": { "$ref": "#/components/schemas/MediaData" },- "required": false- },- {- "name": "location",- "description": "Location data (for location messages)",- "schema": { "$ref": "#/components/schemas/LocationData" },- "required": false- },- {- "name": "contact",- "description": "Contact card (for contact messages)",- "schema": { "$ref": "#/components/schemas/ContactCard" },- "required": false- },- {- "name": "reply",- "description": "Reply context for quoting a message",- "schema": { "$ref": "#/components/schemas/ReplyData" },- "required": false- },- {- "name": "metadata",- "description": "Custom metadata key-value pairs",- "schema": { "type": "object", "additionalProperties": { "type": "string" } },- "required": false- }- ],- "result": {- "name": "SendResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Sent"] }- }- }- }- },- {- "name": "media",- "summary": "Download media from a received message",- "params": [- {- "name": "message_id",- "description": "Message ID containing media",- "schema": { "type": "string" },- "required": true- }- ],- "result": {- "name": "MediaResult",- "schema": {- "type": "object",- "properties": {- "data": { "type": "string", "description": "Base64-encoded media data" },- "mime_type": { "type": "string", "description": "MIME type of the media" }- },- "required": ["data", "mime_type"]- }- }- },- {- "name": "groups",- "summary": "List all groups the user is a member of",- "params": [],- "result": {- "name": "GroupsResult",- "schema": {- "type": "array",- "items": { "$ref": "#/components/schemas/GroupInfo" }- }- }- },- {- "name": "group_info",- "summary": "Get detailed information about a specific group",- "params": [- {- "name": "group_id",- "description": "Group JID (e.g., [email protected])",- "schema": { "type": "string" },- "required": true- }- ],- "result": {- "name": "GroupInfoResult",- "schema": { "$ref": "#/components/schemas/GroupInfo" }- }- },- {- "name": "group_update",- "summary": "Update group name and/or description",- "params": [- {- "name": "group_id",- "description": "Group JID",- "schema": { "type": "string" },- "required": true- },- {- "name": "name",- "description": "New group name",- "schema": { "type": "string" },- "required": false- },- {- "name": "topic",- "description": "New group description",- "schema": { "type": "string" },- "required": false- }- ],- "result": {- "name": "GroupUpdateResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Updated"] }- }- }- }- },- {- "name": "contact_check",- "summary": "Check if phone numbers are registered on WhatsApp",- "params": [- {- "name": "phones",- "description": "Array of phone numbers to check (without + prefix)",- "schema": { "type": "array", "items": { "type": "string" } },- "required": true- }- ],- "result": {- "name": "ContactCheckResult",- "schema": {- "type": "array",- "items": {- "type": "object",- "properties": {- "query": { "type": "string", "description": "Original phone number queried" },- "jid": { "type": "string", "description": "WhatsApp JID if registered" },- "is_registered": { "type": "boolean" },- "is_business": { "type": "boolean" },- "business_name": { "type": "string" }- },- "required": ["query", "is_registered"]- }- }- }- },- {- "name": "contact_profile_pic",- "summary": "Get profile picture for a user or group",- "params": [- {- "name": "jid",- "description": "User or group JID",- "schema": { "type": "string" },- "required": true- },- {- "name": "preview",- "description": "Get smaller preview image",- "schema": { "type": "boolean" },- "required": false- }- ],- "result": {- "name": "ProfilePicResult",- "schema": {- "type": "object",- "properties": {- "exists": { "type": "boolean", "description": "Whether profile picture exists" },- "url": { "type": "string", "description": "URL to download image" },- "id": { "type": "string", "description": "Image identifier" },- "data": { "type": "string", "description": "Base64-encoded image data" }- },- "required": ["exists"]- }- }- },- {- "name": "contacts",- "summary": "List all contacts with saved names",- "description": "Returns contacts from the whatsmeow_contacts store with user-saved names",- "params": [- {- "name": "query",- "description": "Optional search query to filter by name or phone number",- "schema": { "type": "string" },- "required": false- }- ],- "result": {- "name": "ContactsResult",- "schema": {- "type": "object",- "properties": {- "contacts": {- "type": "array",- "items": {- "type": "object",- "properties": {- "jid": { "type": "string", "description": "Full JID (e.g., [email protected])" },- "phone": { "type": "string", "description": "Phone number without @s.whatsapp.net" },- "name": { "type": "string", "description": "User's saved contact name (e.g., 'Mummy', 'Dad')" },- "push_name": { "type": "string", "description": "WhatsApp profile name set by user" },- "is_contact": { "type": "boolean", "description": "Whether this is a saved contact" }- }- }- },- "total": { "type": "integer", "description": "Total number of contacts returned" }- },- "required": ["contacts", "total"]- }- }- },- {- "name": "contact_info",- "summary": "Get full information for a single contact",- "description": "Returns comprehensive contact info including name, business status, and profile picture URL",- "params": [- {- "name": "phone",- "description": "Phone number (with or without + prefix)",- "schema": { "type": "string" },- "required": true- }- ],- "result": {- "name": "ContactInfoResult",- "schema": {- "type": "object",- "properties": {- "jid": { "type": "string", "description": "Full JID for sending messages" },- "phone": { "type": "string", "description": "Phone number" },- "name": { "type": "string", "description": "User's saved contact name" },- "push_name": { "type": "string", "description": "WhatsApp profile name" },- "business_name": { "type": "string", "description": "Business account verified name" },- "is_business": { "type": "boolean", "description": "Whether this is a business account" },- "is_contact": { "type": "boolean", "description": "Whether saved in contacts" },- "profile_pic": { "type": "string", "description": "Profile picture URL" }- },- "required": ["jid", "phone"]- }- }- },- {- "name": "typing",- "summary": "Send typing indicator to a chat",- "params": [- {- "name": "jid",- "description": "Chat JID (individual or group)",- "schema": { "type": "string" },- "required": true- },- {- "name": "state",- "description": "Typing state: 'composing' or 'paused'",- "schema": { "type": "string", "enum": ["composing", "paused"] },- "required": true- },- {- "name": "media",- "description": "Media type: '' for text, 'audio' for voice recording",- "schema": { "type": "string", "enum": ["", "text", "audio"] },- "required": false- }- ],- "result": {- "name": "TypingResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Typing indicator sent"] }- }- }- }- },- {- "name": "presence",- "summary": "Set online/offline presence status",- "params": [- {- "name": "status",- "description": "Presence status: 'available' or 'unavailable'",- "schema": { "type": "string", "enum": ["available", "unavailable"] },- "required": true- }- ],- "result": {- "name": "PresenceResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Presence set"] }- }- }- }- },- {- "name": "mark_read",- "summary": "Mark messages as read",- "params": [- {- "name": "message_ids",- "description": "Array of message IDs to mark as read",- "schema": { "type": "array", "items": { "type": "string" } },- "required": true- },- {- "name": "chat_jid",- "description": "Chat JID where messages are from",- "schema": { "type": "string" },- "required": true- },- {- "name": "sender_jid",- "description": "Sender JID (required for group messages)",- "schema": { "type": "string" },- "required": false- }- ],- "result": {- "name": "MarkReadResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string", "enum": ["Messages marked as read"] }- }- }- }- },- {- "name": "group_participants_add",- "summary": "Add participants to a group",- "params": [- {- "name": "group_id",- "description": "Group JID (e.g., [email protected])",- "schema": { "type": "string" },- "required": true- },- {- "name": "participants",- "description": "Array of phone numbers or JIDs to add",- "schema": { "type": "array", "items": { "type": "string" } },- "required": true- }- ],- "result": {- "name": "GroupParticipantsAddResult",- "schema": { "$ref": "#/components/schemas/GroupParticipantsResult" }- }- },- {- "name": "group_participants_remove",- "summary": "Remove participants from a group",- "params": [- {- "name": "group_id",- "description": "Group JID (e.g., [email protected])",- "schema": { "type": "string" },- "required": true- },- {- "name": "participants",- "description": "Array of phone numbers or JIDs to remove",- "schema": { "type": "array", "items": { "type": "string" } },- "required": true- }- ],- "result": {- "name": "GroupParticipantsRemoveResult",- "schema": { "$ref": "#/components/schemas/GroupParticipantsResult" }- }- },- {- "name": "group_invite_link",- "summary": "Get group invite link",- "params": [- {- "name": "group_id",- "description": "Group JID",- "schema": { "type": "string" },- "required": true- }- ],- "result": {- "name": "GroupInviteLinkResult",- "schema": { "$ref": "#/components/schemas/GroupInviteLinkResult" }- }- },- {- "name": "group_revoke_invite",- "summary": "Revoke and regenerate group invite link",- "params": [- {- "name": "group_id",- "description": "Group JID",- "schema": { "type": "string" },- "required": true- }- ],- "result": {- "name": "GroupRevokeInviteResult",- "schema": { "$ref": "#/components/schemas/GroupInviteLinkResult" }- }- },- {- "name": "rate_limit_get",- "summary": "Get rate limit configuration and statistics",- "params": [],- "result": {- "name": "RateLimitGetResult",- "schema": {- "type": "object",- "properties": {- "config": { "$ref": "#/components/schemas/RateLimitConfig" },- "stats": { "$ref": "#/components/schemas/RateLimitStats" }- },- "required": ["config", "stats"]- }- }- },- {- "name": "rate_limit_set",- "summary": "Update rate limit configuration",- "params": [- {- "name": "enabled",- "description": "Enable/disable rate limiting",- "schema": { "type": "boolean" },- "required": false- },- {- "name": "min_delay_ms",- "description": "Minimum delay between messages (milliseconds)",- "schema": { "type": "integer" },- "required": false- },- {- "name": "max_delay_ms",- "description": "Maximum delay for randomization (milliseconds)",- "schema": { "type": "integer" },- "required": false- },- {- "name": "typing_delay_ms",- "description": "Typing indicator duration (milliseconds)",- "schema": { "type": "integer" },- "required": false- },- {- "name": "link_extra_delay_ms",- "description": "Extra delay for messages with links (milliseconds)",- "schema": { "type": "integer" },- "required": false- },- {- "name": "max_messages_per_minute",- "description": "Maximum messages per minute",- "schema": { "type": "integer" },- "required": false- },- {- "name": "max_messages_per_hour",- "description": "Maximum messages per hour",- "schema": { "type": "integer" },- "required": false- },- {- "name": "max_new_contacts_per_day",- "description": "Maximum new contacts per day",- "schema": { "type": "integer" },- "required": false- },- {- "name": "simulate_typing",- "description": "Send typing indicator before messages",- "schema": { "type": "boolean" },- "required": false- },- {- "name": "randomize_delays",- "description": "Add random variance to delays",- "schema": { "type": "boolean" },- "required": false- },- {- "name": "pause_on_low_response",- "description": "Auto-pause if response rate drops",- "schema": { "type": "boolean" },- "required": false- },- {- "name": "response_rate_threshold",- "description": "Minimum response rate threshold (0.0-1.0)",- "schema": { "type": "number" },- "required": false- }- ],- "result": {- "name": "RateLimitSetResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string" },- "config": { "$ref": "#/components/schemas/RateLimitConfig" }- }- }- }- },- {- "name": "rate_limit_stats",- "summary": "Get current rate limiting statistics only",- "params": [],- "result": {- "name": "RateLimitStatsResult",- "schema": { "$ref": "#/components/schemas/RateLimitStats" }- }- },- {- "name": "rate_limit_unpause",- "summary": "Resume rate limiting after automatic pause",- "params": [],- "result": {- "name": "RateLimitUnpauseResult",- "schema": {- "type": "object",- "properties": {- "message": { "type": "string" },- "stats": { "$ref": "#/components/schemas/RateLimitStats" }- }- }- }- },- {- "name": "chat_history",- "summary": "Get chat history from stored messages",- "description": "Retrieve messages from SQLite history store. Messages are synced on first WhatsApp login and stored for later retrieval. Supports filtering by chat type (individual/group), sender, and message type.",- "params": [- {- "name": "chat_id",- "description": "Chat JID (e.g., [email protected] for individual, [email protected] for group)",- "schema": { "type": "string" },- "required": false- },- {- "name": "phone",- "description": "Phone number for individual chats (without +). Converted to JID automatically.",- "schema": { "type": "string" },- "required": false- },- {- "name": "group_id",- "description": "Group JID (e.g., [email protected])",- "schema": { "type": "string" },- "required": false- },- {- "name": "limit",- "description": "Maximum messages to return (default: 50, max: 500)",- "schema": { "type": "integer", "default": 50, "minimum": 1, "maximum": 500 },- "required": false- },- {- "name": "offset",- "description": "Number of messages to skip for pagination (default: 0)",- "schema": { "type": "integer", "default": 0 },- "required": false- },- {- "name": "sender_phone",- "description": "Filter group messages by sender phone number",- "schema": { "type": "string" },- "required": false- },- {- "name": "text_only",- "description": "Only return text messages (default: false)",- "schema": { "type": "boolean", "default": false },- "required": false- }- ],- "result": {- "name": "ChatHistoryResult",- "schema": { "$ref": "#/components/schemas/ChatHistoryResult" }- }- }- ],- "components": {- "schemas": {- "ChatHistoryResult": {- "type": "object",- "description": "Chat history query result",- "properties": {- "messages": {- "type": "array",- "description": "Array of message records",- "items": { "$ref": "#/components/schemas/MessageRecord" }- },- "total": { "type": "integer", "description": "Total matching messages in database" },- "has_more": { "type": "boolean", "description": "Whether more messages exist beyond limit+offset" }- },- "required": ["messages", "total", "has_more"]- },- "MessageRecord": {- "type": "object",- "description": "Stored message record from history",- "properties": {- "message_id": { "type": "string", "description": "Unique message ID" },- "chat_id": { "type": "string", "description": "Chat JID (individual or group)" },- "sender": { "type": "string", "description": "Sender JID" },- "sender_phone": { "type": "string", "description": "Sender phone number" },- "message_type": {- "type": "string",- "enum": ["text", "image", "video", "audio", "document", "sticker", "location", "contact"],- "description": "Type of message"- },- "text": { "type": "string", "description": "Text content (or caption for media)" },- "timestamp": { "type": "string", "format": "date-time", "description": "Message timestamp" },- "is_group": { "type": "boolean", "description": "Whether message is from a group chat" },- "is_from_me": { "type": "boolean", "description": "Whether message was sent by the connected device" }- },- "required": ["message_id", "chat_id", "sender", "message_type", "timestamp", "is_group", "is_from_me"]- },- "MediaData": {- "type": "object",- "description": "Media content for sending",- "properties": {- "data": { "type": "string", "description": "Base64-encoded media data" },- "mime_type": { "type": "string", "description": "MIME type (e.g., image/jpeg, video/mp4)" },- "filename": { "type": "string", "description": "Optional filename for documents" },- "caption": { "type": "string", "description": "Optional caption for images/videos" },- "thumbnail": { "type": "string", "description": "Optional base64 thumbnail" }- },- "required": ["data", "mime_type"]- },- "LocationData": {- "type": "object",- "description": "Location information",- "properties": {- "latitude": { "type": "number" },- "longitude": { "type": "number" },- "name": { "type": "string", "description": "Location name" },- "address": { "type": "string", "description": "Address" }- },- "required": ["latitude", "longitude"]- },- "ContactCard": {- "type": "object",- "description": "Contact vCard",- "properties": {- "display_name": { "type": "string" },- "vcard": { "type": "string", "description": "vCard 3.0 format string" }- },- "required": ["display_name", "vcard"]- },- "ReplyData": {- "type": "object",- "description": "Reply context for quoting messages",- "properties": {- "message_id": { "type": "string", "description": "ID of message to reply to" },- "sender": { "type": "string", "description": "Sender JID of quoted message" },- "content": { "type": "string", "description": "Text preview of quoted message" }- },- "required": ["message_id", "sender", "content"]- },- "GroupInfo": {- "type": "object",- "description": "Group information",- "properties": {- "jid": { "type": "string", "description": "Group JID (e.g., [email protected])" },- "name": { "type": "string" },- "topic": { "type": "string", "description": "Group description" },- "owner": { "type": "string", "description": "Owner JID" },- "participants": {- "type": "array",- "items": { "$ref": "#/components/schemas/GroupParticipant" }- },- "created_at": { "type": "string", "format": "date-time" },- "size": { "type": "integer", "description": "Number of participants" },- "is_announce": { "type": "boolean", "description": "Only admins can send messages" },- "is_locked": { "type": "boolean", "description": "Only admins can edit group info" }- },- "required": ["jid", "name", "owner", "participants", "size"]- },- "GroupParticipant": {- "type": "object",- "description": "Group member with resolved phone number",- "properties": {- "jid": { "type": "string", "description": "Participant JID (may be LID format)" },- "phone": { "type": "string", "description": "Real phone number (resolved from LID if needed)" },- "name": { "type": "string" },- "is_admin": { "type": "boolean" },- "is_super_admin": { "type": "boolean", "description": "True for group owner" }- },- "required": ["jid", "phone", "is_admin", "is_super_admin"]- },- "GroupParticipantsResult": {- "type": "object",- "description": "Result of participant changes",- "properties": {- "group_id": { "type": "string", "description": "Group JID" },- "action": { "type": "string", "enum": ["add", "remove"], "description": "Action performed" },- "results": {- "type": "array",- "items": { "$ref": "#/components/schemas/GroupParticipantChangeResult" }- },- "added": { "type": "integer", "description": "Number of participants successfully added" },- "removed": { "type": "integer", "description": "Number of participants successfully removed" },- "failed": { "type": "integer", "description": "Number of failed operations" }- },- "required": ["group_id", "action", "results", "failed"]- },- "GroupParticipantChangeResult": {- "type": "object",- "description": "Result for a single participant change",- "properties": {- "jid": { "type": "string", "description": "Participant JID" },- "phone": { "type": "string", "description": "Phone number" },- "success": { "type": "boolean", "description": "Whether operation succeeded" },- "error": { "type": "string", "description": "Error message if failed" }- },- "required": ["jid", "success"]- },- "GroupInviteLinkResult": {- "type": "object",- "description": "Group invite link information",- "properties": {- "group_id": { "type": "string", "description": "Group JID" },- "invite_link": { "type": "string", "description": "Full invite link (https://chat.whatsapp.com/...)" },- "revoked": { "type": "boolean", "description": "Whether old link was revoked" }- },- "required": ["group_id", "invite_link"]- },- "RateLimitConfig": {- "type": "object",- "description": "Rate limiting configuration for anti-ban protection",- "properties": {- "enabled": { "type": "boolean", "default": true, "description": "Enable rate limiting" },- "min_delay_ms": { "type": "integer", "default": 3000, "description": "Minimum delay between messages (ms)" },- "max_delay_ms": { "type": "integer", "default": 8000, "description": "Maximum delay for randomization (ms)" },- "typing_delay_ms": { "type": "integer", "default": 2000, "description": "Typing indicator duration (ms)" },- "link_extra_delay_ms": { "type": "integer", "default": 5000, "description": "Extra delay for messages with links (ms)" },- "max_messages_per_minute": { "type": "integer", "default": 10, "description": "Per-minute message limit" },- "max_messages_per_hour": { "type": "integer", "default": 60, "description": "Per-hour message limit" },- "max_new_contacts_per_day": { "type": "integer", "default": 20, "description": "Daily new contacts limit" },- "simulate_typing": { "type": "boolean", "default": true, "description": "Send typing indicator before messages" },- "randomize_delays": { "type": "boolean", "default": true, "description": "Add random variance to delays" },- "pause_on_low_response": { "type": "boolean", "default": false, "description": "Auto-pause if response rate drops" },- "response_rate_threshold": { "type": "number", "default": 0.3, "description": "Minimum response rate (0.0-1.0)" }- }- },- "RateLimitStats": {- "type": "object",- "description": "Current rate limiting statistics",- "properties": {- "messages_sent_last_minute": { "type": "integer", "description": "Messages sent in last 60 seconds" },- "messages_sent_last_hour": { "type": "integer", "description": "Messages sent in last 60 minutes" },- "messages_sent_today": { "type": "integer", "description": "Total messages sent today" },- "new_contacts_today": { "type": "integer", "description": "New contacts messaged today" },- "responses_received": { "type": "integer", "description": "Responses received today" },- "response_rate": { "type": "number", "description": "Response rate (responses/sent)" },- "is_paused": { "type": "boolean", "description": "Whether rate limiting is paused" },- "pause_reason": { "type": "string", "description": "Reason for pause if paused" },- "last_message_time": { "type": "string", "format": "date-time", "description": "Time of last sent message" },- "next_allowed_time": { "type": "string", "format": "date-time", "description": "Earliest time next message allowed" }- }- },- "ReceivedMedia": {- "type": "object",- "description": "Received media (image/video) information",- "properties": {- "mime_type": { "type": "string" },- "file_sha256": { "type": "string" },- "file_length": { "type": "integer" },- "caption": { "type": "string" },- "url": { "type": "string" },- "seconds": { "type": "integer", "description": "Duration for video" }- }- },- "ReceivedAudio": {- "type": "object",- "description": "Received audio/voice message information",- "properties": {- "mime_type": { "type": "string" },- "file_sha256": { "type": "string" },- "file_length": { "type": "integer" },- "seconds": { "type": "integer" },- "ptt": { "type": "boolean", "description": "True for voice messages (push-to-talk)" },- "url": { "type": "string" }- }- },- "ReceivedDocument": {- "type": "object",- "description": "Received document information",- "properties": {- "mime_type": { "type": "string" },- "file_sha256": { "type": "string" },- "file_length": { "type": "integer" },- "file_name": { "type": "string" },- "title": { "type": "string" },- "caption": { "type": "string" },- "url": { "type": "string" }- }- },- "ReceivedContact": {- "type": "object",- "description": "Received contact vCard",- "properties": {- "display_name": { "type": "string" },- "vcard": { "type": "string" }- }- },- "ReceivedSticker": {- "type": "object",- "description": "Received sticker information",- "properties": {- "mime_type": { "type": "string" },- "file_sha256": { "type": "string" },- "file_length": { "type": "integer" },- "is_animated": { "type": "boolean", "description": "True for animated stickers" },- "url": { "type": "string" }- }- }- },- "events": {- "description": "Server-sent notifications (JSON-RPC without id)",- "types": {- "event.status": {- "description": "Initial status sent on WebSocket connection",- "params": {- "connected": { "type": "boolean" },- "has_session": { "type": "boolean" },- "running": { "type": "boolean" },- "pairing": { "type": "boolean" },- "device_id": { "type": "string" },- "timestamp": { "type": "string", "format": "date-time" }- }- },- "event.connected": {- "description": "WhatsApp connected successfully",- "params": {- "status": { "type": "string", "enum": ["connected"] },- "device_id": { "type": "string" }- }- },- "event.disconnected": {- "description": "WhatsApp disconnected",- "params": {- "status": { "type": "string", "enum": ["disconnected"] },- "reason": { "type": "string" }- }- },- "event.connection_failure": {- "description": "Connection failed",- "params": {- "error": { "type": "string" },- "reason": { "type": "string" }- }- },- "event.logged_out": {- "description": "User logged out",- "params": {- "on_connect": { "type": "boolean" },- "reason": { "type": "string" }- }- },- "event.temporary_ban": {- "description": "Temporary ban received",- "params": {- "code": { "type": "string" },- "reason": { "type": "string" }- }- },- "event.qr_code": {- "description": "New QR code available for pairing",- "params": {- "code": { "type": "string", "description": "QR code content" },- "filename": { "type": "string", "description": "PNG file path" },- "image_data": { "type": "string", "description": "Base64-encoded PNG data" }- }- },- "event.message_sent": {- "description": "Message sent successfully",- "params": {- "message_id": { "type": "string" },- "to": { "type": "string" },- "type": { "type": "string" },- "timestamp": { "type": "string", "format": "date-time" }- }- },- "event.message_received": {- "description": "New message received",- "params": {- "message_id": { "type": "string" },- "sender": { "type": "string", "description": "Sender JID" },- "chat_id": { "type": "string", "description": "Chat JID (same as sender for DMs, group JID for groups)" },- "timestamp": { "type": "string", "format": "date-time" },- "is_from_me": { "type": "boolean" },- "is_group": { "type": "boolean" },- "is_forwarded": { "type": "boolean", "description": "Whether the message was forwarded" },- "forwarding_score": { "type": "integer", "description": "Number of times forwarded (higher = forwarded many times)" },- "message_type": {- "type": "string",- "enum": ["text", "image", "video", "audio", "document", "sticker", "location", "contact", "contacts"]- },- "content": { "type": "object", "description": "Message content (varies by type)" },- "text": { "type": "string", "description": "Text content (for text messages)" },- "image": { "$ref": "#/components/schemas/ReceivedMedia" },- "video": { "$ref": "#/components/schemas/ReceivedMedia" },- "audio": { "$ref": "#/components/schemas/ReceivedAudio" },- "document": { "$ref": "#/components/schemas/ReceivedDocument" },- "sticker": { "$ref": "#/components/schemas/ReceivedSticker" },- "location": { "$ref": "#/components/schemas/LocationData" },- "contact": { "$ref": "#/components/schemas/ReceivedContact" },- "contacts": {- "type": "array",- "items": { "$ref": "#/components/schemas/ReceivedContact" }- },- "group_info": {- "type": "object",- "description": "Present for group messages",- "properties": {- "group_jid": { "type": "string" },- "sender_jid": { "type": "string" },- "sender_name": { "type": "string" }- }- },- "is_reply": { "type": "boolean" },- "quoted_message_id": { "type": "string" }- }- },- "event.history_sync_complete": {- "description": "History sync completed after first login",- "params": {- "conversations": { "type": "integer", "description": "Number of conversations synced" },- "messages": { "type": "integer", "description": "Total messages stored" }- }- }- }- }- },- "examples": {- "request": {- "description": "JSON-RPC 2.0 request format",- "value": {- "jsonrpc": "2.0",- "id": 1,- "method": "status",- "params": {}- }- },- "response": {- "description": "JSON-RPC 2.0 response format",- "value": {- "jsonrpc": "2.0",- "id": 1,- "result": {- "connected": true,- "has_session": true,- "running": true,- "pairing": false,- "device_id": "[email protected]",- "timestamp": "2025-01-15T10:30:00Z"- }- }- },- "event": {- "description": "JSON-RPC 2.0 notification (no id)",- "value": {- "jsonrpc": "2.0",- "method": "event.message_received",- "params": {- "message_id": "ABC123",- "sender": "[email protected]",- "chat_id": "[email protected]",- "timestamp": "2025-01-15T10:30:00Z",- "is_from_me": false,- "is_group": false,- "message_type": "text",- "text": "Hello world!",- "content": "Hello world!"- }- }- },- "send_text": {- "description": "Send text message",- "value": {- "jsonrpc": "2.0",- "id": 2,- "method": "send",- "params": {- "phone": "1234567890",- "type": "text",- "message": "Hello from API!"- }- }- },- "send_image": {- "description": "Send image message",- "value": {- "jsonrpc": "2.0",- "id": 3,- "method": "send",- "params": {- "phone": "1234567890",- "type": "image",- "media_data": {- "data": "base64_encoded_image_data",- "mime_type": "image/jpeg",- "caption": "Check this out!"- }- }- }- },- "send_to_group": {- "description": "Send message to group",- "value": {- "jsonrpc": "2.0",- "id": 4,- "method": "send",- "params": {- "group_id": "[email protected]",- "type": "text",- "message": "Hello group!"- }- }- },- "send_location": {- "description": "Send location message",- "value": {- "jsonrpc": "2.0",- "id": 5,- "method": "send",- "params": {- "phone": "1234567890",- "type": "location",- "location": {- "latitude": 37.7749,- "longitude": -122.4194,- "name": "San Francisco",- "address": "California, USA"- }- }- }- },- "download_media": {- "description": "Download media from message",- "value": {- "jsonrpc": "2.0",- "id": 6,- "method": "media",- "params": {- "message_id": "ABC123DEF456"- }- }- },- "error_response": {- "description": "Error response format",- "value": {- "jsonrpc": "2.0",- "id": 1,- "error": {- "code": -32000,- "message": "WhatsApp not connected"- }- }- },- "rate_limit_get": {- "description": "Get rate limit config and stats",- "value": {- "jsonrpc": "2.0",- "id": 7,- "method": "rate_limit_get",- "params": {}- }- },- "rate_limit_set": {- "description": "Update rate limit configuration",- "value": {- "jsonrpc": "2.0",- "id": 8,- "method": "rate_limit_set",- "params": {- "enabled": true,- "min_delay_ms": 5000,- "max_messages_per_hour": 30,- "simulate_typing": true- }- }- },- "rate_limit_unpause": {- "description": "Resume after automatic pause",- "value": {- "jsonrpc": "2.0",- "id": 9,- "method": "rate_limit_unpause",- "params": {}- }- }- },- "errorCodes": {- "-32700": "Parse error - Invalid JSON",- "-32600": "Invalid Request - Not a valid JSON-RPC 2.0 request",- "-32601": "Method not found",- "-32602": "Invalid params",- "-32000": "Server error (WhatsApp operation failed)",- "-32001": "No QR available"- }-}diff --git a/server/whatsapp-rpc/scripts/clean.cjs b/server/whatsapp-rpc/scripts/clean.cjsdeleted file mode 100644index 3ede1632..00000000--- a/server/whatsapp-rpc/scripts/clean.cjs+++ /dev/null@@ -1,66 +0,0 @@-#!/usr/bin/env node-// Standalone clean script - no npm dependencies required-const { existsSync, unlinkSync, readdirSync, rmSync } = require('fs');-const { join } = require('path');-const { execSync } = require('child_process');--const ROOT = join(__dirname, '..');-const BIN = process.platform === 'win32' ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server';-const BIN_DIR = join(ROOT, 'bin');--const log = (msg, color) => {- const colors = { green: '\x1b[32m', blue: '\x1b[34m', yellow: '\x1b[33m', reset: '\x1b[0m' };- console.log(`${colors[color] || ''}${msg}${colors.reset}`);-};--// Kill process on port-const killPort = (port, name) => {- try {- if (process.platform === 'win32') {- execSync(`for /f "tokens=5" %a in ('netstat -aon ^| findstr :${port} ^| findstr LISTENING') do taskkill /F /PID %a`, { stdio: 'ignore', shell: 'cmd.exe' });- } else {- execSync(`lsof -ti:${port} | xargs kill -9 2>/dev/null || true`, { stdio: 'ignore' });- }- log(`${name} stopped`, 'green');- } catch { log(`${name} not running`, 'yellow'); }-};--log('Stopping all processes...', 'blue');-killPort(9400, 'API');-killPort(5000, 'Web');--// Remove binary-const bin = join(BIN_DIR, BIN);-if (existsSync(bin)) { unlinkSync(bin); log(`Removed ${BIN}`, 'green'); }--// Remove bin directory if empty-if (existsSync(BIN_DIR) && readdirSync(BIN_DIR).length === 0) {- rmSync(BIN_DIR, { recursive: true }); log('Removed bin/', 'green');-}--// Remove entire data directory (database, QR codes, etc.)-const dataDir = join(ROOT, 'data');-if (existsSync(dataDir)) {- rmSync(dataDir, { recursive: true });- log('Removed data/', 'green');-}--// Remove any .db files in project root (legacy locations)-readdirSync(ROOT).filter(f => f.endsWith('.db') || f.endsWith('.db-wal') || f.endsWith('.db-shm')).forEach(f => {- unlinkSync(join(ROOT, f));- log(`Removed ${f}`, 'green');-});--// Remove node_modules-const nodeModules = join(ROOT, 'node_modules');-if (existsSync(nodeModules)) { rmSync(nodeModules, { recursive: true }); log('Removed node_modules/', 'green'); }--// Remove Python cache-const pycache = join(ROOT, 'web', '__pycache__');-if (existsSync(pycache)) { rmSync(pycache, { recursive: true }); log('Removed web/__pycache__/', 'green'); }--// Remove package-lock.json-const lockFile = join(ROOT, 'package-lock.json');-if (existsSync(lockFile)) { unlinkSync(lockFile); log('Removed package-lock.json', 'green'); }--log('Clean complete', 'green');diff --git a/server/whatsapp-rpc/scripts/cli.js b/server/whatsapp-rpc/scripts/cli.jsdeleted file mode 100644index 8ffb0e6c..00000000--- a/server/whatsapp-rpc/scripts/cli.js+++ /dev/null@@ -1,171 +0,0 @@-#!/usr/bin/env node-import { program } from 'commander';-import chalk from 'chalk';-import { execa } from 'execa';-import killPort from 'kill-port';-import { Socket } from 'net';-import { execSync, spawn } from 'child_process';-import { existsSync, statSync, unlinkSync, readdirSync, rmSync } from 'fs';-import { dirname, join } from 'path';-import { fileURLToPath } from 'url';--const __dirname = dirname(fileURLToPath(import.meta.url));-const ROOT = join(__dirname, '..');-const API_PORT = 9400, WEB_PORT = 5000;-const BIN = process.platform === 'win32' ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server';-const BIN_DIR = join(ROOT, 'bin');--const log = (m, c = 'blue') => console.log(chalk[c](m));-const sleep = ms => new Promise(r => setTimeout(r, ms));--const portUp = port => new Promise(r => {- const s = new Socket();- s.setTimeout(2000);- s.on('connect', () => { s.destroy(); r(true); });- s.on('timeout', () => { s.destroy(); r(false); });- s.on('error', () => r(false));- s.connect(port, '127.0.0.1');-});--const wait = async (port, ms = 10000) => {- const t = Date.now();- while (Date.now() - t < ms) { if (await portUp(port)) return true; await sleep(500); }- return false;-};--const kill = async (port, name) => {- try { await killPort(port); log(`${name} stopped`, 'green'); }- catch { log(`${name} not running`, 'yellow'); }-};--const py = () => {- try { execSync('python --version', { stdio: 'ignore' }); return 'python'; }- catch { try { execSync('python3 --version', { stdio: 'ignore' }); return 'python3'; } catch { return null; } }-};--const hasGo = () => {- try { execSync('go version', { stdio: 'ignore' }); return true; }- catch { return false; }-};--async function api(foreground = false) {- if (await portUp(API_PORT)) { log(`API already on ${API_PORT}`, 'yellow'); return; }- const bin = join(BIN_DIR, BIN);- if (!existsSync(bin)) {- if (!hasGo()) {- log('Go is not installed. Please either:', 'red');- log(' 1. Install Go: https://go.dev/dl/', 'yellow');- log(' 2. Or run "npm run build" on a machine with Go installed', 'yellow');- log(' 3. Or copy the pre-built binary to: ' + bin, 'yellow');- process.exit(1);- }- log('Building...', 'yellow');- await build();- }-- if (foreground) {- // Run in foreground - will receive Ctrl+C signals- const proc = spawn(bin, [], { cwd: ROOT, stdio: 'inherit' });- proc.on('close', (code) => process.exit(code || 0));- process.on('SIGINT', () => { proc.kill('SIGINT'); });- process.on('SIGTERM', () => { proc.kill('SIGTERM'); });- log(`API: ws://localhost:${API_PORT}/ws/rpc`, 'green');- } else {- // Run detached in background- spawn(bin, [], { cwd: ROOT, detached: true, stdio: 'ignore' }).unref();- if (await wait(API_PORT)) log(`API: ws://localhost:${API_PORT}/ws/rpc`, 'green');- else log('API failed to start', 'red');- }-}--async function web() {- if (await portUp(WEB_PORT)) { log(`Web already on ${WEB_PORT}`, 'yellow'); return; }- const p = py(); if (!p) { log('Python not found', 'red'); return; }- if (!await portUp(API_PORT)) log('Warning: API not running', 'yellow');- spawn(p, ['app.py'], { cwd: join(ROOT, 'web'), detached: true, stdio: 'ignore' }).unref();- if (await wait(WEB_PORT)) log(`Web: http://localhost:${WEB_PORT}`, 'green');- else log('Web failed to start', 'red');-}--async function start() { await api(); await sleep(1000); await web(); }-async function stop() { await kill(API_PORT, 'API'); await kill(WEB_PORT, 'Web'); }--async function status() {- const a = await portUp(API_PORT), w = await portUp(WEB_PORT);- log(`API (${API_PORT}): ${a ? 'UP' : 'DOWN'}`, a ? 'green' : 'red');- log(`Web (${WEB_PORT}): ${w ? 'UP' : 'DOWN'}`, w ? 'green' : 'red');-}--async function build() {- const bin = join(BIN_DIR, BIN);-- // Skip if binary already exists (e.g., downloaded from GitHub Releases)- if (existsSync(bin)) {- log(`Binary already exists: ${BIN} (${(statSync(bin).size / 1024 / 1024).toFixed(1)}MB)`, 'green');- return;- }-- // Build from source requires Go- if (!hasGo()) {- log('Go is not installed and no pre-built binary found.', 'red');- log('Install Go from: https://go.dev/dl/', 'yellow');- process.exit(1);- }-- if (!existsSync(BIN_DIR)) { await execa('mkdir', ['-p', BIN_DIR]); }- await execa('go', ['build', '-o', bin, './src/go/cmd/server'], { cwd: ROOT, stdio: 'inherit' });- log(`Built: ${BIN} (${(statSync(bin).size / 1024 / 1024).toFixed(1)}MB)`, 'green');-}--async function clean() {- log('Stopping all processes...', 'blue');- await stop();- await sleep(1000);-- // Remove binary- const bin = join(BIN_DIR, BIN);- if (existsSync(bin)) { unlinkSync(bin); log(`Removed ${BIN}`, 'green'); }-- // Remove bin directory if empty- if (existsSync(BIN_DIR) && readdirSync(BIN_DIR).length === 0) {- rmSync(BIN_DIR, { recursive: true }); log('Removed bin/', 'green');- }-- // Remove entire data directory (database, QR codes, etc.)- const dataDir = join(ROOT, 'data');- if (existsSync(dataDir)) {- rmSync(dataDir, { recursive: true });- log('Removed data/', 'green');- }-- // Remove any .db files in project root (legacy locations)- readdirSync(ROOT).filter(f => f.endsWith('.db') || f.endsWith('.db-wal') || f.endsWith('.db-shm')).forEach(f => {- unlinkSync(join(ROOT, f));- log(`Removed ${f}`, 'green');- });-- // Remove node_modules- const nodeModules = join(ROOT, 'node_modules');- if (existsSync(nodeModules)) { rmSync(nodeModules, { recursive: true }); log('Removed node_modules/', 'green'); }-- // Remove Python cache- const pycache = join(ROOT, 'web', '__pycache__');- if (existsSync(pycache)) { rmSync(pycache, { recursive: true }); log('Removed web/__pycache__/', 'green'); }-- // Remove package-lock.json- const lockFile = join(ROOT, 'package-lock.json');- if (existsSync(lockFile)) { unlinkSync(lockFile); log('Removed package-lock.json', 'green'); }-- log('Clean complete', 'green');-}--program.name('wa').version('1.0.0');-program.command('start').description('Start all').action(start);-program.command('stop').description('Stop all').action(stop);-program.command('restart').description('Restart all').action(async () => { await stop(); await sleep(1000); await start(); });-program.command('status').description('Status').action(status);-program.command('api').description('Start API only').option('-f, --foreground', 'Run in foreground (receive signals)').action((opts) => api(opts.foreground));-program.command('web').description('Start Web only').action(web);-program.command('build').description('Build binary').action(build);-program.command('clean').description('Clean artifacts').action(clean);-program.parse();diff --git a/server/whatsapp-rpc/src/go/cmd/server/main.go b/server/whatsapp-rpc/src/go/cmd/server/main.godeleted file mode 100644index 87176ea0..00000000--- a/server/whatsapp-rpc/src/go/cmd/server/main.go+++ /dev/null@@ -1,91 +0,0 @@-package main--import (- "context"- "fmt"- "net/http"- "os"- "os/signal"- "syscall"- "time"-- "github.com/sirupsen/logrus"-- "whatsapp-rpc/src/go/config"- server "whatsapp-rpc/src/go/rpc"- "whatsapp-rpc/src/go/whatsapp"-)--func main() {- // Initialize logger- logger := logrus.New()- logger.SetFormatter(&logrus.TextFormatter{- FullTimestamp: true,- })-- // Load configuration- cfg, err := config.Load()- if err != nil {- logger.Fatalf("Failed to load config: %v", err)- }-- // Set log level (5 = Debug, 4 = Info)- if cfg.LogLevel >= 5 {- logger.SetLevel(logrus.DebugLevel)- }-- logger.Info("Starting WhatsApp WebSocket RPC Server")-- // Initialize WhatsApp service- whatsappService, err := whatsapp.NewService(cfg.Database, logger)- if err != nil {- logger.Fatalf("Failed to initialize WhatsApp service: %v", err)- }-- // Auto-start if there's an existing session (no need to press Start button)- if whatsappService.HasExistingSession() {- logger.Info("Existing session found, auto-connecting...")- if err := whatsappService.Start(); err != nil {- logger.Warnf("Auto-start failed: %v (user can manually start)", err)- }- } else {- logger.Info("No existing session, waiting for user to start pairing")- }-- // Create and start server (WebSocket RPC only)- srv := server.New(whatsappService, logger)- router := srv.SetupRoutes()-- httpServer := &http.Server{- Addr: fmt.Sprintf(":%d", cfg.Server.Port),- Handler: router,- }-- // Start server in goroutine- go func() {- logger.Infof("WebSocket RPC server listening on port %d", cfg.Server.Port)- logger.Infof("Connect via: ws://localhost:%d/ws/rpc", cfg.Server.Port)- if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {- logger.Fatalf("Server error: %v", err)- }- }()-- // Wait for interrupt signal- quit := make(chan os.Signal, 1)- signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)- <-quit-- logger.Info("Shutting down server...")-- // Graceful shutdown- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- whatsappService.Shutdown()-- if err := httpServer.Shutdown(ctx); err != nil {- logger.Errorf("Server shutdown error: %v", err)- }-- logger.Info("Server stopped")-}diff --git a/server/whatsapp-rpc/src/go/config/config.go b/server/whatsapp-rpc/src/go/config/config.godeleted file mode 100644index 566f127e..00000000--- a/server/whatsapp-rpc/src/go/config/config.go+++ /dev/null@@ -1,49 +0,0 @@-package config--import (- "github.com/spf13/viper"-)--type Config struct {- Environment string `mapstructure:"environment"`- LogLevel int `mapstructure:"log_level"`- Server ServerConfig `mapstructure:"server"`- Database DatabaseConfig `mapstructure:"database"`-}--type ServerConfig struct {- Port int `mapstructure:"port"`- Host string `mapstructure:"host"`-}--type DatabaseConfig struct {- Path string `mapstructure:"path"`-}--func Load() (*Config, error) {- viper.SetDefault("environment", "development")- viper.SetDefault("log_level", 4) // Info level- viper.SetDefault("server.port", 9400)- viper.SetDefault("server.host", "0.0.0.0")- viper.SetDefault("database.path", "data/whatsapp.db")-- // Environment variables- viper.SetEnvPrefix("WA")- viper.AutomaticEnv()-- // Config file- viper.SetConfigName("config")- viper.SetConfigType("yaml")- viper.AddConfigPath(".")- viper.AddConfigPath("./configs")-- // Read config file (optional)- viper.ReadInConfig()-- var config Config- if err := viper.Unmarshal(&config); err != nil {- return nil, err- }-- return &config, nil-}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/go/rpc/rpc.go b/server/whatsapp-rpc/src/go/rpc/rpc.godeleted file mode 100644index 083de96a..00000000--- a/server/whatsapp-rpc/src/go/rpc/rpc.go+++ /dev/null@@ -1,446 +0,0 @@-package server--import (- "encoding/base64"- "encoding/json"- "os"- "sync"-- "github.com/gorilla/websocket"- "github.com/sirupsen/logrus"-- "whatsapp-rpc/src/go/whatsapp"-)--// JSON-RPC 2.0 message types-type RPCRequest struct {- JSONRPC string `json:"jsonrpc"`- ID interface{} `json:"id,omitempty"`- Method string `json:"method"`- Params json.RawMessage `json:"params,omitempty"`-}--type RPCResponse struct {- JSONRPC string `json:"jsonrpc"`- ID interface{} `json:"id,omitempty"`- Result interface{} `json:"result,omitempty"`- Error *RPCError `json:"error,omitempty"`-}--type RPCError struct {- Code int `json:"code"`- Message string `json:"message"`-}--// RPCHandler processes JSON-RPC requests-type RPCHandler struct {- service *whatsapp.Service- logger *logrus.Logger-}--// NewRPCHandler creates a new RPC handler-func NewRPCHandler(service *whatsapp.Service, logger *logrus.Logger) *RPCHandler {- return &RPCHandler{- service: service,- logger: logger,- }-}--// HandleRequest processes a JSON-RPC request and returns a response-func (h *RPCHandler) HandleRequest(req *RPCRequest) RPCResponse {- resp := RPCResponse{JSONRPC: "2.0", ID: req.ID}-- switch req.Method {- case "status":- resp.Result = h.service.GetStatus()-- case "start":- if err := h.service.Start(); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Started"}- }-- case "stop":- h.service.Shutdown()- resp.Result = map[string]string{"message": "Stopped"}-- case "restart":- // Full restart: cleanup QR codes, reset session, then start fresh- h.service.CleanupQRCodes()- if err := h.service.Reset(); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else if err := h.service.Start(); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Restarted (session cleared)"}- }-- case "reset":- if err := h.service.Reset(); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Reset"}- }-- case "diagnostics":- resp.Result = h.service.GetDiagnostics()-- case "qr":- if qr := h.service.GetCurrentQRCode(); qr != nil {- result := map[string]interface{}{- "has_qr": true,- "code": qr.Code,- "filename": qr.Filename,- }- // Read PNG file and encode to base64 for Docker compatibility- // qr.Filename already contains full path like "data/qr/qr_xxx.png"- if data, err := os.ReadFile(qr.Filename); err == nil {- result["image_data"] = base64.StdEncoding.EncodeToString(data)- }- resp.Result = result- } else {- resp.Error = &RPCError{Code: -32001, Message: "No QR available"}- }-- case "send":- var msgReq whatsapp.MessageRequest- if err := json.Unmarshal(req.Params, &msgReq); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if err := h.service.SendEnhancedMessage(&msgReq); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Sent"}- }-- case "media":- var p struct {- MessageID string `json:"message_id"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if data, mime, err := h.service.DownloadMedia(p.MessageID); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]interface{}{- "data": data,- "mime_type": mime,- }- }-- case "groups":- if groups, err := h.service.GetGroups(); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = groups- }-- case "group_info":- var p struct {- GroupID string `json:"group_id"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.GroupID == "" {- resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}- } else if info, err := h.service.GetGroupInfo(p.GroupID); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = info- }-- case "group_update":- var p whatsapp.GroupUpdateRequest- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.GroupID == "" {- resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}- } else if p.Name == "" && p.Topic == "" {- resp.Error = &RPCError{Code: -32602, Message: "name or topic is required"}- } else if err := h.service.UpdateGroupInfo(p.GroupID, p.Name, p.Topic); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Updated"}- }-- case "contact_check":- var p struct {- Phones []string `json:"phones"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if len(p.Phones) == 0 {- resp.Error = &RPCError{Code: -32602, Message: "phones array is required and must not be empty"}- } else if results, err := h.service.CheckContacts(p.Phones); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = results- }-- case "contact_profile_pic":- var p struct {- JID string `json:"jid"`- Preview bool `json:"preview"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.JID == "" {- resp.Error = &RPCError{Code: -32602, Message: "jid is required"}- } else if result, err := h.service.GetProfilePicture(p.JID, p.Preview); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = result- }-- case "contacts":- var p struct {- Query string `json:"query"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- // If params parsing fails, use empty query (list all)- p.Query = ""- }- if contacts, err := h.service.GetContacts(p.Query); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]interface{}{- "contacts": contacts,- "total": len(contacts),- }- }-- case "contact_info":- var p struct {- Phone string `json:"phone"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.Phone == "" {- resp.Error = &RPCError{Code: -32602, Message: "phone is required"}- } else if info, err := h.service.GetContactInfo(p.Phone); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = info- }-- case "typing":- var p struct {- JID string `json:"jid"`- State string `json:"state"`- Media string `json:"media"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.JID == "" {- resp.Error = &RPCError{Code: -32602, Message: "jid is required"}- } else if p.State == "" {- resp.Error = &RPCError{Code: -32602, Message: "state is required ('composing' or 'paused')"}- } else if err := h.service.SendTyping(p.JID, p.State, p.Media); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Typing indicator sent"}- }-- case "presence":- var p struct {- Status string `json:"status"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.Status == "" {- resp.Error = &RPCError{Code: -32602, Message: "status is required ('available' or 'unavailable')"}- } else if err := h.service.SetPresence(p.Status); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Presence set"}- }-- case "mark_read":- var p struct {- MessageIDs []string `json:"message_ids"`- ChatJID string `json:"chat_jid"`- SenderJID string `json:"sender_jid"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if len(p.MessageIDs) == 0 {- resp.Error = &RPCError{Code: -32602, Message: "message_ids array is required"}- } else if p.ChatJID == "" {- resp.Error = &RPCError{Code: -32602, Message: "chat_jid is required"}- } else if err := h.service.MarkRead(p.MessageIDs, p.ChatJID, p.SenderJID); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]string{"message": "Messages marked as read"}- }-- case "group_participants_add":- var p struct {- GroupID string `json:"group_id"`- Participants []string `json:"participants"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.GroupID == "" {- resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}- } else if len(p.Participants) == 0 {- resp.Error = &RPCError{Code: -32602, Message: "participants array is required and must not be empty"}- } else if result, err := h.service.AddGroupParticipants(p.GroupID, p.Participants); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = result- }-- case "group_participants_remove":- var p struct {- GroupID string `json:"group_id"`- Participants []string `json:"participants"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.GroupID == "" {- resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}- } else if len(p.Participants) == 0 {- resp.Error = &RPCError{Code: -32602, Message: "participants array is required and must not be empty"}- } else if result, err := h.service.RemoveGroupParticipants(p.GroupID, p.Participants); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = result- }-- case "group_invite_link":- var p struct {- GroupID string `json:"group_id"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.GroupID == "" {- resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}- } else if result, err := h.service.GetGroupInviteLink(p.GroupID); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = result- }-- case "group_revoke_invite":- var p struct {- GroupID string `json:"group_id"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if p.GroupID == "" {- resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}- } else if result, err := h.service.RevokeGroupInviteLink(p.GroupID); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = result- }-- case "chat_history":- var p struct {- ChatID string `json:"chat_id"`- Phone string `json:"phone"`- GroupID string `json:"group_id"`- Limit int `json:"limit"`- Offset int `json:"offset"`- SenderPhone string `json:"sender_phone"`- TextOnly bool `json:"text_only"`- }- if err := json.Unmarshal(req.Params, &p); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else {- // Resolve chat_id from phone or group_id if not directly provided- chatID := p.ChatID- if chatID == "" {- if p.Phone != "" {- chatID = p.Phone + "@s.whatsapp.net"- } else if p.GroupID != "" {- chatID = p.GroupID- } else {- resp.Error = &RPCError{Code: -32602, Message: "Either chat_id, phone, or group_id is required"}- break- }- }-- // Set defaults- limit := p.Limit- if limit <= 0 {- limit = 50- }- if limit > 500 {- limit = 500- }-- if result, err := h.service.GetChatHistory(chatID, limit, p.Offset, p.SenderPhone, p.TextOnly); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = result- }- }-- case "rate_limit_get":- resp.Result = map[string]interface{}{- "config": h.service.GetRateLimitConfig(),- "stats": h.service.GetRateLimitStats(),- }-- case "rate_limit_set":- var config whatsapp.RateLimitConfig- if err := json.Unmarshal(req.Params, &config); err != nil {- resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}- } else if err := h.service.SetRateLimitConfig(&config); err != nil {- resp.Error = &RPCError{Code: -32000, Message: err.Error()}- } else {- resp.Result = map[string]interface{}{- "message": "Rate limit config updated",- "config": h.service.GetRateLimitConfig(),- }- }-- case "rate_limit_stats":- resp.Result = h.service.GetRateLimitStats()-- case "rate_limit_unpause":- h.service.UnpauseRateLimiting()- resp.Result = map[string]interface{}{- "message": "Rate limiting unpaused",- "stats": h.service.GetRateLimitStats(),- }-- default:- resp.Error = &RPCError{Code: -32601, Message: "Method not found: " + req.Method}- }-- return resp-}--// ForwardEvents sends WhatsApp events as JSON-RPC notifications-func (h *RPCHandler) ForwardEvents(conn *websocket.Conn, mu *sync.Mutex, done chan struct{}) {- eventChan := h.service.GetEventChannel()- for {- select {- case <-done:- return- case event, ok := <-eventChan:- if !ok {- return- }- notif := RPCRequest{- JSONRPC: "2.0",- Method: "event." + event.Type,- Params: mustMarshal(event.Data),- }- mu.Lock()- if err := conn.WriteJSON(notif); err != nil {- mu.Unlock()- h.logger.Errorf("Failed to send event: %v", err)- return- }- mu.Unlock()- }- }-}--func mustMarshal(v interface{}) json.RawMessage {- b, _ := json.Marshal(v)- return b-}diff --git a/server/whatsapp-rpc/src/go/rpc/server.go b/server/whatsapp-rpc/src/go/rpc/server.godeleted file mode 100644index 3eaa5cc6..00000000--- a/server/whatsapp-rpc/src/go/rpc/server.go+++ /dev/null@@ -1,112 +0,0 @@-package server--import (- "net/http"- "sync"-- "github.com/gin-gonic/gin"- "github.com/gorilla/websocket"- "github.com/sirupsen/logrus"-- "whatsapp-rpc/src/go/whatsapp"-)--// Server handles WebSocket RPC connections-type Server struct {- whatsapp *whatsapp.Service- logger *logrus.Logger- upgrader websocket.Upgrader-}--// New creates a new WebSocket RPC server-func New(whatsappService *whatsapp.Service, logger *logrus.Logger) *Server {- return &Server{- whatsapp: whatsappService,- logger: logger,- upgrader: websocket.Upgrader{- CheckOrigin: func(r *http.Request) bool {- return true- },- ReadBufferSize: 1024 * 1024, // 1 MB read buffer- WriteBufferSize: 100 * 1024 * 1024, // 100 MB write buffer for large media- },- }-}--// SetupRoutes configures WebSocket RPC routes only-func (s *Server) SetupRoutes() *gin.Engine {- gin.SetMode(gin.ReleaseMode)- router := gin.New()- router.Use(gin.Recovery())-- // CORS middleware- router.Use(func(c *gin.Context) {- c.Header("Access-Control-Allow-Origin", "*")- c.Header("Access-Control-Allow-Methods", "GET, OPTIONS")- c.Header("Access-Control-Allow-Headers", "Content-Type")- if c.Request.Method == "OPTIONS" {- c.AbortWithStatus(200)- return- }- c.Next()- })-- // WebSocket RPC endpoint - the only endpoint- router.GET("/ws/rpc", s.handleWebSocketRPC)-- // Health check- router.GET("/health", func(c *gin.Context) {- c.JSON(200, gin.H{"status": "ok", "type": "websocket-rpc"})- })-- return router-}--// handleWebSocketRPC handles bidirectional JSON-RPC over WebSocket-func (s *Server) handleWebSocketRPC(c *gin.Context) {- conn, err := s.upgrader.Upgrade(c.Writer, c.Request, nil)- if err != nil {- s.logger.Errorf("WebSocket upgrade failed: %v", err)- return- }- defer conn.Close()-- s.logger.Info("RPC client connected")-- var writeMu sync.Mutex- done := make(chan struct{})- handler := NewRPCHandler(s.whatsapp, s.logger)-- // Forward events as JSON-RPC notifications- go handler.ForwardEvents(conn, &writeMu, done)-- // Send initial status- status := s.whatsapp.GetStatus()- writeMu.Lock()- conn.WriteJSON(RPCRequest{- JSONRPC: "2.0",- Method: "event.status",- Params: mustMarshal(status),- })- writeMu.Unlock()-- // Read and handle incoming requests- for {- var req RPCRequest- if err := conn.ReadJSON(&req); err != nil {- s.logger.Debugf("RPC client disconnected: %v", err)- close(done)- return- }-- s.logger.Debugf("RPC request: %s", req.Method)-- // Process request and send response- resp := handler.HandleRequest(&req)- if req.ID != nil {- writeMu.Lock()- conn.WriteJSON(resp)- writeMu.Unlock()- }- }-}diff --git a/server/whatsapp-rpc/src/go/whatsapp/history.go b/server/whatsapp-rpc/src/go/whatsapp/history.godeleted file mode 100644index 52ce648c..00000000--- a/server/whatsapp-rpc/src/go/whatsapp/history.go+++ /dev/null@@ -1,166 +0,0 @@-package whatsapp--import (- "database/sql"- "time"-- "github.com/sirupsen/logrus"- _ "modernc.org/sqlite"-)--// HistoryStore handles message persistence for chat history-type HistoryStore struct {- db *sql.DB- logger *logrus.Logger-}--// MessageRecord represents a stored message-type MessageRecord struct {- MessageID string `json:"message_id"`- ChatID string `json:"chat_id"`- Sender string `json:"sender"`- SenderPhone string `json:"sender_phone"`- MessageType string `json:"message_type"`- Text string `json:"text"`- Timestamp time.Time `json:"timestamp"`- IsGroup bool `json:"is_group"`- IsFromMe bool `json:"is_from_me"`-}--// ChatHistoryResult is the response for chat_history queries-type ChatHistoryResult struct {- Messages []MessageRecord `json:"messages"`- Total int `json:"total"`- HasMore bool `json:"has_more"`-}--// NewHistoryStore creates a new history store with SQLite persistence-func NewHistoryStore(dbPath string, logger *logrus.Logger) (*HistoryStore, error) {- // Use separate file for history to avoid conflicts with whatsmeow's session store- historyPath := dbPath + "_history"- db, err := sql.Open("sqlite", "file:"+historyPath+"?_journal_mode=WAL&_busy_timeout=5000")- if err != nil {- return nil, err- }-- store := &HistoryStore{db: db, logger: logger}- if err := store.initTable(); err != nil {- return nil, err- }- return store, nil-}--func (h *HistoryStore) initTable() error {- _, err := h.db.Exec(`- CREATE TABLE IF NOT EXISTS message_history (- message_id TEXT PRIMARY KEY,- chat_id TEXT NOT NULL,- sender TEXT NOT NULL,- sender_phone TEXT,- message_type TEXT NOT NULL,- text TEXT,- timestamp INTEGER NOT NULL,- is_group INTEGER NOT NULL DEFAULT 0,- is_from_me INTEGER NOT NULL DEFAULT 0,- created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))- );- CREATE INDEX IF NOT EXISTS idx_chat_id ON message_history(chat_id);- CREATE INDEX IF NOT EXISTS idx_timestamp ON message_history(timestamp DESC);- CREATE INDEX IF NOT EXISTS idx_sender_phone ON message_history(sender_phone);- `)- return err-}--// StoreMessage persists a message to the history store-func (h *HistoryStore) StoreMessage(msg MessageRecord) error {- _, err := h.db.Exec(`- INSERT OR IGNORE INTO message_history- (message_id, chat_id, sender, sender_phone, message_type, text, timestamp, is_group, is_from_me)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)- `, msg.MessageID, msg.ChatID, msg.Sender, msg.SenderPhone, msg.MessageType,- msg.Text, msg.Timestamp.Unix(), boolToInt(msg.IsGroup), boolToInt(msg.IsFromMe))- return err-}--// GetChatHistory retrieves messages for a chat with optional filters-func (h *HistoryStore) GetChatHistory(chatID string, limit, offset int, senderPhone string, textOnly bool) (*ChatHistoryResult, error) {- // Build query with filters- query := `SELECT message_id, chat_id, sender, sender_phone, message_type, text, timestamp, is_group, is_from_me- FROM message_history WHERE chat_id = ?`- args := []interface{}{chatID}-- if senderPhone != "" {- query += " AND sender_phone = ?"- args = append(args, senderPhone)- }- if textOnly {- query += " AND message_type = 'text'"- }-- // Count total matching- countQuery := "SELECT COUNT(*) FROM message_history WHERE chat_id = ?"- countArgs := []interface{}{chatID}- if senderPhone != "" {- countQuery += " AND sender_phone = ?"- countArgs = append(countArgs, senderPhone)- }- if textOnly {- countQuery += " AND message_type = 'text'"- }-- var total int- h.db.QueryRow(countQuery, countArgs...).Scan(&total)-- // Get messages ordered by timestamp descending (newest first)- query += " ORDER BY timestamp DESC LIMIT ? OFFSET ?"- args = append(args, limit, offset)-- rows, err := h.db.Query(query, args...)- if err != nil {- return nil, err- }- defer rows.Close()-- messages := []MessageRecord{}- for rows.Next() {- var msg MessageRecord- var ts int64- var isGroup, isFromMe int- err := rows.Scan(&msg.MessageID, &msg.ChatID, &msg.Sender, &msg.SenderPhone,- &msg.MessageType, &msg.Text, &ts, &isGroup, &isFromMe)- if err != nil {- continue- }- msg.Timestamp = time.Unix(ts, 0)- msg.IsGroup = isGroup == 1- msg.IsFromMe = isFromMe == 1- messages = append(messages, msg)- }-- return &ChatHistoryResult{- Messages: messages,- Total: total,- HasMore: offset+len(messages) < total,- }, nil-}--// Close closes the database connection-func (h *HistoryStore) Close() error {- if h.db != nil {- return h.db.Close()- }- return nil-}--// ClearHistory deletes all messages from the history store-func (h *HistoryStore) ClearHistory() error {- _, err := h.db.Exec("DELETE FROM message_history")- return err-}--func boolToInt(b bool) int {- if b {- return 1- }- return 0-}diff --git a/server/whatsapp-rpc/src/go/whatsapp/messages.go b/server/whatsapp-rpc/src/go/whatsapp/messages.godeleted file mode 100644index 2a98059f..00000000--- a/server/whatsapp-rpc/src/go/whatsapp/messages.go+++ /dev/null@@ -1,390 +0,0 @@-package whatsapp--import (- "context"- "encoding/base64"- "fmt"- "strings"- "time"-- "go.mau.fi/whatsmeow"- "go.mau.fi/whatsmeow/proto/waE2E"- "go.mau.fi/whatsmeow/types"- "google.golang.org/protobuf/proto"-)--// SendMessage - Legacy simple message sending (kept for backward compatibility)-func (s *Service) SendMessage(phone, message string) error {- req := &MessageRequest{- Phone: phone,- Message: message,- Type: "text",- }- return s.SendEnhancedMessage(req)-}--// SendEnhancedMessage - Comprehensive message sending with all WhatsApp features-func (s *Service) SendEnhancedMessage(req *MessageRequest) error {- if !s.client.IsConnected() {- return fmt.Errorf("WhatsApp not connected")- }-- var targetJID types.JID- var err error-- // Log received data for debugging- s.logger.Infof("SendEnhancedMessage: Type=%s, Phone='%s', GroupID='%s'", req.Type, req.Phone, req.GroupID)-- // Determine target JID (individual or group)- if req.GroupID != "" {- targetJID, err = types.ParseJID(req.GroupID)- if err != nil {- return fmt.Errorf("invalid group ID '%s': %w", req.GroupID, err)- }- } else if req.Phone != "" {- // Validate phone number is not empty after trimming- if len(req.Phone) == 0 {- return fmt.Errorf("phone number cannot be empty")- }- targetJID = types.NewJID(req.Phone, types.DefaultUserServer)- } else {- return fmt.Errorf("either phone or group_id is required (received: phone='%s', group_id='%s')", req.Phone, req.GroupID)- }-- // Determine recipient for rate limiting (use phone or group ID)- recipient := req.Phone- if recipient == "" {- recipient = req.GroupID- }-- // Check rate limits before proceeding- if err := s.CheckRateLimit(recipient); err != nil {- s.logger.Warnf("Rate limit check failed: %v", err)- return err- }-- // Send typing indicator if enabled (simulates human behavior)- s.SendTypingIfEnabled(targetJID.String())-- // Check if message contains links for extra delay- hasLinks := strings.Contains(req.Message, "http://") || strings.Contains(req.Message, "https://")-- // Apply message delay (with randomization for human-like behavior)- s.ApplyMessageDelay(hasLinks)-- // Create message based on type- var message *waE2E.Message- switch req.Type {- case "text":- message = s.createTextMessage(req)- case "image":- message, err = s.createImageMessage(req)- case "document":- message, err = s.createDocumentMessage(req)- case "audio":- message, err = s.createAudioMessage(req)- case "video":- message, err = s.createVideoMessage(req)- case "location":- message = s.createLocationMessage(req)- case "sticker":- message, err = s.createStickerMessage(req)- case "contact":- message = s.createContactMessage(req)- default:- return fmt.Errorf("unsupported message type: %s", req.Type)- }-- if err != nil {- return fmt.Errorf("failed to create %s message: %w", req.Type, err)- }-- // Add reply context if specified- if req.Reply != nil {- msgText := message.GetConversation()- message.ExtendedTextMessage = &waE2E.ExtendedTextMessage{- Text: &msgText,- ContextInfo: &waE2E.ContextInfo{- StanzaID: proto.String(req.Reply.MessageID),- Participant: proto.String(req.Reply.Sender),- QuotedMessage: &waE2E.Message{Conversation: proto.String(req.Reply.Content)},- },- }- message.Conversation = nil- }-- // Send the message- resp, err := s.client.SendMessage(context.Background(), targetJID, message)- if err != nil {- return fmt.Errorf("failed to send message: %w", err)- }-- // Record message sent for rate limiting stats- s.RecordMessageSent(recipient)-- // Log successful send- s.logger.Infof("Message sent successfully: %s to %s", resp.ID, targetJID.String())-- // Send event notification- s.safeEventSend(Event{- Type: "message_sent",- Data: map[string]interface{}{- "message_id": resp.ID,- "to": targetJID.String(),- "type": req.Type,- "timestamp": resp.Timestamp,- },- Time: time.Now(),- })-- return nil-}--// SendTyping sends typing indicator-// TODO: Fix context API breaking changes-/*-func (s *Service) SendTyping(jidStr string, typing bool) error {- if !s.client.IsConnected() {- return fmt.Errorf("WhatsApp not connected")- }-- var presence types.Presence- if typing {- presence = types.PresenceAvailable- } else {- presence = types.PresenceUnavailable- }-- sendErr := s.client.SendPresence(context.Background(), presence)- if sendErr != nil {- return fmt.Errorf("failed to send typing indicator: %w", sendErr)- }-- return nil-}--// MarkMessageAsRead marks a message as read-func (s *Service) MarkMessageAsRead(messageID, senderJID string) error {- if !s.client.IsConnected() {- return fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(senderJID)- if err != nil {- return fmt.Errorf("invalid sender JID: %w", err)- }-- err = s.client.MarkRead(context.Background(), []string{messageID}, time.Now(), jid, jid)- if err != nil {- return fmt.Errorf("failed to mark message as read: %w", err)- }-- return nil-}-*/--// Helper functions to create different message types--func (s *Service) createTextMessage(req *MessageRequest) *waE2E.Message {- return &waE2E.Message{- Conversation: proto.String(req.Message),- }-}--func (s *Service) createImageMessage(req *MessageRequest) (*waE2E.Message, error) {- if req.MediaData == nil {- return nil, fmt.Errorf("media_data is required for image messages")- }-- // Decode base64 media data- mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)- if err != nil {- return nil, fmt.Errorf("invalid base64 media data: %w", err)- }-- // Upload media to WhatsApp servers- uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaImage)- if err != nil {- return nil, fmt.Errorf("failed to upload image: %w", err)- }-- // Create image message- message := &waE2E.Message{- ImageMessage: &waE2E.ImageMessage{- Caption: proto.String(req.MediaData.Caption),- Mimetype: proto.String(req.MediaData.MimeType),- URL: proto.String(uploaded.URL),- DirectPath: proto.String(uploaded.DirectPath),- MediaKey: uploaded.MediaKey,- FileEncSHA256: uploaded.FileEncSHA256,- FileSHA256: uploaded.FileSHA256,- FileLength: proto.Uint64(uint64(len(mediaBytes))),- },- }-- return message, nil-}--func (s *Service) createDocumentMessage(req *MessageRequest) (*waE2E.Message, error) {- if req.MediaData == nil {- return nil, fmt.Errorf("media_data is required for document messages")- }-- // Decode base64 media data- mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)- if err != nil {- return nil, fmt.Errorf("invalid base64 media data: %w", err)- }-- // Upload media to WhatsApp servers- uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaDocument)- if err != nil {- return nil, fmt.Errorf("failed to upload document: %w", err)- }-- // Create document message- message := &waE2E.Message{- DocumentMessage: &waE2E.DocumentMessage{- Title: proto.String(req.MediaData.Filename),- FileName: proto.String(req.MediaData.Filename),- Mimetype: proto.String(req.MediaData.MimeType),- URL: proto.String(uploaded.URL),- DirectPath: proto.String(uploaded.DirectPath),- MediaKey: uploaded.MediaKey,- FileEncSHA256: uploaded.FileEncSHA256,- FileSHA256: uploaded.FileSHA256,- FileLength: proto.Uint64(uint64(len(mediaBytes))),- },- }-- return message, nil-}--func (s *Service) createAudioMessage(req *MessageRequest) (*waE2E.Message, error) {- if req.MediaData == nil {- return nil, fmt.Errorf("media_data is required for audio messages")- }-- // Decode base64 media data- mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)- if err != nil {- return nil, fmt.Errorf("invalid base64 media data: %w", err)- }-- // Upload media to WhatsApp servers- uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaAudio)- if err != nil {- return nil, fmt.Errorf("failed to upload audio: %w", err)- }-- // Create audio message- message := &waE2E.Message{- AudioMessage: &waE2E.AudioMessage{- Mimetype: proto.String(req.MediaData.MimeType),- URL: proto.String(uploaded.URL),- DirectPath: proto.String(uploaded.DirectPath),- MediaKey: uploaded.MediaKey,- FileEncSHA256: uploaded.FileEncSHA256,- FileSHA256: uploaded.FileSHA256,- FileLength: proto.Uint64(uint64(len(mediaBytes))),- PTT: proto.Bool(strings.Contains(req.MediaData.MimeType, "ogg")), // Voice note for OGG- },- }-- return message, nil-}--func (s *Service) createVideoMessage(req *MessageRequest) (*waE2E.Message, error) {- if req.MediaData == nil {- return nil, fmt.Errorf("media_data is required for video messages")- }-- // Decode base64 media data- mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)- if err != nil {- return nil, fmt.Errorf("invalid base64 media data: %w", err)- }-- // Upload media to WhatsApp servers- uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaVideo)- if err != nil {- return nil, fmt.Errorf("failed to upload video: %w", err)- }-- // Create video message- message := &waE2E.Message{- VideoMessage: &waE2E.VideoMessage{- Caption: proto.String(req.MediaData.Caption),- Mimetype: proto.String(req.MediaData.MimeType),- URL: proto.String(uploaded.URL),- DirectPath: proto.String(uploaded.DirectPath),- MediaKey: uploaded.MediaKey,- FileEncSHA256: uploaded.FileEncSHA256,- FileSHA256: uploaded.FileSHA256,- FileLength: proto.Uint64(uint64(len(mediaBytes))),- },- }-- return message, nil-}--func (s *Service) createLocationMessage(req *MessageRequest) *waE2E.Message {- if req.Location == nil {- return &waE2E.Message{Conversation: proto.String("Invalid location data")}- }-- return &waE2E.Message{- LocationMessage: &waE2E.LocationMessage{- DegreesLatitude: proto.Float64(req.Location.Latitude),- DegreesLongitude: proto.Float64(req.Location.Longitude),- Name: proto.String(req.Location.Name),- Address: proto.String(req.Location.Address),- },- }-}--func (s *Service) createStickerMessage(req *MessageRequest) (*waE2E.Message, error) {- if req.MediaData == nil {- return nil, fmt.Errorf("media_data is required for sticker messages")- }-- // Decode base64 media data- mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)- if err != nil {- return nil, fmt.Errorf("invalid base64 media data: %w", err)- }-- // Upload media to WhatsApp servers- uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaImage)- if err != nil {- return nil, fmt.Errorf("failed to upload sticker: %w", err)- }-- // Create sticker message- message := &waE2E.Message{- StickerMessage: &waE2E.StickerMessage{- Mimetype: proto.String(req.MediaData.MimeType),- URL: proto.String(uploaded.URL),- DirectPath: proto.String(uploaded.DirectPath),- MediaKey: uploaded.MediaKey,- FileEncSHA256: uploaded.FileEncSHA256,- FileSHA256: uploaded.FileSHA256,- FileLength: proto.Uint64(uint64(len(mediaBytes))),- },- }-- return message, nil-}--func (s *Service) createContactMessage(req *MessageRequest) *waE2E.Message {- if req.Contact == nil {- return &waE2E.Message{Conversation: proto.String("Invalid contact data")}- }-- return &waE2E.Message{- ContactMessage: &waE2E.ContactMessage{- DisplayName: proto.String(req.Contact.DisplayName),- Vcard: proto.String(req.Contact.VCard),- },- }-}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/go/whatsapp/service.go b/server/whatsapp-rpc/src/go/whatsapp/service.godeleted file mode 100644index e2960ab3..00000000--- a/server/whatsapp-rpc/src/go/whatsapp/service.go+++ /dev/null@@ -1,2130 +0,0 @@-package whatsapp--import (- "context"- "encoding/json"- "fmt"- "math/rand"- "os"- "path/filepath"- "strings"- "sync"- "time"-- "github.com/sirupsen/logrus"- "github.com/skip2/go-qrcode"- "go.mau.fi/whatsmeow"- "go.mau.fi/whatsmeow/proto/waCompanionReg"- "go.mau.fi/whatsmeow/proto/waE2E"- "go.mau.fi/whatsmeow/store"- "go.mau.fi/whatsmeow/store/sqlstore"- "go.mau.fi/whatsmeow/types"- "go.mau.fi/whatsmeow/types/events"- waLog "go.mau.fi/whatsmeow/util/log"- _ "modernc.org/sqlite"-- "whatsapp-rpc/src/go/config"-)--type Service struct {- mu sync.Mutex- client *whatsmeow.Client- container *sqlstore.Container // Database container for proper cleanup- dbPath string // Database file path- logger *logrus.Logger- events chan Event- running bool- pairing bool- shutdown bool- lastQRCode *QRCodeData- lastQRCodeTime time.Time- messages map[string]*events.Message // Store messages by ID for media download- messageOrder []string // Track message insertion order for FIFO cleanup- historyStore *HistoryStore // Persistent message history store-- // Rate limiting for anti-ban protection- rateMu sync.Mutex- rateLimitConfig *RateLimitConfig- rateLimitStats *RateLimitStats- messageTimes []time.Time // Sliding window of message times- contactsSeen map[string]bool // Track known contacts- newContactsToday map[string]time.Time // New contacts with timestamp- dailyResetTime time.Time // When daily counters were last reset-}----func NewService(dbConfig config.DatabaseConfig, logger *logrus.Logger) (*Service, error) {- // Configure device to appear as legitimate WhatsApp Web on Chrome- // Uses default WhatsApp Web version and Chrome platform type for natural appearance- store.DeviceProps.PlatformType = waCompanionReg.DeviceProps_CHROME.Enum()- store.SetOSInfo("Windows - Zeenie", store.GetWAVersion())-- // Ensure database directory exists- dbDir := filepath.Dir(dbConfig.Path)- if dbDir != "" && dbDir != "." {- if err := os.MkdirAll(dbDir, 0755); err != nil {- return nil, fmt.Errorf("failed to create database directory: %w", err)- }- }-- // Setup database with WAL mode for concurrent access and extended busy timeout- dbLog := waLog.Stdout("Database", "INFO", true)- ctx := context.Background()- // Increased busy timeout to 30 seconds and added cache=shared for better concurrency on Windows- container, err := sqlstore.New(ctx, "sqlite", "file:"+dbConfig.Path+"?_pragma=foreign_keys(1)&_journal_mode=WAL&_busy_timeout=30000&cache=shared", dbLog)- if err != nil {- return nil, fmt.Errorf("failed to initialize database: %w", err)- }-- // Get device store- deviceStore, err := container.GetFirstDevice(ctx)- if err != nil {- return nil, fmt.Errorf("failed to get device: %w", err)- }-- // Create client - NO extra configuration like working example- clientLog := waLog.Stdout("WhatsApp", "INFO", true)- client := whatsmeow.NewClient(deviceStore, clientLog)-- service := &Service{- client: client,- container: container,- dbPath: dbConfig.Path,- logger: logger,- events: make(chan Event, 100),- running: false,- pairing: false,- shutdown: false,- messages: make(map[string]*events.Message),- messageOrder: make([]string, 0, 100),- rateLimitConfig: DefaultRateLimitConfig(),- rateLimitStats: &RateLimitStats{},- messageTimes: make([]time.Time, 0, 100),- contactsSeen: make(map[string]bool),- newContactsToday: make(map[string]time.Time),- dailyResetTime: time.Now(),- }-- // Initialize history store for message persistence- historyStore, err := NewHistoryStore(dbConfig.Path, logger)- if err != nil {- logger.Warnf("Failed to init history store (history disabled): %v", err)- } else {- service.historyStore = historyStore- logger.Info("History store initialized")- }-- // Reset any previous connection state on service creation- if client.IsConnected() {- client.Disconnect()- }-- // Add event handler- client.AddEventHandler(service.eventHandler)-- return service, nil-}--// HasExistingSession returns true if there's a stored session that can be used to auto-connect-func (s *Service) HasExistingSession() bool {- hasClient := s.client != nil- hasStore := hasClient && s.client.Store != nil- hasID := hasStore && s.client.Store.ID != nil-- s.logger.Infof("HasExistingSession check: client=%v, store=%v, id=%v", hasClient, hasStore, hasID)-- return hasID-}--func (s *Service) safeEventSend(event Event) {- if s.shutdown {- return- }-- defer func() {- if r := recover(); r != nil {- s.logger.Errorf("Event send panic recovered: %v", r)- }- }()-- select {- case s.events <- event:- // Event sent successfully- default:- if s.shutdown {- s.logger.Info("Service is shutdown, skipping event")- } else {- s.logger.Warn("Events channel blocked, skipping event")- }- }-}--func (s *Service) Start() error {- s.mu.Lock()- defer s.mu.Unlock()-- if s.running {- s.logger.Warn("Service already running")- return nil- }-- // Events channel is kept open across restarts (not closed in Shutdown)- // This allows existing WebSocket ForwardEvents goroutines to continue working-- s.shutdown = false- s.running = true-- s.logger.Info("Starting WhatsApp service...")-- // Simple flow like working example- if s.client.Store.ID == nil {- s.logger.Info("No existing session found, starting pairing")- // Run pairing synchronously like working example- go func() {- if err := s.startPairing(); err != nil {- s.logger.Errorf("Pairing failed: %v", err)- }- }()- return nil- }-- // Connect with existing session- s.logger.Info("Existing session found, connecting...")- err := s.client.Connect()- if err != nil {- s.logger.Errorf("Failed to connect: %v", err)- return err- }-- s.logger.Info("Connected successfully")- return nil-}--func (s *Service) startPairing() error {- s.logger.Info("Starting pairing process")- s.pairing = true-- // Get QR channel - use simple context like working example- qrChan, err := s.client.GetQRChannel(context.Background())- if err != nil {- s.logger.Errorf("Failed to get QR channel: %v", err)- s.pairing = false- return err- }-- // Connect to WhatsApp- err = s.client.Connect()- if err != nil {- s.logger.Errorf("Failed to connect: %v", err)- s.pairing = false- return err- }-- // Process QR events - simple loop like working example- for evt := range qrChan {- if evt.Event == "code" {- s.logger.Info("QR code received, generating PNG")- qrData := s.handleQRCode(evt.Code)-- s.safeEventSend(Event{- Type: "qr_code",- Data: map[string]interface{}{- "code": qrData.Code,- "filename": qrData.Filename,- },- Time: time.Now(),- })- } else if evt.Event == "success" {- s.logger.Info("Pairing successful")- s.pairing = false- s.safeEventSend(Event{- Type: "connected",- Data: map[string]interface{}{"status": "connected"},- Time: time.Now(),- })- return nil- } else {- s.logger.Infof("QR event: %s", evt.Event)- }- }-- s.pairing = false- return fmt.Errorf("QR channel closed")-}--func (s *Service) handleQRCode(code string) QRCodeData {- // Delete old QR code files before creating new one- s.cleanupOldQRCodes()-- // Ensure data/qr directory exists- qrDir := "data/qr"- os.MkdirAll(qrDir, 0755)-- filename := filepath.Join(qrDir, fmt.Sprintf("qr_%d.png", time.Now().Unix()))-- s.logger.Infof("Generating QR code PNG file: %s", filename)- s.logger.Debugf("QR code content (first 50 chars): %s...", code[:min(50, len(code))])-- // Save QR code as PNG- err := qrcode.WriteFile(code, qrcode.Medium, 256, filename)- if err != nil {- s.logger.Errorf("Failed to save QR code to file %s: %v", filename, err)- } else {- s.logger.Infof("QR code successfully saved to %s", filename)- }-- qrData := QRCodeData{- Code: code,- Filename: filename,- Time: time.Now(),- }-- // Store QR code for API retrieval- s.mu.Lock()- s.lastQRCode = &qrData- s.lastQRCodeTime = time.Now()- s.mu.Unlock()-- s.logger.Info("QR code ready for scanning. Instructions:")- s.logger.Info("1. Open WhatsApp on your phone")- s.logger.Info("2. Go to Settings > Linked Devices")- s.logger.Info("3. Tap 'Link a Device'")- s.logger.Info("4. Scan the QR code from the generated PNG file or terminal")- s.logger.Infof("5. QR code file location: %s", filename)-- return qrData-}---func (s *Service) eventHandler(evt interface{}) {- if s.shutdown {- return- }-- switch v := evt.(type) {- case *events.Connected:- s.logger.Infof("Successfully connected to WhatsApp! Device ID: %s", s.client.Store.ID.String())- s.pairing = false-- // Generate groups JSON file asynchronously- go func() {- time.Sleep(2 * time.Second) // Wait for connection to stabilize- if err := s.generateGroupsJSON(); err != nil {- s.logger.Errorf("Failed to generate groups.json: %v", err)- }- }()-- s.safeEventSend(Event{- Type: "connected",- Data: map[string]interface{}{- "status": "connected",- "device_id": s.client.Store.ID.String(),- },- Time: time.Now(),- })- case *events.Disconnected:- s.logger.Warnf("Disconnected from WhatsApp. Reason: %+v", v)- s.safeEventSend(Event{- Type: "disconnected",- Data: map[string]interface{}{- "status": "disconnected",- "reason": fmt.Sprintf("%+v", v),- },- Time: time.Now(),- })- case *events.ConnectFailure:- s.logger.Errorf("Connection failure: %+v", v)- s.safeEventSend(Event{- Type: "connection_failure",- Data: map[string]interface{}{- "error": fmt.Sprintf("%+v", v),- "reason": v.Reason.String(),- },- Time: time.Now(),- })- case *events.LoggedOut:- s.logger.Warnf("=== LOGOUT EVENT RECEIVED ===")- s.logger.Warnf("OnConnect: %v", v.OnConnect)- s.logger.Warnf("Reason: %s", v.Reason.String())- s.logger.Warnf("Full logout event: %+v", v)- s.logger.Warnf("Device Store ID: %v", s.client.Store.ID)- s.logger.Warnf("Is Connected: %v", s.client.IsConnected())- s.logger.Warnf("=== END LOGOUT EVENT ===")- s.safeEventSend(Event{- Type: "logged_out",- Data: map[string]interface{}{- "on_connect": v.OnConnect,- "reason": v.Reason.String(),- "full_event": fmt.Sprintf("%+v", v),- },- Time: time.Now(),- })- case *events.TemporaryBan:- s.logger.Errorf("Temporary ban received: %+v", v)- s.safeEventSend(Event{- Type: "temporary_ban",- Data: map[string]interface{}{- "code": v.Code.String(),- "reason": fmt.Sprintf("%+v", v),- },- Time: time.Now(),- })- case *events.HistorySync:- s.handleHistorySync(v)- case *events.Message:- s.handleIncomingMessage(v)- default:- s.logger.Debugf("Unhandled event type: %T, data: %+v", evt, evt)- }-}--// handleIncomingMessage processes incoming messages and extracts all message types-func (s *Service) handleIncomingMessage(v *events.Message) {- // Extract basic info- sender := v.Info.Sender.String()- chatID := v.Info.Chat.String()- timestamp := v.Info.Timestamp- messageID := v.Info.ID- isGroup := v.Info.IsGroup-- // Resolve LID to phone number (LIDs can appear in both group and individual chats)- senderPhone := v.Info.Sender.User // Default to JID user part- if v.Info.Sender.Server == "lid" && s.client.Store.LIDs != nil {- ctx := context.Background()- pn, err := s.client.Store.LIDs.GetPNForLID(ctx, v.Info.Sender)- if err == nil && pn.User != "" {- senderPhone = pn.User- s.logger.Debugf("Resolved LID %s to phone %s", sender, senderPhone)- } else if err != nil {- s.logger.Debugf("Could not resolve LID %s: %v", sender, err)- }- }-- if isGroup {- s.logger.Debugf("Processing group message from %s (phone: %s) in %s (ID: %s)", sender, senderPhone, chatID, messageID)- } else {- s.logger.Debugf("Processing individual message from %s (phone: %s) (ID: %s)", sender, senderPhone, messageID)- }-- // Store message for later media download (keep last 100 messages to avoid memory issues)- s.mu.Lock()- // Check if message already exists (avoid duplicates)- if _, exists := s.messages[messageID]; !exists {- // Remove oldest messages if at capacity (FIFO cleanup)- maxMessages := 100- for len(s.messageOrder) >= maxMessages {- oldestID := s.messageOrder[0]- s.messageOrder = s.messageOrder[1:]- delete(s.messages, oldestID)- s.logger.Debugf("Removed oldest message %s from cache (capacity: %d)", oldestID, maxMessages)- }- // Add new message- s.messages[messageID] = v- s.messageOrder = append(s.messageOrder, messageID)- s.logger.Debugf("Cached message %s for media download (total: %d)", messageID, len(s.messages))- }- s.mu.Unlock()-- // Prepare event data with common fields- eventData := map[string]interface{}{- "message_id": messageID,- "sender": sender,- "sender_phone": senderPhone,- "chat_id": chatID,- "timestamp": timestamp,- "is_from_me": v.Info.IsFromMe,- "is_group": isGroup,- }-- // Add group info for group messages- if isGroup {- groupInfo := map[string]interface{}{- "group_jid": chatID,- "sender_jid": sender,- "sender_phone": senderPhone,- }- // Try to get group name from push name or leave empty- if v.Info.PushName != "" {- groupInfo["sender_name"] = v.Info.PushName- }- eventData["group_info"] = groupInfo- }-- // Determine message type and extract content- msg := v.Message- messageType := "unknown"- var messageContent interface{}-- // Helper function to extract forwarded info from ContextInfo- extractForwardedInfo := func(ctx *waE2E.ContextInfo) {- if ctx == nil {- return- }- if ctx.GetIsForwarded() {- eventData["is_forwarded"] = true- eventData["forwarding_score"] = ctx.GetForwardingScore()- }- }-- switch {- case msg.Conversation != nil && *msg.Conversation != "":- // Plain text message (no ContextInfo, cannot be forwarded)- messageType = "text"- messageContent = *msg.Conversation- eventData["text"] = *msg.Conversation-- case msg.ExtendedTextMessage != nil:- // Extended text message (with link preview, quoted message, etc.)- messageType = "text"- if msg.ExtendedTextMessage.Text != nil {- messageContent = *msg.ExtendedTextMessage.Text- eventData["text"] = *msg.ExtendedTextMessage.Text- }- // Check forwarded status- extractForwardedInfo(msg.ExtendedTextMessage.ContextInfo)- // Check if it's a reply/quoted message- if msg.ExtendedTextMessage.ContextInfo != nil && msg.ExtendedTextMessage.ContextInfo.QuotedMessage != nil {- eventData["is_reply"] = true- if msg.ExtendedTextMessage.ContextInfo.StanzaID != nil {- eventData["quoted_message_id"] = *msg.ExtendedTextMessage.ContextInfo.StanzaID- }- }-- case msg.ImageMessage != nil:- // Image message- messageType = "image"- imageData := map[string]interface{}{- "mime_type": msg.ImageMessage.GetMimetype(),- "file_sha256": fmt.Sprintf("%x", msg.ImageMessage.GetFileSHA256()),- "file_length": msg.ImageMessage.GetFileLength(),- }- if msg.ImageMessage.Caption != nil {- imageData["caption"] = *msg.ImageMessage.Caption- }- if msg.ImageMessage.URL != nil {- imageData["url"] = *msg.ImageMessage.URL- }- messageContent = imageData- eventData["image"] = imageData- // Check forwarded status- extractForwardedInfo(msg.ImageMessage.ContextInfo)-- case msg.VideoMessage != nil:- // Video message- messageType = "video"- videoData := map[string]interface{}{- "mime_type": msg.VideoMessage.GetMimetype(),- "file_sha256": fmt.Sprintf("%x", msg.VideoMessage.GetFileSHA256()),- "file_length": msg.VideoMessage.GetFileLength(),- "seconds": msg.VideoMessage.GetSeconds(),- }- if msg.VideoMessage.Caption != nil {- videoData["caption"] = *msg.VideoMessage.Caption- }- if msg.VideoMessage.URL != nil {- videoData["url"] = *msg.VideoMessage.URL- }- messageContent = videoData- eventData["video"] = videoData- // Check forwarded status- extractForwardedInfo(msg.VideoMessage.ContextInfo)-- case msg.AudioMessage != nil:- // Audio/Voice message- messageType = "audio"- audioData := map[string]interface{}{- "mime_type": msg.AudioMessage.GetMimetype(),- "file_sha256": fmt.Sprintf("%x", msg.AudioMessage.GetFileSHA256()),- "file_length": msg.AudioMessage.GetFileLength(),- "seconds": msg.AudioMessage.GetSeconds(),- "ptt": msg.AudioMessage.GetPTT(), // Push-to-talk (voice message)- }- if msg.AudioMessage.URL != nil {- audioData["url"] = *msg.AudioMessage.URL- }- messageContent = audioData- eventData["audio"] = audioData- // Check forwarded status- extractForwardedInfo(msg.AudioMessage.ContextInfo)-- case msg.DocumentMessage != nil:- // Document message- messageType = "document"- docData := map[string]interface{}{- "mime_type": msg.DocumentMessage.GetMimetype(),- "file_sha256": fmt.Sprintf("%x", msg.DocumentMessage.GetFileSHA256()),- "file_length": msg.DocumentMessage.GetFileLength(),- }- if msg.DocumentMessage.FileName != nil {- docData["file_name"] = *msg.DocumentMessage.FileName- }- if msg.DocumentMessage.Title != nil {- docData["title"] = *msg.DocumentMessage.Title- }- if msg.DocumentMessage.Caption != nil {- docData["caption"] = *msg.DocumentMessage.Caption- }- if msg.DocumentMessage.URL != nil {- docData["url"] = *msg.DocumentMessage.URL- }- messageContent = docData- eventData["document"] = docData- // Check forwarded status- extractForwardedInfo(msg.DocumentMessage.ContextInfo)-- case msg.StickerMessage != nil:- // Sticker message- messageType = "sticker"- stickerData := map[string]interface{}{- "mime_type": msg.StickerMessage.GetMimetype(),- "file_sha256": fmt.Sprintf("%x", msg.StickerMessage.GetFileSHA256()),- "file_length": msg.StickerMessage.GetFileLength(),- "is_animated": msg.StickerMessage.GetIsAnimated(),- }- if msg.StickerMessage.URL != nil {- stickerData["url"] = *msg.StickerMessage.URL- }- messageContent = stickerData- eventData["sticker"] = stickerData- // Check forwarded status- extractForwardedInfo(msg.StickerMessage.ContextInfo)-- case msg.LocationMessage != nil:- // Location message- messageType = "location"- locationData := map[string]interface{}{- "latitude": msg.LocationMessage.GetDegreesLatitude(),- "longitude": msg.LocationMessage.GetDegreesLongitude(),- }- if msg.LocationMessage.Name != nil {- locationData["name"] = *msg.LocationMessage.Name- }- if msg.LocationMessage.Address != nil {- locationData["address"] = *msg.LocationMessage.Address- }- messageContent = locationData- eventData["location"] = locationData-- case msg.ContactMessage != nil:- // Contact card message- messageType = "contact"- contactData := map[string]interface{}{- "display_name": msg.ContactMessage.GetDisplayName(),- "vcard": msg.ContactMessage.GetVcard(),- }- messageContent = contactData- eventData["contact"] = contactData-- case msg.ContactsArrayMessage != nil:- // Multiple contacts- messageType = "contacts"- contacts := []map[string]interface{}{}- for _, contact := range msg.ContactsArrayMessage.Contacts {- contacts = append(contacts, map[string]interface{}{- "display_name": contact.GetDisplayName(),- "vcard": contact.GetVcard(),- })- }- messageContent = contacts- eventData["contacts"] = contacts-- case msg.ReactionMessage != nil:- // Reaction to a message - skip broadcasting these- s.logger.Debugf("Skipping reaction message from %s to message %s", sender, msg.ReactionMessage.GetKey().GetID())- return-- case msg.ProtocolMessage != nil:- // Protocol messages (edits, deletes, ephemeral settings) - skip these- s.logger.Debugf("Skipping protocol message from %s (type: %v)", sender, msg.ProtocolMessage.GetType())- return-- default:- // Unknown message type - silently skip (don't log or broadcast)- return- }-- eventData["message_type"] = messageType- eventData["content"] = messageContent-- // Log the message (debug level to reduce noise)- s.logger.Debugf("Received %s message from %s", messageType, sender)-- // Persist ALL messages to history store for future retrieval- if s.historyStore != nil {- textContent := ""- if t, ok := eventData["text"].(string); ok {- textContent = t- }- record := MessageRecord{- MessageID: messageID,- ChatID: chatID,- Sender: sender,- SenderPhone: senderPhone,- MessageType: messageType,- Text: textContent,- Timestamp: timestamp,- IsGroup: isGroup,- IsFromMe: v.Info.IsFromMe,- }- go func() {- if err := s.historyStore.StoreMessage(record); err != nil {- s.logger.Debugf("Failed to store message: %v", err)- }- }()- }-- // Broadcast event- s.safeEventSend(Event{- Type: "message_received",- Data: eventData,- Time: time.Now(),- })-}--// handleHistorySync processes history sync events received on first login-// This contains all past conversations and messages from WhatsApp-func (s *Service) handleHistorySync(evt *events.HistorySync) {- if s.historyStore == nil {- s.logger.Warn("History sync received but history store not initialized")- return- }-- historyData := evt.Data- if historyData == nil {- return- }-- conversations := historyData.GetConversations()- s.logger.Infof("Processing history sync: %d conversations", len(conversations))-- totalMessages := 0- for _, conv := range conversations {- chatJID, err := types.ParseJID(conv.GetID())- if err != nil {- s.logger.Warnf("Invalid chat JID in history: %s", conv.GetID())- continue- }-- isGroup := chatJID.Server == "g.us"- chatID := chatJID.String()-- for _, historyMsg := range conv.GetMessages() {- webMsg := historyMsg.GetMessage()- if webMsg == nil {- continue- }-- // Parse the web message to get standard message format- parsedMsg, err := s.client.ParseWebMessage(chatJID, webMsg)- if err != nil {- continue- }-- // Extract message info- msgInfo := parsedMsg.Info- messageID := msgInfo.ID- sender := msgInfo.Sender.String()- senderPhone := msgInfo.Sender.User- timestamp := msgInfo.Timestamp-- // Determine message type and extract text content- messageType := "unknown"- text := ""-- msg := parsedMsg.Message- if msg == nil {- // Skip messages with nil content (protocol messages, etc.)- continue- }-- switch {- case msg.Conversation != nil && *msg.Conversation != "":- messageType = "text"- text = *msg.Conversation- case msg.ExtendedTextMessage != nil && msg.ExtendedTextMessage.Text != nil:- messageType = "text"- text = *msg.ExtendedTextMessage.Text- case msg.ImageMessage != nil:- messageType = "image"- if msg.ImageMessage.Caption != nil {- text = *msg.ImageMessage.Caption- }- case msg.VideoMessage != nil:- messageType = "video"- if msg.VideoMessage.Caption != nil {- text = *msg.VideoMessage.Caption- }- case msg.AudioMessage != nil:- messageType = "audio"- case msg.DocumentMessage != nil:- messageType = "document"- if msg.DocumentMessage.Caption != nil {- text = *msg.DocumentMessage.Caption- }- case msg.StickerMessage != nil:- messageType = "sticker"- case msg.LocationMessage != nil:- messageType = "location"- case msg.ContactMessage != nil:- messageType = "contact"- default:- // Skip unknown/protocol messages- continue- }-- // Store ALL message types- record := MessageRecord{- MessageID: messageID,- ChatID: chatID,- Sender: sender,- SenderPhone: senderPhone,- MessageType: messageType,- Text: text,- Timestamp: timestamp,- IsGroup: isGroup,- IsFromMe: msgInfo.IsFromMe,- }-- if err := s.historyStore.StoreMessage(record); err != nil {- s.logger.Debugf("Failed to store history message: %v", err)- } else {- totalMessages++- }- }- }-- s.logger.Infof("History sync complete: stored %d messages from %d conversations",- totalMessages, len(conversations))-- // Broadcast event for frontend notification- s.safeEventSend(Event{- Type: "history_sync_complete",- Data: map[string]interface{}{- "conversations": len(conversations),- "messages": totalMessages,- },- Time: time.Now(),- })-}--// GetChatHistory retrieves stored messages for a chat-func (s *Service) GetChatHistory(chatID string, limit, offset int, senderPhone string, textOnly bool) (*ChatHistoryResult, error) {- if s.historyStore == nil {- return nil, fmt.Errorf("history store not initialized")- }- return s.historyStore.GetChatHistory(chatID, limit, offset, senderPhone, textOnly)-}--func (s *Service) GetStatus() map[string]interface{} {- status := map[string]interface{}{- "connected": s.client.IsConnected(),- "has_session": s.client.Store.ID != nil,- "running": s.running,- "pairing": s.pairing,- "timestamp": time.Now(),- }-- // Add device information if available- if s.client.Store.ID != nil {- status["device_id"] = s.client.Store.ID.String()- }-- return status-}--func (s *Service) GetDiagnostics() map[string]interface{} {- diagnostics := map[string]interface{}{- "client_connected": s.client.IsConnected(),- "client_logged_in": s.client.IsLoggedIn(),- "store_has_id": s.client.Store.ID != nil,- "service_running": s.running,- "service_pairing": s.pairing,- "service_shutdown": s.shutdown,- "events_channel_open": !s.shutdown,- "timestamp": time.Now(),- }-- // Add store information if available- if s.client.Store.ID != nil {- diagnostics["device_store"] = map[string]interface{}{- "device_id": s.client.Store.ID.String(),- "user": s.client.Store.ID.User,- "device": s.client.Store.ID.Device,- "server": s.client.Store.ID.Server,- }- }-- return diagnostics-}--func (s *Service) GetEventChannel() <-chan Event {- return s.events-}--func (s *Service) IsConnected() bool {- return s.client.IsConnected()-}--// DownloadMedia downloads media from a message by ID-func (s *Service) DownloadMedia(messageID string) ([]byte, string, error) {- s.mu.Lock()- msg, exists := s.messages[messageID]- cachedCount := len(s.messages)- s.mu.Unlock()-- if !exists {- s.logger.Warnf("Media download failed: message %s not found in cache (cached: %d messages)", messageID, cachedCount)- return nil, "", fmt.Errorf("message not found or expired (message_id: %s, cached: %d)", messageID, cachedCount)- }-- // Download media based on message type- var data []byte- var err error- var mimeType string- var mediaType string-- ctx := context.Background()-- switch {- case msg.Message.ImageMessage != nil:- mediaType = "image"- s.logger.Infof("Downloading image from message %s", messageID)- data, err = s.client.Download(ctx, msg.Message.ImageMessage)- mimeType = msg.Message.ImageMessage.GetMimetype()- case msg.Message.VideoMessage != nil:- mediaType = "video"- s.logger.Infof("Downloading video from message %s", messageID)- data, err = s.client.Download(ctx, msg.Message.VideoMessage)- mimeType = msg.Message.VideoMessage.GetMimetype()- case msg.Message.AudioMessage != nil:- mediaType = "audio"- s.logger.Infof("Downloading audio from message %s", messageID)- data, err = s.client.Download(ctx, msg.Message.AudioMessage)- mimeType = msg.Message.AudioMessage.GetMimetype()- case msg.Message.DocumentMessage != nil:- mediaType = "document"- s.logger.Infof("Downloading document from message %s", messageID)- data, err = s.client.Download(ctx, msg.Message.DocumentMessage)- mimeType = msg.Message.DocumentMessage.GetMimetype()- case msg.Message.StickerMessage != nil:- mediaType = "sticker"- s.logger.Infof("Downloading sticker from message %s", messageID)- data, err = s.client.Download(ctx, msg.Message.StickerMessage)- mimeType = msg.Message.StickerMessage.GetMimetype()- default:- s.logger.Warnf("Media download failed: message %s does not contain downloadable media", messageID)- return nil, "", fmt.Errorf("message does not contain downloadable media")- }-- if err != nil {- s.logger.Errorf("Failed to download %s from message %s: %v", mediaType, messageID, err)- return nil, "", fmt.Errorf("failed to download %s: %w", mediaType, err)- }-- s.logger.Infof("Successfully downloaded %s from message %s (%d bytes, %s)", mediaType, messageID, len(data), mimeType)- return data, mimeType, nil-}--// resolveParticipantPhone gets the real phone number for a participant-// Uses LID store to resolve if PhoneNumber is empty and JID is a LID-func (s *Service) resolveParticipantPhone(ctx context.Context, p types.GroupParticipant) string {- // First try PhoneNumber field- if p.PhoneNumber.User != "" {- return p.PhoneNumber.User- }-- // Check if JID is a LID (ends with @lid server)- if p.JID.Server == "lid" && s.client.Store.LIDs != nil {- // Try to resolve LID to phone number- pn, err := s.client.Store.LIDs.GetPNForLID(ctx, p.JID)- if err == nil && pn.User != "" {- return pn.User- }- }-- // Fall back to JID.User- return p.JID.User-}--// GetContactName looks up a contact name by phone number-// Prefers user's saved name, falls back to push name-func (s *Service) GetContactName(phone string) string {- if s.client == nil || s.client.Store == nil || s.client.Store.Contacts == nil {- return ""- }-- jid := types.NewJID(phone, types.DefaultUserServer)- contact, err := s.client.Store.Contacts.GetContact(context.Background(), jid)- if err != nil {- return ""- }-- // Prefer user's saved name, fall back to push name- if contact.FullName != "" {- return contact.FullName- }- return contact.PushName-}--// GetContacts returns all stored contacts with names-func (s *Service) GetContacts(query string) ([]ContactInfo, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- ctx := context.Background()- contacts, err := s.client.Store.Contacts.GetAllContacts(ctx)- if err != nil {- return nil, fmt.Errorf("failed to get contacts: %w", err)- }-- result := make([]ContactInfo, 0)- queryLower := strings.ToLower(query)-- for jid, info := range contacts {- // Skip non-user JIDs (groups, etc.)- if jid.Server != types.DefaultUserServer {- continue- }-- // Filter by query if provided- if query != "" {- nameMatch := strings.Contains(strings.ToLower(info.FullName), queryLower) ||- strings.Contains(strings.ToLower(info.PushName), queryLower) ||- strings.Contains(jid.User, query)- if !nameMatch {- continue- }- }-- result = append(result, ContactInfo{- JID: jid.String(),- Phone: jid.User,- Name: info.FullName,- PushName: info.PushName,- IsContact: true,- })- }-- s.logger.Infof("Retrieved %d contacts (query: %q)", len(result), query)- return result, nil-}--// GetContactInfo returns full info for a single contact (for send/reply use case)-func (s *Service) GetContactInfo(phone string) (*ContactInfo, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- // Clean phone number - remove + prefix if present- phone = strings.TrimPrefix(phone, "+")-- jid := types.NewJID(phone, types.DefaultUserServer)- ctx := context.Background()-- result := &ContactInfo{- JID: jid.String(),- Phone: jid.User,- }-- // Get contact details from store (saved names)- if s.client.Store != nil && s.client.Store.Contacts != nil {- contact, err := s.client.Store.Contacts.GetContact(ctx, jid)- if err == nil {- result.Name = contact.FullName- result.PushName = contact.PushName- result.BusinessName = contact.BusinessName- result.IsContact = true- }- }-- // Check WhatsApp registration + business info- resp, err := s.client.IsOnWhatsApp(ctx, []string{"+" + jid.User})- if err == nil && len(resp) > 0 {- if resp[0].VerifiedName != nil {- result.IsBusiness = true- result.BusinessName = resp[0].VerifiedName.Details.GetVerifiedName()- }- }-- // Get profile photo URL- picInfo, err := s.client.GetProfilePictureInfo(ctx, jid, &whatsmeow.GetProfilePictureParams{Preview: false})- if err == nil && picInfo != nil && picInfo.URL != "" {- result.ProfilePic = picInfo.URL- }-- s.logger.Infof("Retrieved contact info for %s: name=%q", phone, result.Name)- return result, nil-}--// generateGroupsJSON fetches all groups and saves to data/groups.json-// Called automatically on WhatsApp connection for fast offline access-func (s *Service) generateGroupsJSON() error {- if !s.client.IsConnected() {- return fmt.Errorf("not connected")- }-- ctx := context.Background()- groups, err := s.client.GetJoinedGroups(ctx)- if err != nil {- return fmt.Errorf("failed to get groups: %w", err)- }-- // Build indexed structure for fast lookups- groupsMap := make(map[string]interface{})- phoneToGroups := make(map[string][]string)-- for _, g := range groups {- participantsMap := make(map[string]interface{})-- for _, p := range g.Participants {- phone := s.resolveParticipantPhone(ctx, p)- participantsMap[phone] = map[string]interface{}{- "jid": p.JID.String(),- "phone": phone,- "is_admin": p.IsAdmin,- "is_super_admin": p.IsSuperAdmin,- }- // Build reverse index: phone -> groups- phoneToGroups[phone] = append(phoneToGroups[phone], g.JID.String())- }-- groupsMap[g.JID.String()] = map[string]interface{}{- "jid": g.JID.String(),- "name": g.Name,- "topic": g.Topic,- "owner": g.OwnerJID.String(),- "size": len(g.Participants),- "is_announce": g.IsAnnounce,- "is_locked": g.IsLocked,- "created_at": g.GroupCreated,- "participants": participantsMap,- }- }-- data := map[string]interface{}{- "generated_at": time.Now().UTC(),- "device_id": s.client.Store.ID.String(),- "groups": groupsMap,- "phone_to_groups": phoneToGroups,- }-- // Ensure data directory exists- if err := os.MkdirAll("data", 0755); err != nil {- return fmt.Errorf("failed to create data directory: %w", err)- }-- // Write JSON file with pretty formatting- jsonData, err := json.MarshalIndent(data, "", " ")- if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)- }-- if err := os.WriteFile("data/groups.json", jsonData, 0644); err != nil {- return fmt.Errorf("failed to write file: %w", err)- }-- s.logger.Infof("Generated data/groups.json with %d groups", len(groups))- return nil-}--// GetGroups returns all groups the user is a member of-func (s *Service) GetGroups() ([]GroupInfo, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- ctx := context.Background()- groups, err := s.client.GetJoinedGroups(ctx)- if err != nil {- s.logger.Errorf("Failed to get joined groups: %v", err)- return nil, fmt.Errorf("failed to get groups: %w", err)- }-- result := make([]GroupInfo, 0, len(groups))- for _, g := range groups {- participants := make([]GroupParticipant, 0, len(g.Participants))- for _, p := range g.Participants {- phone := s.resolveParticipantPhone(ctx, p)- participants = append(participants, GroupParticipant{- JID: p.JID.String(),- Phone: phone,- Name: s.GetContactName(phone),- IsAdmin: p.IsAdmin,- IsSuperAdmin: p.IsSuperAdmin,- })- }-- result = append(result, GroupInfo{- JID: g.JID.String(),- Name: g.Name,- Topic: g.Topic,- Owner: g.OwnerJID.String(),- Participants: participants,- CreatedAt: g.GroupCreated,- Size: len(g.Participants),- IsAnnounce: g.IsAnnounce,- IsLocked: g.IsLocked,- IsCommunity: g.IsParent,- })- }-- s.logger.Infof("Retrieved %d groups", len(result))- return result, nil-}--// GetGroupInfo returns detailed information about a specific group-func (s *Service) GetGroupInfo(groupJID string) (*GroupInfo, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(groupJID)- if err != nil {- return nil, fmt.Errorf("invalid group JID: %w", err)- }-- ctx := context.Background()- info, err := s.client.GetGroupInfo(ctx, jid)- if err != nil {- s.logger.Errorf("Failed to get group info for %s: %v", groupJID, err)- return nil, fmt.Errorf("failed to get group info: %w", err)- }-- participants := make([]GroupParticipant, 0, len(info.Participants))- for _, p := range info.Participants {- phone := s.resolveParticipantPhone(ctx, p)- participants = append(participants, GroupParticipant{- JID: p.JID.String(),- Phone: phone,- Name: s.GetContactName(phone),- IsAdmin: p.IsAdmin,- IsSuperAdmin: p.IsSuperAdmin,- })- }-- result := &GroupInfo{- JID: info.JID.String(),- Name: info.Name,- Topic: info.Topic,- Owner: info.OwnerJID.String(),- Participants: participants,- CreatedAt: info.GroupCreated,- Size: len(info.Participants),- IsAnnounce: info.IsAnnounce,- IsLocked: info.IsLocked,- IsCommunity: info.IsParent,- }-- s.logger.Infof("Retrieved info for group %s (%s)", info.Name, groupJID)- return result, nil-}--// UpdateGroupInfo updates the name and/or topic of a group-func (s *Service) UpdateGroupInfo(groupJID, name, topic string) error {- if !s.client.IsConnected() {- return fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(groupJID)- if err != nil {- return fmt.Errorf("invalid group JID: %w", err)- }-- ctx := context.Background()-- // Update name if provided- if name != "" {- err = s.client.SetGroupName(ctx, jid, name)- if err != nil {- s.logger.Errorf("Failed to update group name for %s: %v", groupJID, err)- return fmt.Errorf("failed to update group name: %w", err)- }- s.logger.Infof("Updated group name for %s to: %s", groupJID, name)- }-- // Update topic/description if provided- if topic != "" {- // SetGroupTopic requires: ctx, jid, previousTopicID, newTopicID, topic- // Using empty strings for topic IDs as they're optional for setting new topic- err = s.client.SetGroupTopic(ctx, jid, "", "", topic)- if err != nil {- s.logger.Errorf("Failed to update group topic for %s: %v", groupJID, err)- return fmt.Errorf("failed to update group topic: %w", err)- }- s.logger.Infof("Updated group topic for %s", groupJID)- }-- return nil-}--// CheckContacts checks if phone numbers are registered on WhatsApp-func (s *Service) CheckContacts(phones []string) ([]ContactCheckResult, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- ctx := context.Background()- results, err := s.client.IsOnWhatsApp(ctx, phones)- if err != nil {- s.logger.Errorf("Failed to check contacts: %v", err)- return nil, fmt.Errorf("failed to check contacts: %w", err)- }-- response := make([]ContactCheckResult, 0, len(results))- for _, r := range results {- result := ContactCheckResult{- Query: r.Query,- IsRegistered: r.IsIn,- }- if r.IsIn && r.JID.User != "" {- result.JID = r.JID.String()- }- if r.VerifiedName != nil {- result.IsBusiness = true- result.BusinessName = r.VerifiedName.Details.GetVerifiedName()- }- response = append(response, result)- }-- s.logger.Infof("Checked %d phone numbers, %d registered", len(phones), countRegistered(response))- return response, nil-}--func countRegistered(results []ContactCheckResult) int {- count := 0- for _, r := range results {- if r.IsRegistered {- count++- }- }- return count-}--// GetProfilePicture gets profile picture for a JID-func (s *Service) GetProfilePicture(jidStr string, preview bool) (*ProfilePicResult, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(jidStr)- if err != nil {- return nil, fmt.Errorf("invalid JID: %w", err)- }-- ctx := context.Background()- params := &whatsmeow.GetProfilePictureParams{- Preview: preview,- }-- info, err := s.client.GetProfilePictureInfo(ctx, jid, params)- if err != nil {- // Profile picture may not exist - this is not an error- errStr := err.Error()- if strings.Contains(errStr, "item-not-found") || strings.Contains(errStr, "not-authorized") {- return &ProfilePicResult{Exists: false}, nil- }- s.logger.Errorf("Failed to get profile picture for %s: %v", jidStr, err)- return nil, fmt.Errorf("failed to get profile picture: %w", err)- }-- result := &ProfilePicResult{- Exists: true,- URL: info.URL,- ID: info.ID,- }-- s.logger.Infof("Retrieved profile picture for %s", jidStr)- return result, nil-}--// SendTyping sends typing indicator to a chat-func (s *Service) SendTyping(jidStr, state, media string) error {- if !s.client.IsConnected() {- return fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(jidStr)- if err != nil {- return fmt.Errorf("invalid JID: %w", err)- }-- // Convert state string to ChatPresence- var chatPresence types.ChatPresence- switch state {- case "composing":- chatPresence = types.ChatPresenceComposing- case "paused":- chatPresence = types.ChatPresencePaused- default:- return fmt.Errorf("invalid state: %s (must be 'composing' or 'paused')", state)- }-- // Convert media string to ChatPresenceMedia- var chatMedia types.ChatPresenceMedia- switch media {- case "", "text":- chatMedia = types.ChatPresenceMediaText- case "audio":- chatMedia = types.ChatPresenceMediaAudio- default:- return fmt.Errorf("invalid media: %s (must be 'text' or 'audio')", media)- }-- ctx := context.Background()- err = s.client.SendChatPresence(ctx, jid, chatPresence, chatMedia)- if err != nil {- s.logger.Errorf("Failed to send typing indicator to %s: %v", jidStr, err)- return fmt.Errorf("failed to send typing indicator: %w", err)- }-- s.logger.Infof("Sent typing indicator (%s) to %s", state, jidStr)- return nil-}--// SetPresence sets online/offline presence status-func (s *Service) SetPresence(status string) error {- if !s.client.IsConnected() {- return fmt.Errorf("WhatsApp not connected")- }-- var presence types.Presence- switch status {- case "available", "online":- presence = types.PresenceAvailable- case "unavailable", "offline":- presence = types.PresenceUnavailable- default:- return fmt.Errorf("invalid status: %s (must be 'available' or 'unavailable')", status)- }-- ctx := context.Background()- err := s.client.SendPresence(ctx, presence)- if err != nil {- s.logger.Errorf("Failed to set presence to %s: %v", status, err)- return fmt.Errorf("failed to set presence: %w", err)- }-- s.logger.Infof("Set presence to %s", status)- return nil-}--// MarkRead marks messages as read-func (s *Service) MarkRead(messageIDs []string, chatJID, senderJID string) error {- if !s.client.IsConnected() {- return fmt.Errorf("WhatsApp not connected")- }-- if len(messageIDs) == 0 {- return fmt.Errorf("at least one message_id is required")- }-- chat, err := types.ParseJID(chatJID)- if err != nil {- return fmt.Errorf("invalid chat_jid: %w", err)- }-- // For DMs, sender is the same as chat- // For groups, sender is the actual message sender- sender := chat- if senderJID != "" {- sender, err = types.ParseJID(senderJID)- if err != nil {- return fmt.Errorf("invalid sender_jid: %w", err)- }- }-- ctx := context.Background()- err = s.client.MarkRead(ctx, messageIDs, time.Now(), chat, sender)- if err != nil {- s.logger.Errorf("Failed to mark messages as read: %v", err)- return fmt.Errorf("failed to mark messages as read: %w", err)- }-- s.logger.Infof("Marked %d message(s) as read in %s", len(messageIDs), chatJID)- return nil-}--// normalizeToJID converts a phone number or JID string to types.JID-func (s *Service) normalizeToJID(input string) (types.JID, error) {- // If it's already a JID (contains @), parse it directly- if strings.Contains(input, "@") {- return types.ParseJID(input)- }-- // Otherwise, treat as phone number and create user JID- // Remove any non-digit characters- phone := strings.Map(func(r rune) rune {- if r >= '0' && r <= '9' {- return r- }- return -1- }, input)-- if phone == "" {- return types.JID{}, fmt.Errorf("invalid phone number: %s", input)- }-- return types.NewJID(phone, types.DefaultUserServer), nil-}--// AddGroupParticipants adds participants to a group-func (s *Service) AddGroupParticipants(groupJID string, participants []string) (*GroupParticipantsResult, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(groupJID)- if err != nil {- return nil, fmt.Errorf("invalid group JID: %w", err)- }-- // Convert phone numbers/JIDs to types.JID slice- participantJIDs := make([]types.JID, 0, len(participants))- for _, p := range participants {- pJID, err := s.normalizeToJID(p)- if err != nil {- s.logger.Warnf("Invalid participant %s: %v", p, err)- continue- }- participantJIDs = append(participantJIDs, pJID)- }-- if len(participantJIDs) == 0 {- return nil, fmt.Errorf("no valid participants provided")- }-- ctx := context.Background()- results, err := s.client.UpdateGroupParticipants(ctx, jid, participantJIDs, whatsmeow.ParticipantChangeAdd)- if err != nil {- s.logger.Errorf("Failed to add participants to %s: %v", groupJID, err)- return nil, fmt.Errorf("failed to add participants: %w", err)- }-- // Build result- response := &GroupParticipantsResult{- GroupID: groupJID,- Action: "add",- Results: make([]GroupParticipantChangeResult, 0, len(results)),- }-- for _, r := range results {- result := GroupParticipantChangeResult{- JID: r.JID.String(),- Phone: r.JID.User,- Success: r.Error == 0, // 0 means success- }- if r.Error != 0 {- result.Error = fmt.Sprintf("error code: %d", r.Error)- response.Failed++- } else {- response.Added++- }- response.Results = append(response.Results, result)- }-- s.logger.Infof("Added %d participants to group %s (failed: %d)", response.Added, groupJID, response.Failed)- return response, nil-}--// RemoveGroupParticipants removes participants from a group-func (s *Service) RemoveGroupParticipants(groupJID string, participants []string) (*GroupParticipantsResult, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(groupJID)- if err != nil {- return nil, fmt.Errorf("invalid group JID: %w", err)- }-- // Convert phone numbers/JIDs to types.JID slice- participantJIDs := make([]types.JID, 0, len(participants))- for _, p := range participants {- pJID, err := s.normalizeToJID(p)- if err != nil {- s.logger.Warnf("Invalid participant %s: %v", p, err)- continue- }- participantJIDs = append(participantJIDs, pJID)- }-- if len(participantJIDs) == 0 {- return nil, fmt.Errorf("no valid participants provided")- }-- ctx := context.Background()- results, err := s.client.UpdateGroupParticipants(ctx, jid, participantJIDs, whatsmeow.ParticipantChangeRemove)- if err != nil {- s.logger.Errorf("Failed to remove participants from %s: %v", groupJID, err)- return nil, fmt.Errorf("failed to remove participants: %w", err)- }-- // Build result- response := &GroupParticipantsResult{- GroupID: groupJID,- Action: "remove",- Results: make([]GroupParticipantChangeResult, 0, len(results)),- }-- for _, r := range results {- result := GroupParticipantChangeResult{- JID: r.JID.String(),- Phone: r.JID.User,- Success: r.Error == 0,- }- if r.Error != 0 {- result.Error = fmt.Sprintf("error code: %d", r.Error)- response.Failed++- } else {- response.Removed++- }- response.Results = append(response.Results, result)- }-- s.logger.Infof("Removed %d participants from group %s (failed: %d)", response.Removed, groupJID, response.Failed)- return response, nil-}--// GetGroupInviteLink gets the invite link for a group-func (s *Service) GetGroupInviteLink(groupJID string) (*GroupInviteLinkResult, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(groupJID)- if err != nil {- return nil, fmt.Errorf("invalid group JID: %w", err)- }-- ctx := context.Background()- link, err := s.client.GetGroupInviteLink(ctx, jid, false)- if err != nil {- s.logger.Errorf("Failed to get invite link for %s: %v", groupJID, err)- return nil, fmt.Errorf("failed to get invite link: %w", err)- }-- s.logger.Infof("Retrieved invite link for group %s", groupJID)- return &GroupInviteLinkResult{- GroupID: groupJID,- InviteLink: link,- Revoked: false,- }, nil-}--// RevokeGroupInviteLink revokes the current invite link and generates a new one-func (s *Service) RevokeGroupInviteLink(groupJID string) (*GroupInviteLinkResult, error) {- if !s.client.IsConnected() {- return nil, fmt.Errorf("WhatsApp not connected")- }-- jid, err := types.ParseJID(groupJID)- if err != nil {- return nil, fmt.Errorf("invalid group JID: %w", err)- }-- ctx := context.Background()- // reset=true revokes the old link and generates new one- link, err := s.client.GetGroupInviteLink(ctx, jid, true)- if err != nil {- s.logger.Errorf("Failed to revoke invite link for %s: %v", groupJID, err)- return nil, fmt.Errorf("failed to revoke invite link: %w", err)- }-- s.logger.Infof("Revoked and regenerated invite link for group %s", groupJID)- return &GroupInviteLinkResult{- GroupID: groupJID,- InviteLink: link,- Revoked: true,- }, nil-}--// GetCurrentQRCode returns the last generated QR code if recent-func (s *Service) GetCurrentQRCode() *QRCodeData {- s.mu.Lock()- defer s.mu.Unlock()-- if s.lastQRCode == nil {- return nil- }-- // Return QR if it was generated within last 60 seconds- if time.Since(s.lastQRCodeTime) > 60*time.Second {- return nil- }-- return s.lastQRCode-}--// ============================================================================-// Rate Limiting Methods-// ============================================================================--// GetRateLimitConfig returns the current rate limit configuration-func (s *Service) GetRateLimitConfig() *RateLimitConfig {- s.rateMu.Lock()- defer s.rateMu.Unlock()- return s.rateLimitConfig-}--// SetRateLimitConfig updates the rate limit configuration-func (s *Service) SetRateLimitConfig(config *RateLimitConfig) error {- s.rateMu.Lock()- defer s.rateMu.Unlock()-- // Validate config- if config.MinDelayMs < 0 {- return fmt.Errorf("min_delay_ms cannot be negative")- }- if config.MaxDelayMs < config.MinDelayMs {- config.MaxDelayMs = config.MinDelayMs- }- if config.MaxMessagesPerMinute < 0 {- config.MaxMessagesPerMinute = 0- }- if config.MaxMessagesPerHour < 0 {- config.MaxMessagesPerHour = 0- }- if config.MaxNewContactsPerDay < 0 {- config.MaxNewContactsPerDay = 0- }-- s.rateLimitConfig = config- s.logger.Infof("Rate limit config updated: enabled=%v, delay=%d-%dms, typing=%v",- config.Enabled, config.MinDelayMs, config.MaxDelayMs, config.SimulateTyping)- return nil-}--// GetRateLimitStats returns current rate limiting statistics-func (s *Service) GetRateLimitStats() *RateLimitStats {- s.rateMu.Lock()- defer s.rateMu.Unlock()-- // Reset daily counters if needed- s.resetDailyCountersIfNeeded()-- // Calculate stats from sliding window- now := time.Now()- minuteAgo := now.Add(-1 * time.Minute)- hourAgo := now.Add(-1 * time.Hour)-- minuteCount := 0- hourCount := 0- for _, t := range s.messageTimes {- if t.After(minuteAgo) {- minuteCount++- }- if t.After(hourAgo) {- hourCount++- }- }-- // Count new contacts today- newContactsCount := 0- for _, t := range s.newContactsToday {- if t.After(s.dailyResetTime) {- newContactsCount++- }- }-- // Calculate response rate (simplified - based on messages received vs sent)- responseRate := 0.0- if s.rateLimitStats.MessagesSentToday > 0 {- responseRate = float64(s.rateLimitStats.ResponsesReceived) / float64(s.rateLimitStats.MessagesSentToday)- }-- // Calculate next allowed time- nextAllowed := s.rateLimitStats.LastMessageTime.Add(time.Duration(s.rateLimitConfig.MinDelayMs) * time.Millisecond)-- return &RateLimitStats{- MessagesSentLastMinute: minuteCount,- MessagesSentLastHour: hourCount,- MessagesSentToday: s.rateLimitStats.MessagesSentToday,- NewContactsToday: newContactsCount,- ResponsesReceived: s.rateLimitStats.ResponsesReceived,- ResponseRate: responseRate,- IsPaused: s.rateLimitStats.IsPaused,- PauseReason: s.rateLimitStats.PauseReason,- LastMessageTime: s.rateLimitStats.LastMessageTime,- NextAllowedTime: nextAllowed,- }-}--// resetDailyCountersIfNeeded resets daily counters at midnight-func (s *Service) resetDailyCountersIfNeeded() {- now := time.Now()- // Check if we've crossed midnight since last reset- if now.Day() != s.dailyResetTime.Day() || now.Month() != s.dailyResetTime.Month() {- s.rateLimitStats.MessagesSentToday = 0- s.rateLimitStats.ResponsesReceived = 0- s.newContactsToday = make(map[string]time.Time)- s.dailyResetTime = now- s.logger.Info("Daily rate limit counters reset")- }-}--// CheckRateLimit checks rate limits and waits if necessary. Returns error only for hard limits.-func (s *Service) CheckRateLimit(recipient string) error {- s.rateMu.Lock()- config := s.rateLimitConfig- s.rateMu.Unlock()-- if !config.Enabled {- return nil- }-- // Keep checking and waiting until we're within limits- for {- waitDuration, hardError := s.checkRateLimitInternal(recipient)- if hardError != nil {- return hardError // New contacts limit or paused - can't wait- }- if waitDuration <= 0 {- return nil // Within limits, proceed- }-- // Wait until we're within rate limits- s.logger.Infof("Rate limit reached, waiting %v before sending...", waitDuration)- time.Sleep(waitDuration)- }-}--// checkRateLimitInternal checks limits and returns wait duration or hard error-func (s *Service) checkRateLimitInternal(recipient string) (time.Duration, error) {- s.rateMu.Lock()- defer s.rateMu.Unlock()-- // Reset daily counters if needed- s.resetDailyCountersIfNeeded()-- // Check if paused - this is a hard error, can't wait- if s.rateLimitStats.IsPaused {- return 0, fmt.Errorf("rate limiting paused: %s", s.rateLimitStats.PauseReason)- }-- now := time.Now()-- // Clean up old message times (keep only last hour)- hourAgo := now.Add(-1 * time.Hour)- newTimes := make([]time.Time, 0, len(s.messageTimes))- for _, t := range s.messageTimes {- if t.After(hourAgo) {- newTimes = append(newTimes, t)- }- }- s.messageTimes = newTimes-- // Count messages in last minute and hour- minuteAgo := now.Add(-1 * time.Minute)- minuteCount := 0- hourCount := len(s.messageTimes)-- // Find oldest message in last minute (to calculate wait time)- var oldestInMinute time.Time- var oldestInHour time.Time- for _, t := range s.messageTimes {- if t.After(minuteAgo) {- minuteCount++- if oldestInMinute.IsZero() || t.Before(oldestInMinute) {- oldestInMinute = t- }- }- if oldestInHour.IsZero() || t.Before(oldestInHour) {- oldestInHour = t- }- }-- // Check per-minute limit - calculate wait time if exceeded- if s.rateLimitConfig.MaxMessagesPerMinute > 0 && minuteCount >= s.rateLimitConfig.MaxMessagesPerMinute {- // Wait until oldest message in minute window expires- waitUntil := oldestInMinute.Add(1 * time.Minute)- waitDuration := waitUntil.Sub(now) + 100*time.Millisecond // Add small buffer- if waitDuration > 0 {- s.logger.Debugf("Per-minute limit reached (%d/%d), need to wait %v",- minuteCount, s.rateLimitConfig.MaxMessagesPerMinute, waitDuration)- return waitDuration, nil- }- }-- // Check per-hour limit - calculate wait time if exceeded- if s.rateLimitConfig.MaxMessagesPerHour > 0 && hourCount >= s.rateLimitConfig.MaxMessagesPerHour {- // Wait until oldest message in hour window expires- waitUntil := oldestInHour.Add(1 * time.Hour)- waitDuration := waitUntil.Sub(now) + 100*time.Millisecond // Add small buffer- if waitDuration > 0 {- s.logger.Debugf("Per-hour limit reached (%d/%d), need to wait %v",- hourCount, s.rateLimitConfig.MaxMessagesPerHour, waitDuration)- return waitDuration, nil- }- }-- // Check new contacts limit - this is a HARD limit, return error (can't wait for tomorrow)- if s.rateLimitConfig.MaxNewContactsPerDay > 0 {- if _, seen := s.contactsSeen[recipient]; !seen {- newContactsCount := 0- for _, t := range s.newContactsToday {- if t.After(s.dailyResetTime) {- newContactsCount++- }- }- if newContactsCount >= s.rateLimitConfig.MaxNewContactsPerDay {- return 0, fmt.Errorf("new contacts limit exceeded: %d new contacts/day (max: %d) - try again tomorrow",- newContactsCount, s.rateLimitConfig.MaxNewContactsPerDay)- }- }- }-- // Check response rate threshold (if enabled) - hard error- if s.rateLimitConfig.PauseOnLowResponse && s.rateLimitStats.MessagesSentToday >= 10 {- responseRate := float64(s.rateLimitStats.ResponsesReceived) / float64(s.rateLimitStats.MessagesSentToday)- if responseRate < s.rateLimitConfig.ResponseRateThreshold {- s.rateLimitStats.IsPaused = true- s.rateLimitStats.PauseReason = fmt.Sprintf("low response rate: %.1f%% (threshold: %.1f%%)",- responseRate*100, s.rateLimitConfig.ResponseRateThreshold*100)- return 0, fmt.Errorf("rate limiting paused: %s", s.rateLimitStats.PauseReason)- }- }-- return 0, nil // Within all limits-}--// ApplyMessageDelay applies the configured delay before sending a message-func (s *Service) ApplyMessageDelay(hasLinks bool) {- s.rateMu.Lock()- config := s.rateLimitConfig- s.rateMu.Unlock()-- if !config.Enabled || config.MinDelayMs <= 0 {- return- }-- delay := config.MinDelayMs-- // Add randomization if enabled- if config.RandomizeDelays && config.MaxDelayMs > config.MinDelayMs {- delay = config.MinDelayMs + rand.Intn(config.MaxDelayMs-config.MinDelayMs)- }-- // Add extra delay for messages with links- if hasLinks && config.LinkExtraDelayMs > 0 {- delay += config.LinkExtraDelayMs- }-- s.logger.Debugf("Applying message delay: %dms (links: %v)", delay, hasLinks)- time.Sleep(time.Duration(delay) * time.Millisecond)-}--// SendTypingIfEnabled sends typing indicator if configured-// The typing indicator stays active until the message is sent-func (s *Service) SendTypingIfEnabled(jidStr string) {- s.rateMu.Lock()- config := s.rateLimitConfig- s.rateMu.Unlock()-- if !config.Enabled || !config.SimulateTyping || config.TypingDelayMs <= 0 {- return- }-- // Parse JID- jid, err := types.ParseJID(jidStr)- if err != nil {- s.logger.Debugf("Could not parse JID for typing indicator: %v", err)- return- }-- // Send composing indicator - stays active until message is sent- ctx := context.Background()- err = s.client.SendChatPresence(ctx, jid, types.ChatPresenceComposing, types.ChatPresenceMediaText)- if err != nil {- s.logger.Debugf("Failed to send typing indicator: %v", err)- return- }-- s.logger.Debugf("Sent typing indicator to %s, waiting %dms", jidStr, config.TypingDelayMs)-- // Wait for typing duration (indicator stays active)- time.Sleep(time.Duration(config.TypingDelayMs) * time.Millisecond)-- // No paused indicator - typing stays active until message is sent- // WhatsApp clears the typing indicator when the message arrives-}--// RecordMessageSent updates rate limiting stats after a message is sent-func (s *Service) RecordMessageSent(recipient string) {- s.rateMu.Lock()- defer s.rateMu.Unlock()-- now := time.Now()-- // Record message time- s.messageTimes = append(s.messageTimes, now)- s.rateLimitStats.MessagesSentToday++- s.rateLimitStats.LastMessageTime = now-- // Track new contacts- if _, seen := s.contactsSeen[recipient]; !seen {- s.contactsSeen[recipient] = true- s.newContactsToday[recipient] = now- s.logger.Debugf("New contact recorded: %s (total today: %d)", recipient, len(s.newContactsToday))- }-}--// RecordResponseReceived increments the response counter (call when receiving a message)-func (s *Service) RecordResponseReceived() {- s.rateMu.Lock()- defer s.rateMu.Unlock()- s.rateLimitStats.ResponsesReceived++-}--// UnpauseRateLimiting resumes rate limiting after it was paused-func (s *Service) UnpauseRateLimiting() {- s.rateMu.Lock()- defer s.rateMu.Unlock()- s.rateLimitStats.IsPaused = false- s.rateLimitStats.PauseReason = ""- s.logger.Info("Rate limiting unpaused")-}--func (s *Service) Shutdown() {- if s.shutdown {- return // Already shutdown- }-- s.logger.Info("Shutting down WhatsApp service...")- s.shutdown = true- s.running = false- s.pairing = false-- if s.client != nil {- s.client.Disconnect()- }-- // Give goroutines more time to exit cleanly- time.Sleep(500 * time.Millisecond)-- // Drain any remaining events but DON'T close the channel- // This allows ForwardEvents goroutines to continue working after restart- for {- select {- case <-s.events:- // Keep draining- default:- goto done- }- }- done:-- // DO NOT close(s.events) - keep channel open for restart- s.logger.Info("WhatsApp service shutdown complete")-}--func (s *Service) Reset() error {- s.logger.Info("Starting full reset with logout...")-- // Logout from WhatsApp servers first (invalidates session on server side)- if s.client != nil && s.client.IsLoggedIn() {- s.logger.Info("Logging out from WhatsApp...")- if err := s.client.Logout(context.Background()); err != nil {- s.logger.Warnf("Logout failed (may already be logged out): %v", err)- } else {- s.logger.Info("Logged out from WhatsApp successfully")- }- }-- // Shutdown the service (disconnect, close channels)- s.Shutdown()-- // Delete the device session from store- if s.client != nil && s.client.Store != nil {- s.logger.Info("Deleting device session from store...")- if err := s.client.Store.Delete(context.Background()); err != nil {- s.logger.Warnf("Failed to delete device store: %v", err)- }- }-- // Clear message history (belongs to old instance)- if s.historyStore != nil {- s.logger.Info("Clearing message history...")- if err := s.historyStore.ClearHistory(); err != nil {- s.logger.Warnf("Failed to clear history: %v", err)- }- }-- // Clear client reference to allow GC and release DB locks- s.client = nil- s.container = nil-- // Give time for database to release locks- time.Sleep(500 * time.Millisecond)-- // Reinitialize client with fresh database- if err := s.reinitClient(); err != nil {- s.logger.Errorf("Failed to reinitialize client: %v", err)- return fmt.Errorf("failed to reinitialize client: %w", err)- }-- s.logger.Info("WhatsApp reset complete")- return nil-}--// reinitClient creates a new database and client after reset-func (s *Service) reinitClient() error {- s.logger.Info("Reinitializing WhatsApp client...")-- // Create new database- dbLog := waLog.Stdout("Database", "INFO", true)- ctx := context.Background()- container, err := sqlstore.New(ctx, "sqlite", "file:"+s.dbPath+"?_pragma=foreign_keys(1)&_journal_mode=WAL&_busy_timeout=30000&cache=shared", dbLog)- if err != nil {- return fmt.Errorf("failed to initialize database: %w", err)- }-- // Get device store- deviceStore, err := container.GetFirstDevice(ctx)- if err != nil {- return fmt.Errorf("failed to get device: %w", err)- }-- // Create new client- clientLog := waLog.Stdout("WhatsApp", "INFO", true)- client := whatsmeow.NewClient(deviceStore, clientLog)-- // Update service references- s.container = container- s.client = client-- // Add event handler to new client- client.AddEventHandler(s.eventHandler)-- s.logger.Info("WhatsApp client reinitialized successfully")- return nil-}--func (s *Service) cleanupOldQRCodes() {- s.CleanupQRCodes()-}--// CleanupQRCodes deletes all QR code PNG files-func (s *Service) CleanupQRCodes() {- // Delete all old QR code PNG files- files, err := filepath.Glob("data/qr/qr_*.png")- if err != nil {- s.logger.Warnf("Failed to find old QR code files: %v", err)- return- }-- if len(files) > 0 {- s.logger.Infof("Cleaning up %d old QR code file(s)", len(files))- for _, file := range files {- if err := os.Remove(file); err != nil {- s.logger.Warnf("Failed to delete old QR code file %s: %v", file, err)- } else {- s.logger.Debugf("Deleted old QR code file: %s", file)- }- }- }-- // Clear cached QR code- s.lastQRCode = nil-}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/go/whatsapp/types.go b/server/whatsapp-rpc/src/go/whatsapp/types.godeleted file mode 100644index d73410ed..00000000--- a/server/whatsapp-rpc/src/go/whatsapp/types.go+++ /dev/null@@ -1,261 +0,0 @@-package whatsapp--import "time"--// Event represents a WhatsApp service event-type Event struct {- Type string `json:"type"`- Data map[string]interface{} `json:"data"`- Time time.Time `json:"timestamp"`-}--// QRCodeData represents QR code information-type QRCodeData struct {- Code string `json:"code"`- Filename string `json:"filename"`- ImageData string `json:"image_data,omitempty"` // Base64 PNG data- Time time.Time `json:"timestamp"`-}--// MessageRequest represents various message types for sending-type MessageRequest struct {- Phone string `json:"phone,omitempty"`- GroupID string `json:"group_id,omitempty"`- Message string `json:"message,omitempty"`- Type string `json:"type"` // text, image, document, audio, video, location, sticker, contact- MediaData *MediaData `json:"media_data,omitempty"`- Location *LocationData `json:"location,omitempty"`- Contact *ContactCard `json:"contact,omitempty"`- Reply *ReplyData `json:"reply,omitempty"`- Metadata map[string]string `json:"metadata,omitempty"`-}--// MediaData represents media content for messages-type MediaData struct {- Data string `json:"data"` // base64 encoded data- MimeType string `json:"mime_type"` // image/jpeg, audio/mp3, etc.- Filename string `json:"filename"` // optional filename- Caption string `json:"caption"` // optional caption for media- Thumbnail string `json:"thumbnail"` // base64 encoded thumbnail (optional)-}--// LocationData represents location information-type LocationData struct {- Latitude float64 `json:"latitude"`- Longitude float64 `json:"longitude"`- Name string `json:"name,omitempty"` // optional location name- Address string `json:"address,omitempty"` // optional address-}--// ReplyData represents reply context for messages-type ReplyData struct {- MessageID string `json:"message_id"`- Sender string `json:"sender"`- Content string `json:"content"`-}--// ContactCard represents a contact vCard for sharing-type ContactCard struct {- DisplayName string `json:"display_name"`- VCard string `json:"vcard"` // vCard format string-}--// ContactInfo represents comprehensive contact information-type ContactInfo struct {- JID string `json:"jid"`- Phone string `json:"phone"`- Name string `json:"name,omitempty"`- BusinessName string `json:"business_name,omitempty"`- PushName string `json:"push_name,omitempty"`- IsContact bool `json:"is_contact"`- IsBusiness bool `json:"is_business"`- LastSeen time.Time `json:"last_seen,omitempty"`- ProfilePic string `json:"profile_pic,omitempty"` // base64 encoded-}--// GroupInfo represents comprehensive group information-type GroupInfo struct {- JID string `json:"jid"`- Name string `json:"name"`- Topic string `json:"topic,omitempty"`- Owner string `json:"owner"`- Participants []GroupParticipant `json:"participants"`- CreatedAt time.Time `json:"created_at"`- Size int `json:"size"`- IsAnnounce bool `json:"is_announce"` // Only admins can send messages- IsLocked bool `json:"is_locked"` // Only admins can edit group info- IsCommunity bool `json:"is_community"` // True if this is a community (parent group)-}--// GroupUpdateRequest represents parameters for updating a group-type GroupUpdateRequest struct {- GroupID string `json:"group_id"`- Name string `json:"name,omitempty"`- Topic string `json:"topic,omitempty"`-}--// GroupParticipant represents a group member-type GroupParticipant struct {- JID string `json:"jid"`- Phone string `json:"phone"`- Name string `json:"name,omitempty"`- IsAdmin bool `json:"is_admin"`- IsSuperAdmin bool `json:"is_super_admin"`-}--// MessageInfo represents received message information-type MessageInfo struct {- ID string `json:"id"`- From string `json:"from"`- To string `json:"to"`- Type string `json:"type"`- Content string `json:"content,omitempty"`- MediaInfo *ReceivedMediaInfo `json:"media_info,omitempty"`- Location *LocationData `json:"location,omitempty"`- GroupInfo *GroupMessageInfo `json:"group_info,omitempty"`- Reply *ReplyData `json:"reply,omitempty"`- Timestamp time.Time `json:"timestamp"`- IsFromMe bool `json:"is_from_me"`- Status string `json:"status"` // sent, delivered, read-}--// ReceivedMediaInfo represents received media message information-type ReceivedMediaInfo struct {- MimeType string `json:"mime_type"`- Size int64 `json:"size"`- Filename string `json:"filename,omitempty"`- Caption string `json:"caption,omitempty"`- URL string `json:"url"` // download URL- SHA256 string `json:"sha256"` // file hash-}--// GroupMessageInfo represents group message context-type GroupMessageInfo struct {- GroupJID string `json:"group_jid"`- GroupName string `json:"group_name,omitempty"`- SenderJID string `json:"sender_jid"`- SenderName string `json:"sender_name,omitempty"`-}--// PresenceInfo represents presence information-type PresenceInfo struct {- JID string `json:"jid"`- Status string `json:"status"` // available, unavailable, composing, paused- LastSeen time.Time `json:"last_seen,omitempty"`-}--// WebhookConfig represents webhook configuration-type WebhookConfig struct {- URL string `json:"url"`- Secret string `json:"secret,omitempty"`- Events []string `json:"events"` // message, status, presence, etc.- Headers map[string]string `json:"headers"` // custom headers- Enabled bool `json:"enabled"`-}--// MessageStatus represents delivery status-type MessageStatus struct {- ID string `json:"id"`- Status string `json:"status"` // sent, delivered, read- Timestamp time.Time `json:"timestamp"`- From string `json:"from"`- To string `json:"to"`-}--// ContactCheckResult represents the result of checking if a phone is on WhatsApp-type ContactCheckResult struct {- Query string `json:"query"` // Original phone number queried- JID string `json:"jid,omitempty"` // WhatsApp JID if registered- IsRegistered bool `json:"is_registered"` // Whether registered on WhatsApp- IsBusiness bool `json:"is_business"` // Whether it's a business account- BusinessName string `json:"business_name,omitempty"` // Business verified name-}--// ProfilePicResult represents profile picture information-type ProfilePicResult struct {- URL string `json:"url,omitempty"` // URL to download image- ID string `json:"id,omitempty"` // Image identifier- Data string `json:"data,omitempty"` // Base64-encoded image data- Exists bool `json:"exists"` // Whether profile picture exists-}--// GroupParticipantChangeResult represents result for a single participant change-type GroupParticipantChangeResult struct {- JID string `json:"jid"`- Phone string `json:"phone,omitempty"`- Success bool `json:"success"`- Error string `json:"error,omitempty"`-}--// GroupParticipantsResult represents batch participant change result-type GroupParticipantsResult struct {- GroupID string `json:"group_id"`- Action string `json:"action"` // "add" or "remove"- Results []GroupParticipantChangeResult `json:"results"`- Added int `json:"added,omitempty"`- Removed int `json:"removed,omitempty"`- Failed int `json:"failed"`-}--// GroupInviteLinkResult represents invite link response-type GroupInviteLinkResult struct {- GroupID string `json:"group_id"`- InviteLink string `json:"invite_link"`- Revoked bool `json:"revoked,omitempty"`-}--// RateLimitConfig represents configurable rate limiting settings for anti-ban protection-type RateLimitConfig struct {- Enabled bool `json:"enabled"`-- // Message delays (milliseconds)- MinDelayMs int `json:"min_delay_ms"` // Minimum delay between messages (default: 3000)- MaxDelayMs int `json:"max_delay_ms"` // Maximum delay for randomization (default: 8000)- TypingDelayMs int `json:"typing_delay_ms"` // Typing indicator duration (default: 2000)- LinkExtraDelayMs int `json:"link_extra_delay_ms"` // Extra delay for messages with links (default: 5000)-- // Rate limits- MaxMessagesPerMinute int `json:"max_messages_per_minute"` // Per-minute limit (default: 10)- MaxMessagesPerHour int `json:"max_messages_per_hour"` // Per-hour limit (default: 60)- MaxNewContactsPerDay int `json:"max_new_contacts_per_day"` // New contacts limit (default: 20)-- // Human simulation- SimulateTyping bool `json:"simulate_typing"` // Send typing indicator before message- RandomizeDelays bool `json:"randomize_delays"` // Add random variance to delays-- // Safety- PauseOnLowResponse bool `json:"pause_on_low_response"` // Pause if response rate < threshold- ResponseRateThreshold float64 `json:"response_rate_threshold"` // Min response rate (0.3 = 30%)-}--// RateLimitStats represents current rate limiting statistics-type RateLimitStats struct {- MessagesSentLastMinute int `json:"messages_sent_last_minute"`- MessagesSentLastHour int `json:"messages_sent_last_hour"`- MessagesSentToday int `json:"messages_sent_today"`- NewContactsToday int `json:"new_contacts_today"`- ResponsesReceived int `json:"responses_received"`- ResponseRate float64 `json:"response_rate"`- IsPaused bool `json:"is_paused"`- PauseReason string `json:"pause_reason,omitempty"`- LastMessageTime time.Time `json:"last_message_time"`- NextAllowedTime time.Time `json:"next_allowed_time"`-}--// DefaultRateLimitConfig returns conservative defaults for anti-ban protection-func DefaultRateLimitConfig() *RateLimitConfig {- return &RateLimitConfig{- Enabled: true,- MinDelayMs: 3000, // 3 seconds minimum- MaxDelayMs: 8000, // Up to 8 seconds with randomization- TypingDelayMs: 2000, // 2 seconds typing- LinkExtraDelayMs: 5000, // 5 extra seconds for links- MaxMessagesPerMinute: 10, // Conservative- MaxMessagesPerHour: 60, // 1 per minute average- MaxNewContactsPerDay: 20, // Critical for new accounts- SimulateTyping: true, // Major anti-detection- RandomizeDelays: true, // Avoid fixed patterns- PauseOnLowResponse: false, // Disabled by default- ResponseRateThreshold: 0.3, // 30% minimum- }-}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/python/pyproject.toml b/server/whatsapp-rpc/src/python/pyproject.tomldeleted file mode 100644index 38b277a2..00000000--- a/server/whatsapp-rpc/src/python/pyproject.toml+++ /dev/null@@ -1,15 +0,0 @@-[build-system]-requires = ["setuptools>=61.0"]-build-backend = "setuptools.build_meta"--[project]-name = "whatsapp-rpc"-version = "1.0.0"-description = "Python client for WhatsApp RPC API"-requires-python = ">=3.8"-dependencies = [- "websockets>=12.0",-]--[tool.setuptools.packages.find]-where = ["."]diff --git a/server/whatsapp-rpc/src/python/whatsapp_rpc/__init__.py b/server/whatsapp-rpc/src/python/whatsapp_rpc/__init__.pydeleted file mode 100644index 60db3f6a..00000000--- a/server/whatsapp-rpc/src/python/whatsapp_rpc/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-from .client import WhatsAppRPCClient--__version__ = "1.0.0"-__all__ = ["WhatsAppRPCClient"]diff --git a/server/whatsapp-rpc/src/python/whatsapp_rpc/client.py b/server/whatsapp-rpc/src/python/whatsapp_rpc/client.pydeleted file mode 100644index eee7b64c..00000000--- a/server/whatsapp-rpc/src/python/whatsapp_rpc/client.py+++ /dev/null@@ -1,427 +0,0 @@-"""-WhatsApp RPC Client - Async JSON-RPC 2.0 client over WebSocket--Uses the official `websockets` library for stable async WebSocket communication.-Implements JSON-RPC 2.0 protocol for bidirectional communication with Go backend.-"""--import asyncio-import json-import logging-from typing import Any, Callable, Optional--import websockets-from websockets.exceptions import ConnectionClosed--logger = logging.getLogger(__name__)---class WhatsAppRPCClient:- """Async JSON-RPC 2.0 client using official websockets library."""-- def __init__(self, ws_url: str):- """- Initialize RPC client.-- Args:- ws_url: WebSocket URL (e.g., 'ws://localhost:9400/ws/rpc')- """- self.ws_url = ws_url- self.ws = None- self.request_id = 0- self.pending: dict[int, asyncio.Future] = {}- self.event_callback: Optional[Callable[[dict], None]] = None- self._recv_task: Optional[asyncio.Task] = None- self._connected = False-- @property- def connected(self) -> bool:- """Check if WebSocket is connected."""- return self._connected and self.ws is not None-- async def connect(self) -> None:- """Connect to WebSocket RPC endpoint."""- try:- self.ws = await websockets.connect(- self.ws_url,- ping_interval=300, # 5 minutes, same as Go server- ping_timeout=60,- max_size=100 * 1024 * 1024, # 100 MB max message size for large media- close_timeout=10,- )- self._connected = True- self._recv_task = asyncio.create_task(self._receive_loop())- logger.info(f"Connected to RPC endpoint: {self.ws_url}")- except Exception as e:- logger.error(f"Failed to connect to RPC endpoint: {e}")- raise-- async def close(self) -> None:- """Close connection."""- self._connected = False- if self._recv_task:- self._recv_task.cancel()- try:- await self._recv_task- except asyncio.CancelledError:- pass- if self.ws:- await self.ws.close()- self.ws = None- logger.info("RPC connection closed")-- async def _receive_loop(self) -> None:- """Handle incoming messages (responses and events)."""- try:- async for message in self.ws:- try:- data = json.loads(message)-- if "id" in data and data["id"] is not None:- # Response to a request- req_id = data["id"]- if req_id in self.pending:- self.pending[req_id].set_result(data)- elif data.get("method", "").startswith("event."):- # Event notification from server- if self.event_callback:- try:- self.event_callback(data)- except Exception as e:- logger.error(f"Error in event callback: {e}")- except json.JSONDecodeError as e:- logger.error(f"Invalid JSON received: {e}")- except ConnectionClosed:- logger.warning("WebSocket connection closed")- self._connected = False- except Exception as e:- logger.error(f"Error in receive loop: {e}")- self._connected = False-- async def call(self, method: str, params: Any = None, timeout: float = 30) -> Any:- """- Call RPC method and wait for response.-- Args:- method: RPC method name (e.g., 'status', 'send')- params: Method parameters (optional)- timeout: Response timeout in seconds-- Returns:- Result from the RPC call-- Raises:- Exception: If RPC call fails or times out- """- if not self.connected:- raise Exception("Not connected to RPC endpoint")-- self.request_id += 1- req_id = self.request_id-- request = {"jsonrpc": "2.0", "id": req_id, "method": method}- if params is not None:- request["params"] = params-- future = asyncio.get_event_loop().create_future()- self.pending[req_id] = future-- try:- await self.ws.send(json.dumps(request))- response = await asyncio.wait_for(future, timeout)-- if "error" in response and response["error"]:- error = response["error"]- raise Exception(f"RPC Error {error.get('code', -1)}: {error.get('message', 'Unknown error')}")-- return response.get("result")- except asyncio.TimeoutError:- raise Exception(f"RPC call '{method}' timed out after {timeout}s")- finally:- self.pending.pop(req_id, None)-- # Convenience methods for each RPC command- async def status(self) -> dict:- """Get WhatsApp connection status."""- return await self.call("status")-- async def start(self) -> dict:- """Start WhatsApp service."""- return await self.call("start")-- async def stop(self) -> dict:- """Stop WhatsApp service."""- return await self.call("stop")-- async def restart(self) -> dict:- """Restart WhatsApp service."""- return await self.call("restart")-- async def reset(self) -> dict:- """Reset WhatsApp session."""- return await self.call("reset")-- async def diagnostics(self) -> dict:- """Get diagnostics information."""- return await self.call("diagnostics")-- async def qr(self) -> dict:- """Get QR code for pairing."""- return await self.call("qr")-- async def send(self, **kwargs) -> dict:- """- Send WhatsApp message.-- Supports all message types: text, image, video, audio, document,- sticker, location, contact.-- Args:- phone: Recipient phone number (or use group_id)- group_id: Group JID (or use phone)- type: Message type (text, image, etc.)- message: Text content (for text messages)- media_data: Media content (for media messages)- location: Location data (for location messages)- contact: Contact data (for contact messages)- reply: Reply context (optional)- """- return await self.call("send", kwargs)-- async def media(self, message_id: str) -> dict:- """- Download media from a received message.-- Args:- message_id: ID of the message containing media-- Returns:- Dict with 'data' (base64) and 'mime_type'- """- # Use longer timeout for media downloads (videos can be large)- return await self.call("media", {"message_id": message_id}, timeout=120)-- async def groups(self) -> list:- """- Get all groups the user is a member of.-- Returns:- List of group info dicts with jid, name, topic, participants, etc.- """- return await self.call("groups")-- async def group_info(self, group_id: str) -> dict:- """- Get detailed information about a specific group.-- Args:- group_id: Group JID (e.g., '[email protected]')-- Returns:- Dict with group details including participants- """- return await self.call("group_info", {"group_id": group_id})-- async def group_update(self, group_id: str, name: str = None, topic: str = None) -> dict:- """- Update group name and/or topic (description).-- Args:- group_id: Group JID- name: New group name (optional)- topic: New group description (optional)-- Returns:- Success message- """- params = {"group_id": group_id}- if name is not None:- params["name"] = name- if topic is not None:- params["topic"] = topic- return await self.call("group_update", params)-- async def contact_check(self, phones: list) -> list:- """- Check if phone numbers are registered on WhatsApp.-- Args:- phones: List of phone numbers (without + prefix)-- Returns:- List of dicts with query, jid, is_registered, is_business, business_name- """- return await self.call("contact_check", {"phones": phones})-- async def contact_profile_pic(self, jid: str, preview: bool = False) -> dict:- """- Get profile picture for a user or group.-- Args:- jid: User or group JID (e.g., '[email protected]')- preview: Get smaller preview image instead of full size-- Returns:- Dict with exists, url, id, data (base64 if available)- """- return await self.call("contact_profile_pic", {"jid": jid, "preview": preview})-- async def typing(self, jid: str, state: str = "composing", media: str = "") -> dict:- """- Send typing indicator to a chat.-- Args:- jid: Chat JID (individual or group)- state: 'composing' (typing) or 'paused' (stopped typing)- media: '' for text typing, 'audio' for recording voice-- Returns:- Success message- """- params = {"jid": jid, "state": state}- if media:- params["media"] = media- return await self.call("typing", params)-- async def presence(self, status: str) -> dict:- """- Set online/offline presence status.-- Args:- status: 'available' (online) or 'unavailable' (offline)-- Returns:- Success message- """- return await self.call("presence", {"status": status})-- async def mark_read(self, message_ids: list, chat_jid: str, sender_jid: str = None) -> dict:- """- Mark messages as read.-- Args:- message_ids: List of message IDs to mark as read- chat_jid: Chat JID where messages are from- sender_jid: Sender JID (required for group messages)-- Returns:- Success message- """- params = {"message_ids": message_ids, "chat_jid": chat_jid}- if sender_jid:- params["sender_jid"] = sender_jid- return await self.call("mark_read", params)-- async def group_participants_add(self, group_id: str, participants: list) -> dict:- """- Add participants to a group.-- Args:- group_id: Group JID (e.g., '[email protected]')- participants: List of phone numbers or JIDs to add-- Returns:- Dict with group_id, action, results (list with success/error per participant),- added count, and failed count- """- return await self.call("group_participants_add", {- "group_id": group_id,- "participants": participants- })-- async def group_participants_remove(self, group_id: str, participants: list) -> dict:- """- Remove participants from a group.-- Args:- group_id: Group JID (e.g., '[email protected]')- participants: List of phone numbers or JIDs to remove-- Returns:- Dict with group_id, action, results (list with success/error per participant),- removed count, and failed count- """- return await self.call("group_participants_remove", {- "group_id": group_id,- "participants": participants- })-- async def group_invite_link(self, group_id: str) -> dict:- """- Get the invite link for a group.-- Args:- group_id: Group JID (e.g., '[email protected]')-- Returns:- Dict with group_id, invite_link- """- return await self.call("group_invite_link", {"group_id": group_id})-- async def group_revoke_invite(self, group_id: str) -> dict:- """- Revoke and regenerate the group invite link.-- Args:- group_id: Group JID (e.g., '[email protected]')-- Returns:- Dict with group_id, invite_link (new), revoked=true- """- return await self.call("group_revoke_invite", {"group_id": group_id})-- # ========================================================================- # Rate Limiting Methods (Anti-Ban Protection)- # ========================================================================-- async def rate_limit_get(self) -> dict:- """- Get current rate limit configuration and statistics.-- Returns:- Dict with 'config' (RateLimitConfig) and 'stats' (RateLimitStats)- """- return await self.call("rate_limit_get")-- async def rate_limit_set(self, **config) -> dict:- """- Update rate limit configuration dynamically.-- Args:- enabled: Enable/disable rate limiting- min_delay_ms: Minimum delay between messages (ms, default: 3000)- max_delay_ms: Maximum delay for randomization (ms, default: 8000)- typing_delay_ms: Typing indicator duration (ms, default: 2000)- link_extra_delay_ms: Extra delay for messages with links (ms, default: 5000)- max_messages_per_minute: Per-minute message limit (default: 10)- max_messages_per_hour: Per-hour message limit (default: 60)- max_new_contacts_per_day: Daily new contact limit (default: 20)- simulate_typing: Send typing indicator before messages (default: true)- randomize_delays: Add random variance to delays (default: true)- pause_on_low_response: Pause if response rate < threshold (default: false)- response_rate_threshold: Min response rate 0.0-1.0 (default: 0.3)-- Returns:- Dict with 'message' and updated 'config'- """- return await self.call("rate_limit_set", config)-- async def rate_limit_stats(self) -> dict:- """- Get current rate limiting statistics.-- Returns:- Dict with messages_sent_last_minute, messages_sent_last_hour,- messages_sent_today, new_contacts_today, response_rate,- is_paused, pause_reason, last_message_time, next_allowed_time- """- return await self.call("rate_limit_stats")-- async def rate_limit_unpause(self) -> dict:- """- Unpause rate limiting after it was paused due to low response rate.-- Returns:- Dict with 'message' and current 'stats'- """- return await self.call("rate_limit_unpause")diff --git a/server/whatsapp-rpc/web/app.py b/server/whatsapp-rpc/web/app.pydeleted file mode 100644index 20d252a0..00000000--- a/server/whatsapp-rpc/web/app.py+++ /dev/null@@ -1,609 +0,0 @@-"""-WhatsApp Controller Web UI - WebSocket RPC Version-Uses WebSocket RPC as the primary and only communication method with Go backend.-"""--import os-import asyncio-import json-import logging-import threading-import time-from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, send_from_directory-from flask_socketio import SocketIO, emit-from flask_limiter import Limiter-from flask_limiter.util import get_remote_address--from rpc_client import WhatsAppRPCClient--# Setup logging-logging.basicConfig(- level=logging.INFO,- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'-)-logger = logging.getLogger(__name__)--app = Flask(__name__)-app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev-secret-key')-socketio_app = SocketIO(app, cors_allowed_origins="*")--# Configuration-GO_WS_RPC_URL = os.getenv('GO_WS_RPC_URL', 'ws://localhost:9400/ws/rpc')--# Rate Limiting Configuration-RATE_LIMIT_ENABLED = os.getenv('RATE_LIMIT_ENABLED', 'true').lower() == 'true'-RATE_LIMIT_GLOBAL = os.getenv('RATE_LIMIT_GLOBAL', '20 per minute')-RATE_LIMIT_PER_USER = os.getenv('RATE_LIMIT_PER_USER', '10 per minute')-MESSAGE_DELAY_SECONDS = float(os.getenv('MESSAGE_DELAY_SECONDS', '3'))--# Initialize rate limiter-limiter = Limiter(- app=app,- key_func=get_remote_address,- default_limits=[] if not RATE_LIMIT_ENABLED else [RATE_LIMIT_GLOBAL],- storage_uri="memory://",- strategy="fixed-window"-)--# RPC Client globals-rpc_loop: asyncio.AbstractEventLoop = None-rpc_client: WhatsAppRPCClient = None---def get_recipient_key():- """Extract recipient (phone or group_id) for per-user rate limiting"""- try:- if request.is_json:- data = request.json- return data.get('phone') or data.get('group_id') or get_remote_address()- elif request.form:- return request.form.get('phone') or request.form.get('group_id') or get_remote_address()- except:- pass- return get_remote_address()---def apply_message_delay():- """Add delay between messages to simulate human behavior"""- if RATE_LIMIT_ENABLED and MESSAGE_DELAY_SECONDS > 0:- time.sleep(MESSAGE_DELAY_SECONDS)---def run_async(coro, timeout=30):- """Run async coroutine from sync Flask context."""- if rpc_loop is None or rpc_client is None:- raise Exception("RPC client not initialized")- if not rpc_client.connected:- raise Exception("RPC client not connected")- return asyncio.run_coroutine_threadsafe(coro, rpc_loop).result(timeout=timeout)---def init_rpc_client():- """Initialize RPC client in background thread."""- global rpc_loop, rpc_client-- rpc_client = WhatsAppRPCClient(GO_WS_RPC_URL)-- # Set event callback to forward to Socket.IO clients- def on_event(event):- try:- method = event.get("method", "")- event_type = method.replace("event.", "") if method.startswith("event.") else method- params = event.get("params", {})-- data = {"type": event_type, "data": params}- socketio_app.emit('whatsapp_event', data, namespace='/')- logger.debug(f"Event forwarded: {event_type}")- except Exception as e:- logger.error(f"Error forwarding event: {e}")-- rpc_client.event_callback = on_event-- def start_loop():- global rpc_loop- rpc_loop = asyncio.new_event_loop()- asyncio.set_event_loop(rpc_loop)- try:- rpc_loop.run_until_complete(rpc_client.connect())- logger.info(f"RPC client connected to {GO_WS_RPC_URL}")- rpc_loop.run_forever()- except Exception as e:- logger.error(f"RPC client connection failed: {e}")-- thread = threading.Thread(target=start_loop, daemon=True)- thread.start()- logger.info("RPC client initialization started")---# ============================================================================-# Routes-# ============================================================================-[email protected]('/')-def index():- """Main dashboard"""- try:- status = run_async(rpc_client.status())- return render_template('dashboard.html', status={"success": True, "data": status})- except Exception as e:- return render_template('dashboard.html', status={"success": False, "error": str(e)})--[email protected]('/api/status')-def api_status():- """Get WhatsApp connection status"""- try:- result = run_async(rpc_client.status())- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/start', methods=['POST'])-def api_start():- """Start WhatsApp service"""- try:- result = run_async(rpc_client.start())- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/stop', methods=['POST'])-def api_stop():- """Stop WhatsApp service"""- try:- result = run_async(rpc_client.stop())- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/restart', methods=['POST'])-def api_restart():- """Restart WhatsApp service"""- try:- result = run_async(rpc_client.restart())- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/reset', methods=['POST'])-def api_reset():- """Reset WhatsApp session"""- try:- result = run_async(rpc_client.reset())- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/qr')-def api_qr():- """Get QR code information"""- try:- result = run_async(rpc_client.qr())- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 404--[email protected]('/api/diagnostics')-def api_diagnostics():- """Get diagnostics information"""- try:- result = run_async(rpc_client.diagnostics())- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/send', methods=['POST'])[email protected](RATE_LIMIT_PER_USER, key_func=get_recipient_key)-def api_send():- """Send WhatsApp message (simple)"""- data = request.json- if not data or 'phone' not in data or 'message' not in data:- return jsonify({"success": False, "error": "Phone and message required"}), 400-- apply_message_delay()-- try:- result = run_async(rpc_client.send(- phone=data['phone'],- message=data['message'],- type='text'- ))- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/send/enhanced', methods=['POST'])[email protected](RATE_LIMIT_PER_USER, key_func=get_recipient_key)-def api_send_enhanced():- """Send enhanced WhatsApp message (all types)"""- data = request.json- if not data:- return jsonify({"success": False, "error": "Message data required"}), 400-- apply_message_delay()-- try:- result = run_async(rpc_client.send(**data))- return jsonify({"success": True, "data": result})- except Exception as e:- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/media/<message_id>')-def api_media(message_id):- """Download media from a message"""- try:- # Use longer timeout for media downloads (videos can be large)- result = run_async(rpc_client.media(message_id), timeout=120)- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Media download failed for {message_id}: {e}")- return jsonify({"success": False, "error": str(e)}), 404--[email protected]('/api/groups')-def api_groups():- """Get all groups"""- try:- result = run_async(rpc_client.groups())- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to get groups: {e}")- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/groups/<path:group_id>')-def api_group_info(group_id):- """Get group info"""- try:- result = run_async(rpc_client.group_info(group_id))- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to get group info for {group_id}: {e}")- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/groups/update', methods=['POST'])-def api_group_update():- """Update group name/topic"""- data = request.json- if not data or 'group_id' not in data:- return jsonify({"success": False, "error": "group_id required"}), 400-- try:- result = run_async(rpc_client.group_update(- group_id=data['group_id'],- name=data.get('name'),- topic=data.get('topic')- ))- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to update group {data.get('group_id')}: {e}")- return jsonify({"success": False, "error": str(e)}), 500---# ============================================================================-# Rate Limiting API Routes-# ============================================================================-[email protected]('/api/rate-limit')-def api_rate_limit_get():- """Get rate limit configuration and stats"""- try:- result = run_async(rpc_client.rate_limit_get())- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to get rate limit config: {e}")- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/rate-limit', methods=['POST'])-def api_rate_limit_set():- """Update rate limit configuration"""- data = request.json- if not data:- return jsonify({"success": False, "error": "Configuration data required"}), 400-- try:- result = run_async(rpc_client.rate_limit_set(**data))- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to update rate limit config: {e}")- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/rate-limit/stats')-def api_rate_limit_stats():- """Get rate limiting statistics"""- try:- result = run_async(rpc_client.rate_limit_stats())- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to get rate limit stats: {e}")- return jsonify({"success": False, "error": str(e)}), 500--[email protected]('/api/rate-limit/unpause', methods=['POST'])-def api_rate_limit_unpause():- """Unpause rate limiting"""- try:- result = run_async(rpc_client.rate_limit_unpause())- return jsonify({"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to unpause rate limiting: {e}")- return jsonify({"success": False, "error": str(e)}), 500---# ============================================================================-# Pages-# ============================================================================-[email protected]('/send')-def send_page():- """Send message page"""- return render_template('send.html')--[email protected]('/send', methods=['POST'])[email protected](RATE_LIMIT_PER_USER, key_func=get_recipient_key)-def send_message():- """Handle message sending from form"""- phone = request.form.get('phone')- message = request.form.get('message')-- if not phone or not message:- flash('Phone number and message are required', 'error')- return redirect(url_for('send_page'))-- apply_message_delay()-- try:- run_async(rpc_client.send(phone=phone, message=message, type='text'))- flash(f'Message sent to {phone}!', 'success')- except Exception as e:- flash(f'Failed to send message: {str(e)}', 'error')-- return redirect(url_for('send_page'))--[email protected]('/messaging')-def messaging_page():- """Enhanced messaging page"""- return render_template('messaging.html')--[email protected]('/messages')-def messages_page():- """Messages viewing page"""- return render_template('messages.html')--[email protected]('/groups')-def groups_page():- """Groups management page"""- return render_template('groups.html')--[email protected]('/contacts')-def contacts_page():- """Contacts management page"""- return render_template('contacts.html')--[email protected]('/settings')-def settings_page():- """Rate limiting and settings page"""- return render_template('settings.html')--[email protected]('/qr/<filename>')-def serve_qr_file(filename):- """Serve QR PNG files from project root"""- if filename.startswith('qr_') and filename.endswith('.png'):- current_dir = os.path.dirname(os.path.abspath(__file__))- project_root = os.path.dirname(current_dir)- file_path = os.path.join(project_root, filename)-- if os.path.exists(file_path):- return send_from_directory(project_root, filename, mimetype='image/png')- else:- return jsonify({"success": False, "error": "File not found"}), 404- return jsonify({"success": False, "error": "Invalid filename"}), 400---# ============================================================================-# WebSocket Events (Flask-SocketIO for browser clients)-# ============================================================================--@socketio_app.on('connect')-def handle_connect():- logger.info('Browser client connected')- try:- status = run_async(rpc_client.status())- emit('status_update', {"success": True, "data": status})- except Exception as e:- emit('status_update', {"success": False, "error": str(e)})---@socketio_app.on('disconnect')-def handle_disconnect():- logger.info('Browser client disconnected')---@socketio_app.on('request_status')-def handle_status_request():- try:- status = run_async(rpc_client.status())- emit('status_update', {"success": True, "data": status})- except Exception as e:- emit('status_update', {"success": False, "error": str(e)})---@socketio_app.on('subscribe_messages')-def handle_subscribe_messages():- """Client subscribes to receive all WhatsApp events"""- logger.info('Client subscribed to messages')- emit('subscribed', {'success': True})---@socketio_app.on('contact_check')-def handle_contact_check(data):- """Check if phone numbers are registered on WhatsApp"""- phones = data.get('phones', [])- if not phones:- emit('contact_check_result', {"success": False, "error": "phones array required"})- return- try:- result = run_async(rpc_client.contact_check(phones))- emit('contact_check_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to check contacts: {e}")- emit('contact_check_result', {"success": False, "error": str(e)})---@socketio_app.on('contact_profile_pic')-def handle_contact_profile_pic(data):- """Get profile picture for a user or group"""- jid = data.get('jid')- if not jid:- emit('contact_profile_pic_result', {"success": False, "error": "jid required"})- return- try:- result = run_async(rpc_client.contact_profile_pic(jid, data.get('preview', False)))- emit('contact_profile_pic_result', {"success": True, "data": result, "jid": jid})- except Exception as e:- logger.error(f"Failed to get profile picture: {e}")- emit('contact_profile_pic_result', {"success": False, "error": str(e), "jid": jid})---@socketio_app.on('typing')-def handle_typing(data):- """Send typing indicator to a chat"""- jid = data.get('jid')- if not jid:- emit('typing_result', {"success": False, "error": "jid required"})- return- try:- result = run_async(rpc_client.typing(- jid=jid,- state=data.get('state', 'composing'),- media=data.get('media', '')- ))- emit('typing_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to send typing indicator: {e}")- emit('typing_result', {"success": False, "error": str(e)})---@socketio_app.on('presence')-def handle_presence(data):- """Set online/offline presence status"""- status = data.get('status')- if not status:- emit('presence_result', {"success": False, "error": "status required"})- return- try:- result = run_async(rpc_client.presence(status))- emit('presence_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to set presence: {e}")- emit('presence_result', {"success": False, "error": str(e)})---@socketio_app.on('mark_read')-def handle_mark_read(data):- """Mark messages as read"""- message_ids = data.get('message_ids', [])- chat_jid = data.get('chat_jid')- if not message_ids or not chat_jid:- emit('mark_read_result', {"success": False, "error": "message_ids and chat_jid required"})- return- try:- result = run_async(rpc_client.mark_read(- message_ids=message_ids,- chat_jid=chat_jid,- sender_jid=data.get('sender_jid')- ))- emit('mark_read_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to mark messages as read: {e}")- emit('mark_read_result', {"success": False, "error": str(e)})---@socketio_app.on('rate_limit_get')-def handle_rate_limit_get():- """Get rate limit configuration and stats"""- try:- result = run_async(rpc_client.rate_limit_get())- emit('rate_limit_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to get rate limit config: {e}")- emit('rate_limit_result', {"success": False, "error": str(e)})---@socketio_app.on('rate_limit_set')-def handle_rate_limit_set(data):- """Update rate limit configuration"""- try:- result = run_async(rpc_client.rate_limit_set(**data))- emit('rate_limit_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to update rate limit config: {e}")- emit('rate_limit_result', {"success": False, "error": str(e)})---@socketio_app.on('rate_limit_stats')-def handle_rate_limit_stats():- """Get rate limiting statistics"""- try:- result = run_async(rpc_client.rate_limit_stats())- emit('rate_limit_stats_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to get rate limit stats: {e}")- emit('rate_limit_stats_result', {"success": False, "error": str(e)})---@socketio_app.on('rate_limit_unpause')-def handle_rate_limit_unpause():- """Unpause rate limiting"""- try:- result = run_async(rpc_client.rate_limit_unpause())- emit('rate_limit_result', {"success": True, "data": result})- except Exception as e:- logger.error(f"Failed to unpause rate limiting: {e}")- emit('rate_limit_result', {"success": False, "error": str(e)})---# ============================================================================-# Main-# ============================================================================--if __name__ == '__main__':- port = int(os.getenv('PORT', 5000))- debug = os.getenv('FLASK_ENV') == 'development'-- if debug:- logging.getLogger().setLevel(logging.DEBUG)-- print(f"Starting WhatsApp Web UI (WebSocket RPC) on port {port}")- print(f"Go WebSocket RPC URL: {GO_WS_RPC_URL}")-- # Initialize RPC client- print("Connecting to Go backend via WebSocket RPC...")- init_rpc_client()- time.sleep(2) # Give RPC client time to connect-- # Print routes- print("Registered routes:")- for rule in app.url_map.iter_rules():- print(f" {rule.rule} - {rule.methods}")-- socketio_app.run(app, host='0.0.0.0', port=port, debug=debug, allow_unsafe_werkzeug=True)diff --git a/server/whatsapp-rpc/web/requirements.txt b/server/whatsapp-rpc/web/requirements.txtdeleted file mode 100644index 083185c9..00000000--- a/server/whatsapp-rpc/web/requirements.txt+++ /dev/null@@ -1,6 +0,0 @@-# WhatsApp Controller Web UI - WebSocket RPC Version-Flask==3.0.0-Flask-SocketIO==5.3.6-Flask-Limiter==3.5.0-python-socketio==5.10.0-websockets>=12.0diff --git a/server/whatsapp-rpc/web/rpc_client.py b/server/whatsapp-rpc/web/rpc_client.pydeleted file mode 100644index eee7b64c..00000000--- a/server/whatsapp-rpc/web/rpc_client.py+++ /dev/null@@ -1,427 +0,0 @@-"""-WhatsApp RPC Client - Async JSON-RPC 2.0 client over WebSocket--Uses the official `websockets` library for stable async WebSocket communication.-Implements JSON-RPC 2.0 protocol for bidirectional communication with Go backend.-"""--import asyncio-import json-import logging-from typing import Any, Callable, Optional--import websockets-from websockets.exceptions import ConnectionClosed--logger = logging.getLogger(__name__)---class WhatsAppRPCClient:- """Async JSON-RPC 2.0 client using official websockets library."""-- def __init__(self, ws_url: str):- """- Initialize RPC client.-- Args:- ws_url: WebSocket URL (e.g., 'ws://localhost:9400/ws/rpc')- """- self.ws_url = ws_url- self.ws = None- self.request_id = 0- self.pending: dict[int, asyncio.Future] = {}- self.event_callback: Optional[Callable[[dict], None]] = None- self._recv_task: Optional[asyncio.Task] = None- self._connected = False-- @property- def connected(self) -> bool:- """Check if WebSocket is connected."""- return self._connected and self.ws is not None-- async def connect(self) -> None:- """Connect to WebSocket RPC endpoint."""- try:- self.ws = await websockets.connect(- self.ws_url,- ping_interval=300, # 5 minutes, same as Go server- ping_timeout=60,- max_size=100 * 1024 * 1024, # 100 MB max message size for large media- close_timeout=10,- )- self._connected = True- self._recv_task = asyncio.create_task(self._receive_loop())- logger.info(f"Connected to RPC endpoint: {self.ws_url}")- except Exception as e:- logger.error(f"Failed to connect to RPC endpoint: {e}")- raise-- async def close(self) -> None:- """Close connection."""- self._connected = False- if self._recv_task:- self._recv_task.cancel()- try:- await self._recv_task- except asyncio.CancelledError:- pass- if self.ws:- await self.ws.close()- self.ws = None- logger.info("RPC connection closed")-- async def _receive_loop(self) -> None:- """Handle incoming messages (responses and events)."""- try:- async for message in self.ws:- try:- data = json.loads(message)-- if "id" in data and data["id"] is not None:- # Response to a request- req_id = data["id"]- if req_id in self.pending:- self.pending[req_id].set_result(data)- elif data.get("method", "").startswith("event."):- # Event notification from server- if self.event_callback:- try:- self.event_callback(data)- except Exception as e:- logger.error(f"Error in event callback: {e}")- except json.JSONDecodeError as e:- logger.error(f"Invalid JSON received: {e}")- except ConnectionClosed:- logger.warning("WebSocket connection closed")- self._connected = False- except Exception as e:- logger.error(f"Error in receive loop: {e}")- self._connected = False-- async def call(self, method: str, params: Any = None, timeout: float = 30) -> Any:- """- Call RPC method and wait for response.-- Args:- method: RPC method name (e.g., 'status', 'send')- params: Method parameters (optional)- timeout: Response timeout in seconds-- Returns:- Result from the RPC call-- Raises:- Exception: If RPC call fails or times out- """- if not self.connected:- raise Exception("Not connected to RPC endpoint")-- self.request_id += 1- req_id = self.request_id-- request = {"jsonrpc": "2.0", "id": req_id, "method": method}- if params is not None:- request["params"] = params-- future = asyncio.get_event_loop().create_future()- self.pending[req_id] = future-- try:- await self.ws.send(json.dumps(request))- response = await asyncio.wait_for(future, timeout)-- if "error" in response and response["error"]:- error = response["error"]- raise Exception(f"RPC Error {error.get('code', -1)}: {error.get('message', 'Unknown error')}")-- return response.get("result")- except asyncio.TimeoutError:- raise Exception(f"RPC call '{method}' timed out after {timeout}s")- finally:- self.pending.pop(req_id, None)-- # Convenience methods for each RPC command- async def status(self) -> dict:- """Get WhatsApp connection status."""- return await self.call("status")-- async def start(self) -> dict:- """Start WhatsApp service."""- return await self.call("start")-- async def stop(self) -> dict:- """Stop WhatsApp service."""- return await self.call("stop")-- async def restart(self) -> dict:- """Restart WhatsApp service."""- return await self.call("restart")-- async def reset(self) -> dict:- """Reset WhatsApp session."""- return await self.call("reset")-- async def diagnostics(self) -> dict:- """Get diagnostics information."""- return await self.call("diagnostics")-- async def qr(self) -> dict:- """Get QR code for pairing."""- return await self.call("qr")-- async def send(self, **kwargs) -> dict:- """- Send WhatsApp message.-- Supports all message types: text, image, video, audio, document,- sticker, location, contact.-- Args:- phone: Recipient phone number (or use group_id)- group_id: Group JID (or use phone)- type: Message type (text, image, etc.)- message: Text content (for text messages)- media_data: Media content (for media messages)- location: Location data (for location messages)- contact: Contact data (for contact messages)- reply: Reply context (optional)- """- return await self.call("send", kwargs)-- async def media(self, message_id: str) -> dict:- """- Download media from a received message.-- Args:- message_id: ID of the message containing media-- Returns:- Dict with 'data' (base64) and 'mime_type'- """- # Use longer timeout for media downloads (videos can be large)- return await self.call("media", {"message_id": message_id}, timeout=120)-- async def groups(self) -> list:- """- Get all groups the user is a member of.-- Returns:- List of group info dicts with jid, name, topic, participants, etc.- """- return await self.call("groups")-- async def group_info(self, group_id: str) -> dict:- """- Get detailed information about a specific group.-- Args:- group_id: Group JID (e.g., '[email protected]')-- Returns:- Dict with group details including participants- """- return await self.call("group_info", {"group_id": group_id})-- async def group_update(self, group_id: str, name: str = None, topic: str = None) -> dict:- """- Update group name and/or topic (description).-- Args:- group_id: Group JID- name: New group name (optional)- topic: New group description (optional)-- Returns:- Success message- """- params = {"group_id": group_id}- if name is not None:- params["name"] = name- if topic is not None:- params["topic"] = topic- return await self.call("group_update", params)-- async def contact_check(self, phones: list) -> list:- """- Check if phone numbers are registered on WhatsApp.-- Args:- phones: List of phone numbers (without + prefix)-- Returns:- List of dicts with query, jid, is_registered, is_business, business_name- """- return await self.call("contact_check", {"phones": phones})-- async def contact_profile_pic(self, jid: str, preview: bool = False) -> dict:- """- Get profile picture for a user or group.-- Args:- jid: User or group JID (e.g., '[email protected]')- preview: Get smaller preview image instead of full size-- Returns:- Dict with exists, url, id, data (base64 if available)- """- return await self.call("contact_profile_pic", {"jid": jid, "preview": preview})-- async def typing(self, jid: str, state: str = "composing", media: str = "") -> dict:- """- Send typing indicator to a chat.-- Args:- jid: Chat JID (individual or group)- state: 'composing' (typing) or 'paused' (stopped typing)- media: '' for text typing, 'audio' for recording voice-- Returns:- Success message- """- params = {"jid": jid, "state": state}- if media:- params["media"] = media- return await self.call("typing", params)-- async def presence(self, status: str) -> dict:- """- Set online/offline presence status.-- Args:- status: 'available' (online) or 'unavailable' (offline)-- Returns:- Success message- """- return await self.call("presence", {"status": status})-- async def mark_read(self, message_ids: list, chat_jid: str, sender_jid: str = None) -> dict:- """- Mark messages as read.-- Args:- message_ids: List of message IDs to mark as read- chat_jid: Chat JID where messages are from- sender_jid: Sender JID (required for group messages)-- Returns:- Success message- """- params = {"message_ids": message_ids, "chat_jid": chat_jid}- if sender_jid:- params["sender_jid"] = sender_jid- return await self.call("mark_read", params)-- async def group_participants_add(self, group_id: str, participants: list) -> dict:- """- Add participants to a group.-- Args:- group_id: Group JID (e.g., '[email protected]')- participants: List of phone numbers or JIDs to add-- Returns:- Dict with group_id, action, results (list with success/error per participant),- added count, and failed count- """- return await self.call("group_participants_add", {- "group_id": group_id,- "participants": participants- })-- async def group_participants_remove(self, group_id: str, participants: list) -> dict:- """- Remove participants from a group.-- Args:- group_id: Group JID (e.g., '[email protected]')- participants: List of phone numbers or JIDs to remove-- Returns:- Dict with group_id, action, results (list with success/error per participant),- removed count, and failed count- """- return await self.call("group_participants_remove", {- "group_id": group_id,- "participants": participants- })-- async def group_invite_link(self, group_id: str) -> dict:- """- Get the invite link for a group.-- Args:- group_id: Group JID (e.g., '[email protected]')-- Returns:- Dict with group_id, invite_link- """- return await self.call("group_invite_link", {"group_id": group_id})-- async def group_revoke_invite(self, group_id: str) -> dict:- """- Revoke and regenerate the group invite link.-- Args:- group_id: Group JID (e.g., '[email protected]')-- Returns:- Dict with group_id, invite_link (new), revoked=true- """- return await self.call("group_revoke_invite", {"group_id": group_id})-- # ========================================================================- # Rate Limiting Methods (Anti-Ban Protection)- # ========================================================================-- async def rate_limit_get(self) -> dict:- """- Get current rate limit configuration and statistics.-- Returns:- Dict with 'config' (RateLimitConfig) and 'stats' (RateLimitStats)- """- return await self.call("rate_limit_get")-- async def rate_limit_set(self, **config) -> dict:- """- Update rate limit configuration dynamically.-- Args:- enabled: Enable/disable rate limiting- min_delay_ms: Minimum delay between messages (ms, default: 3000)- max_delay_ms: Maximum delay for randomization (ms, default: 8000)- typing_delay_ms: Typing indicator duration (ms, default: 2000)- link_extra_delay_ms: Extra delay for messages with links (ms, default: 5000)- max_messages_per_minute: Per-minute message limit (default: 10)- max_messages_per_hour: Per-hour message limit (default: 60)- max_new_contacts_per_day: Daily new contact limit (default: 20)- simulate_typing: Send typing indicator before messages (default: true)- randomize_delays: Add random variance to delays (default: true)- pause_on_low_response: Pause if response rate < threshold (default: false)- response_rate_threshold: Min response rate 0.0-1.0 (default: 0.3)-- Returns:- Dict with 'message' and updated 'config'- """- return await self.call("rate_limit_set", config)-- async def rate_limit_stats(self) -> dict:- """- Get current rate limiting statistics.-- Returns:- Dict with messages_sent_last_minute, messages_sent_last_hour,- messages_sent_today, new_contacts_today, response_rate,- is_paused, pause_reason, last_message_time, next_allowed_time- """- return await self.call("rate_limit_stats")-- async def rate_limit_unpause(self) -> dict:- """- Unpause rate limiting after it was paused due to low response rate.-- Returns:- Dict with 'message' and current 'stats'- """- return await self.call("rate_limit_unpause")diff --git a/server/whatsapp-rpc/web/static/openapi.yaml b/server/whatsapp-rpc/web/static/openapi.yamldeleted file mode 100644index 4b1d4747..00000000--- a/server/whatsapp-rpc/web/static/openapi.yaml+++ /dev/null@@ -1,59 +0,0 @@-openapi: 3.0.0-info:- title: WhatsApp Controller API- version: 1.0.0- description: WhatsApp Web API with enhanced messaging capabilities--servers:- - url: http://localhost:5000- description: Flask Server--paths:- /api/status:- get:- summary: Get WhatsApp status- tags: [Status]- responses:- '200':- description: Success-- /api/start:- post:- summary: Start WhatsApp service- tags: [Status]- responses:- '200':- description: Service started-- /api/send/enhanced:- post:- summary: Send message- tags: [Messaging]- requestBody:- content:- application/json:- schema:- type: object- properties:- phone:- type: string- type:- type: string- message:- type: string- responses:- '200':- description: Message sent-- /api/messages:- get:- summary: Get received messages- tags: [Messages]- parameters:- - name: limit- in: query- schema:- type: integer- responses:- '200':- description: Messages retrieveddiff --git a/server/whatsapp-rpc/web/templates/base.html b/server/whatsapp-rpc/web/templates/base.htmldeleted file mode 100644index f6c9e702..00000000--- a/server/whatsapp-rpc/web/templates/base.html+++ /dev/null@@ -1,150 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>{% block title %}WhatsApp Controller{% endblock %}</title>-- <!-- Tailwind CSS -->- <script src="https://cdn.tailwindcss.com"></script>-- <!-- Socket.IO -->- <script src="https://cdn.socket.io/4.7.4/socket.io.min.js"></script>-- <!-- QR Code Library -->- <script src="https://unpkg.com/[email protected]/dist/qrious.min.js"></script>-- <style>- .status-indicator {- @apply inline-block w-3 h-3 rounded-full mr-2;- }- .status-connected { @apply bg-green-500; }- .status-disconnected { @apply bg-red-500; }- .status-connecting { @apply bg-yellow-500 animate-pulse; }- </style>-</head>-<body class="bg-gray-100 min-h-screen">- <!-- Navigation -->- <nav class="bg-green-600 shadow-lg">- <div class="max-w-7xl mx-auto px-4">- <div class="flex justify-between items-center h-16">- <div class="flex items-center">- <h1 class="text-white text-xl font-bold">- <a href="{{ url_for('index') }}">WhatsApp Controller</a>- </h1>- </div>-- <div class="flex items-center space-x-4">- <!-- Status indicator -->- <div id="status-indicator" class="flex items-center text-white">- <span class="status-indicator status-disconnected" id="status-dot"></span>- <span id="status-text">Disconnected</span>- </div>-- <!-- Navigation links -->- <div class="flex items-center space-x-1">- <a href="{{ url_for('index') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">- Dashboard- </a>-- <!-- Messaging Dropdown -->- <div class="relative group">- <button class="text-white hover:text-green-200 px-3 py-2 rounded text-sm flex items-center">- Messaging- <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>- </svg>- </button>- <div class="absolute left-0 mt-2 w-48 bg-white rounded-md shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50">- <a href="{{ url_for('send_page') }}" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Simple Send</a>- <a href="{{ url_for('messaging_page') }}" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Enhanced Messaging</a>- <a href="{{ url_for('messages_page') }}" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Received Messages</a>- </div>- </div>-- <a href="{{ url_for('groups_page') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">- Groups- </a>- <a href="{{ url_for('contacts_page') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">- Contacts- </a>- <a href="{{ url_for('settings_page') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">- Settings- </a>- </div>- </div>- </div>- </div>- </nav>-- <!-- Flash messages -->- {% with messages = get_flashed_messages(with_categories=true) %}- {% if messages %}- <div class="max-w-7xl mx-auto px-4 py-4">- {% for category, message in messages %}- <div class="alert alert-{{ 'success' if category == 'success' else 'error' }} mb-4 p-4 rounded-lg- {{ 'bg-green-100 border border-green-400 text-green-700' if category == 'success' else 'bg-red-100 border border-red-400 text-red-700' }}">- {{ message }}- </div>- {% endfor %}- </div>- {% endif %}- {% endwith %}-- <!-- Main content -->- <main class="max-w-7xl mx-auto px-4 py-8">- {% block content %}{% endblock %}- </main>-- <!-- Footer -->- <footer class="bg-white border-t mt-12">- <div class="max-w-7xl mx-auto px-4 py-6">- <p class="text-center text-gray-600">- WhatsApp Controller - Modern Web Interface- </p>- </div>- </footer>-- <!-- JavaScript -->- <script>- // Initialize Socket.IO connection- const socket = io();-- // Status elements- const statusDot = document.getElementById('status-dot');- const statusText = document.getElementById('status-text');-- // Socket events- socket.on('connect', function() {- console.log('Connected to WebSocket');- socket.emit('request_status');- });-- socket.on('disconnect', function() {- console.log('Disconnected from WebSocket');- updateStatus('disconnected', 'Disconnected');- });-- socket.on('status_update', function(data) {- console.log('Status update:', data);- if (data.success && data.data) {- const connected = data.data.connected;- updateStatus(connected ? 'connected' : 'disconnected',- connected ? 'Connected' : 'Disconnected');- }- });-- function updateStatus(status, text) {- statusDot.className = `status-indicator status-${status}`;- statusText.textContent = text;- }-- // Auto-refresh status every 30 seconds- setInterval(() => {- socket.emit('request_status');- }, 30000);- </script>-- {% block scripts %}{% endblock %}-</body>-</html>\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/contacts.html b/server/whatsapp-rpc/web/templates/contacts.htmldeleted file mode 100644index 7ab4169a..00000000--- a/server/whatsapp-rpc/web/templates/contacts.html+++ /dev/null@@ -1,240 +0,0 @@-{% extends "base.html" %}-{% block title %}Contacts - WhatsApp Controller{% endblock %}--{% block content %}-<div class="space-y-8">- <!-- Page Header -->- <div>- <h1 class="text-3xl font-bold text-gray-900">Contacts</h1>- <p class="text-gray-600 mt-1">Check if phone numbers are on WhatsApp and view profile pictures</p>- </div>-- <!-- Check Numbers Section -->- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4">Check Phone Numbers</h2>- <p class="text-gray-600 mb-4">Enter phone numbers (one per line) to check if they are registered on WhatsApp</p>-- <div class="space-y-4">- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Phone Numbers</label>- <textarea id="phone-numbers" rows="5"- placeholder="Enter phone numbers, one per line (without + prefix) e.g. 919876543210 14155551234"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>- </div>-- <button onclick="checkContacts()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center">- <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>- </svg>- Check Numbers- </button>- </div>-- <!-- Results -->- <div id="check-results" class="mt-6 hidden">- <h3 class="font-semibold text-gray-800 mb-3">Results</h3>- <div id="results-container" class="space-y-2"></div>- </div>- </div>-- <!-- Profile Picture Section -->- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4">Profile Picture</h2>- <p class="text-gray-600 mb-4">View profile picture for a user or group</p>-- <div class="flex flex-wrap gap-4 items-end">- <div class="flex-1 min-w-[250px]">- <label class="block text-sm font-medium text-gray-700 mb-2">JID (Phone or Group)</label>- <input type="text" id="profile-jid"- placeholder="[email protected] or [email protected]"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- <button onclick="getProfilePicture()" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center">- <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>- </svg>- Get Picture- </button>- </div>-- <!-- Profile Picture Result -->- <div id="profile-result" class="mt-6 hidden">- <div id="profile-container" class="flex items-center space-x-4">- <img id="profile-image" src="" alt="Profile Picture" class="w-24 h-24 rounded-full object-cover border-4 border-gray-200">- <div>- <p id="profile-jid-display" class="font-semibold text-gray-800"></p>- <p id="profile-status" class="text-sm text-gray-600"></p>- </div>- </div>- <div id="profile-no-picture" class="hidden text-gray-500">- <svg class="w-24 h-24 text-gray-300 mx-auto" fill="currentColor" viewBox="0 0 24 24">- <path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z"></path>- </svg>- <p class="text-center mt-2">No profile picture available</p>- </div>- </div>- </div>-- <!-- Presence Section -->- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4">Presence Status</h2>- <p class="text-gray-600 mb-4">Set your online/offline presence status</p>-- <div class="flex flex-wrap gap-4">- <button onclick="setPresence('available')" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center">- <span class="w-3 h-3 bg-green-300 rounded-full mr-2"></span>- Set Online- </button>- <button onclick="setPresence('unavailable')" class="px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 flex items-center">- <span class="w-3 h-3 bg-gray-400 rounded-full mr-2"></span>- Set Offline- </button>- </div>- <p id="presence-status" class="mt-3 text-sm text-gray-600"></p>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>- // Listen for contact check result- socket.on('contact_check_result', function(data) {- const resultsSection = document.getElementById('check-results');- const container = document.getElementById('results-container');-- resultsSection.classList.remove('hidden');-- if (!data.success) {- container.innerHTML = `<div class="text-red-600">Error: ${data.error}</div>`;- return;- }-- const results = data.data;- container.innerHTML = results.map(r => {- const statusClass = r.is_registered ? 'bg-green-100 border-green-300' : 'bg-red-100 border-red-300';- const statusIcon = r.is_registered- ? '<svg class="w-5 h-5 text-green-600" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>'- : '<svg class="w-5 h-5 text-red-600" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path></svg>';-- let businessBadge = '';- if (r.is_business) {- businessBadge = `<span class="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">Business${r.business_name ? ': ' + escapeHtml(r.business_name) : ''}</span>`;- }-- return `- <div class="flex items-center justify-between p-3 border rounded-lg ${statusClass}">- <div class="flex items-center space-x-3">- ${statusIcon}- <div>- <p class="font-medium">${escapeHtml(r.query)}</p>- ${r.is_registered ? `<p class="text-xs text-gray-600">${escapeHtml(r.jid || '')}</p>` : ''}- </div>- ${businessBadge}- </div>- <span class="text-sm font-medium ${r.is_registered ? 'text-green-700' : 'text-red-700'}">- ${r.is_registered ? 'On WhatsApp' : 'Not on WhatsApp'}- </span>- </div>- `;- }).join('');- });-- // Listen for profile picture result- socket.on('contact_profile_pic_result', function(data) {- const resultSection = document.getElementById('profile-result');- const container = document.getElementById('profile-container');- const noPicture = document.getElementById('profile-no-picture');- const image = document.getElementById('profile-image');- const jidDisplay = document.getElementById('profile-jid-display');- const statusDisplay = document.getElementById('profile-status');-- resultSection.classList.remove('hidden');-- if (!data.success) {- container.classList.add('hidden');- noPicture.classList.remove('hidden');- noPicture.innerHTML = `<p class="text-red-600">Error: ${data.error}</p>`;- return;- }-- jidDisplay.textContent = data.jid || '';-- if (data.data.exists) {- container.classList.remove('hidden');- noPicture.classList.add('hidden');-- if (data.data.data) {- // Base64 data available- image.src = 'data:image/jpeg;base64,' + data.data.data;- } else if (data.data.url) {- // URL available- image.src = data.data.url;- }- statusDisplay.textContent = 'Profile picture found';- } else {- container.classList.add('hidden');- noPicture.classList.remove('hidden');- noPicture.innerHTML = `- <svg class="w-24 h-24 text-gray-300 mx-auto" fill="currentColor" viewBox="0 0 24 24">- <path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z"></path>- </svg>- <p class="text-center mt-2">No profile picture available</p>- `;- }- });-- // Listen for presence result- socket.on('presence_result', function(data) {- const status = document.getElementById('presence-status');- if (data.success) {- status.textContent = 'Presence updated successfully';- status.className = 'mt-3 text-sm text-green-600';- } else {- status.textContent = 'Failed: ' + data.error;- status.className = 'mt-3 text-sm text-red-600';- }- });-- function checkContacts() {- const textarea = document.getElementById('phone-numbers');- const lines = textarea.value.split('\n').map(l => l.trim()).filter(l => l.length > 0);-- if (lines.length === 0) {- alert('Please enter at least one phone number');- return;- }-- socket.emit('contact_check', { phones: lines });- }-- function getProfilePicture() {- const jid = document.getElementById('profile-jid').value.trim();-- if (!jid) {- alert('Please enter a JID');- return;- }-- // Auto-append @s.whatsapp.net if no @ present- let fullJid = jid;- if (!jid.includes('@')) {- fullJid = jid + '@s.whatsapp.net';- }-- socket.emit('contact_profile_pic', { jid: fullJid, preview: false });- }-- function setPresence(status) {- socket.emit('presence', { status: status });- document.getElementById('presence-status').textContent = 'Setting presence...';- document.getElementById('presence-status').className = 'mt-3 text-sm text-blue-600';- }-- function escapeHtml(text) {- if (!text) return '';- const div = document.createElement('div');- div.textContent = text;- return div.innerHTML;- }-</script>-{% endblock %}diff --git a/server/whatsapp-rpc/web/templates/dashboard.html b/server/whatsapp-rpc/web/templates/dashboard.htmldeleted file mode 100644index aaba43ff..00000000--- a/server/whatsapp-rpc/web/templates/dashboard.html+++ /dev/null@@ -1,320 +0,0 @@-{% extends "base.html" %}--{% block title %}Dashboard - WhatsApp Controller{% endblock %}--{% block content %}-<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">-- <!-- Status Card -->- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4 flex items-center">- <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>- </svg>- Connection Status- </h2>-- <div id="status-details" class="space-y-3">- <div class="flex justify-between items-center">- <span>Status:</span>- <span id="connection-status" class="font-medium">- {{ 'Connected' if status.get('data', {}).get('connected') else 'Disconnected' }}- </span>- </div>- <div class="flex justify-between items-center">- <span>Session:</span>- <span id="session-status" class="font-medium">- {{ 'Active' if status.get('data', {}).get('has_session') else 'None' }}- </span>- </div>- <div class="flex justify-between items-center">- <span>Last Check:</span>- <span id="last-check" class="text-sm text-gray-600">- Never- </span>- </div>- </div>-- <div class="mt-6 space-y-3">- <button id="start-btn" onclick="startWhatsApp()"- class="w-full bg-green-600 text-white py-2 px-4 rounded-lg hover:bg-green-700 transition">- Start WhatsApp- </button>- <button id="restart-btn" onclick="restartWhatsApp()"- class="w-full bg-orange-600 text-white py-2 px-4 rounded-lg hover:bg-orange-700 transition">- Restart- </button>- </div>- </div>-- <!-- QR Code Card -->- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4 flex items-center">- <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>- </svg>- QR Code- </h2>-- <div id="qr-container" class="text-center">- <div class="bg-gray-100 rounded-lg p-8 mb-4">- <svg class="w-16 h-16 mx-auto text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>- </svg>- <p class="text-gray-600 mt-2">No QR code available</p>- </div>- <p class="text-sm text-gray-600">- Start WhatsApp service to generate QR code for pairing- </p>- </div>- </div>-- <!-- Quick Send Card -->- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4 flex items-center">- <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>- </svg>- Quick Send- </h2>-- <form id="quick-send-form" class="space-y-4">- <div>- <label class="block text-sm font-medium mb-1">Phone Number</label>- <input type="text" id="quick-phone" placeholder="1234567890" required- class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500 focus:border-transparent">- </div>- <div>- <label class="block text-sm font-medium mb-1">Message</label>- <textarea id="quick-message" placeholder="Enter your message..." rows="3" required- class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500 focus:border-transparent"></textarea>- </div>- <button type="submit"- class="w-full bg-green-600 text-white py-2 px-4 rounded-lg hover:bg-green-700 transition">- Send Message- </button>- </form>- </div>-</div>--<!-- Activity Feed -->-<div class="mt-8 bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4">Activity Feed</h2>- <div id="activity-feed" class="space-y-2">- <p class="text-gray-600">No recent activity</p>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>- // Dashboard specific JavaScript- let activityFeed = [];-- function startWhatsApp() {- const btn = document.getElementById('start-btn');- btn.disabled = true;- btn.textContent = 'Starting...';-- fetch('/api/start', { method: 'POST' })- .then(response => response.json())- .then(data => {- if (data.success) {- addActivity('success', 'WhatsApp service started successfully');- // Start loading QR code immediately- setTimeout(() => loadQRCode(), 1500);- } else {- addActivity('error', `Failed to start WhatsApp: ${data.error}`);- }- })- .catch(error => {- addActivity('error', `Error: ${error.message}`);- })- .finally(() => {- btn.disabled = false;- btn.textContent = 'Start WhatsApp';- setTimeout(refreshStatus, 2000);- });- }-- function refreshStatus() {- fetch('/api/status')- .then(response => response.json())- .then(data => {- if (data.success && data.data) {- updateStatusDisplay(data.data);- addActivity('info', 'Status refreshed');- }- })- .catch(error => {- addActivity('error', `Failed to refresh status: ${error.message}`);- });- }-- function updateStatusDisplay(status) {- document.getElementById('connection-status').textContent =- status.connected ? 'Connected' : 'Disconnected';- document.getElementById('session-status').textContent =- status.has_session ? 'Active' : 'None';- document.getElementById('last-check').textContent =- new Date().toLocaleTimeString();- }-- function addActivity(type, message) {- const timestamp = new Date().toLocaleTimeString();- activityFeed.unshift({ type, message, timestamp });-- // Keep only last 10 activities- if (activityFeed.length > 10) {- activityFeed = activityFeed.slice(0, 10);- }-- renderActivityFeed();- }-- function renderActivityFeed() {- const container = document.getElementById('activity-feed');- if (activityFeed.length === 0) {- container.innerHTML = '<p class="text-gray-600">No recent activity</p>';- return;- }-- container.innerHTML = activityFeed.map(activity => {- const colorClass = activity.type === 'success' ? 'text-green-600' :- activity.type === 'error' ? 'text-red-600' : 'text-blue-600';- return `- <div class="flex justify-between items-center py-2 border-b last:border-b-0">- <span class="${colorClass}">${activity.message}</span>- <span class="text-sm text-gray-500">${activity.timestamp}</span>- </div>- `;- }).join('');- }-- // Quick send form- document.getElementById('quick-send-form').addEventListener('submit', function(e) {- e.preventDefault();-- const phone = document.getElementById('quick-phone').value;- const message = document.getElementById('quick-message').value;-- if (!phone || !message) {- addActivity('error', 'Phone number and message are required');- return;- }-- fetch('/api/send', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ phone, message })- })- .then(response => response.json())- .then(data => {- if (data.success) {- addActivity('success', `Message sent to ${phone}`);- document.getElementById('quick-message').value = '';- } else {- addActivity('error', `Failed to send message: ${data.error}`);- }- })- .catch(error => {- addActivity('error', `Error sending message: ${error.message}`);- });- });-- function loadQRCode(maxAttempts = 10, attemptNum = 1) {- fetch('/api/qr')- .then(response => response.json())- .then(data => {- const container = document.getElementById('qr-container');- if (data.success && data.data && data.data.has_qr) {- // Display base64 image directly (Docker compatible)- const imgSrc = data.data.image_data- ? `data:image/png;base64,${data.data.image_data}`- : `/qr/${data.data.filename}`;- container.innerHTML = `- <div class="text-center">- <img src="${imgSrc}" alt="QR Code" class="mx-auto mb-4 border-2 border-gray-300 rounded" style="width: 256px; height: 256px;" />- <p class="text-sm text-gray-600">Scan this QR code with WhatsApp</p>- </div>- `;- addActivity('info', 'QR code loaded');- } else {- // QR not ready yet, poll again if we haven't exceeded max attempts- if (attemptNum < maxAttempts) {- container.innerHTML = `- <div class="bg-gray-100 rounded-lg p-8 mb-4">- <svg class="w-16 h-16 mx-auto text-gray-400 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>- </svg>- <p class="text-gray-600 mt-2">Waiting for QR code... (${attemptNum}/${maxAttempts})</p>- </div>- `;- setTimeout(() => loadQRCode(maxAttempts, attemptNum + 1), 1000);- } else {- container.innerHTML = `- <div class="bg-gray-100 rounded-lg p-8 mb-4">- <svg class="w-16 h-16 mx-auto text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>- </svg>- <p class="text-gray-600 mt-2">QR code not available</p>- </div>- <p class="text-sm text-gray-600">- Try clicking "Regenerate QR Code" again- </p>- `;- addActivity('error', 'QR code generation timed out');- }- }- })- .catch(error => {- addActivity('error', `Failed to load QR code: ${error.message}`);- });- }-- function restartWhatsApp() {- const btn = event.target;- btn.disabled = true;- btn.textContent = 'Restarting...';-- fetch('/api/restart', { method: 'POST' })- .then(response => response.json())- .then(data => {- if (data.success) {- addActivity('success', 'WhatsApp service restarted successfully');- // Start loading QR code immediately- setTimeout(() => loadQRCode(), 1500);- } else {- addActivity('error', `Failed to restart WhatsApp: ${data.error}`);- }- })- .catch(error => {- addActivity('error', `Error: ${error.message}`);- })- .finally(() => {- btn.disabled = false;- btn.textContent = 'Restart';- setTimeout(refreshStatus, 2000);- });- }-- // Socket.IO events for real-time updates- socket.on('qr_code', function(data) {- loadQRCode(); // Reload QR code when event received- addActivity('info', 'New QR code generated');- });-- socket.on('connected', function(data) {- addActivity('success', 'WhatsApp connected successfully');- refreshStatus();- });-- socket.on('disconnected', function(data) {- addActivity('warning', 'WhatsApp disconnected');- refreshStatus();- });-- // Initial status check only (QR code must be manually regenerated)- refreshStatus();-</script>-{% endblock %}\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/groups.html b/server/whatsapp-rpc/web/templates/groups.htmldeleted file mode 100644index d9395f2c..00000000--- a/server/whatsapp-rpc/web/templates/groups.html+++ /dev/null@@ -1,328 +0,0 @@-{% extends "base.html" %}--{% block title %}Groups - WhatsApp Controller{% endblock %}--{% block content %}-<div class="max-w-6xl mx-auto">- <div class="bg-white rounded-lg shadow-md p-6">- <div class="flex justify-between items-center mb-6">- <h2 class="text-2xl font-bold text-gray-800">WhatsApp Groups</h2>- <button onclick="loadGroups()" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition">- Refresh- </button>- </div>-- <!-- Groups count -->- <div class="mb-4 p-3 bg-gray-100 rounded">- <p class="text-sm text-gray-600">- <span class="font-semibold">Total Groups:</span>- <span id="group-count">0</span>- </p>- </div>-- <!-- Loading indicator -->- <div id="loading" class="hidden text-center py-8">- <p class="text-gray-500">Loading groups...</p>- </div>-- <!-- Error message -->- <div id="error-message" class="hidden mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">- </div>-- <!-- Groups container -->- <div id="groups-container" class="space-y-4">- <p class="text-gray-500 text-center py-8">Click Refresh to load groups.</p>- </div>- </div>-</div>--<!-- Group Info Modal -->-<div id="group-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50 flex items-center justify-center">- <div class="bg-white rounded-lg max-w-3xl max-h-[90vh] w-full m-4 overflow-hidden">- <div class="flex justify-between items-center p-4 border-b">- <h3 class="text-lg font-semibold" id="group-modal-title">Group Details</h3>- <button onclick="closeGroupModal()" class="text-gray-500 hover:text-gray-700">- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>- </svg>- </button>- </div>- <div id="group-modal-content" class="p-4 overflow-auto max-h-[calc(90vh-80px)]">- <p class="text-gray-500">Loading...</p>- </div>- </div>-</div>--<!-- Edit Group Modal -->-<div id="edit-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50 flex items-center justify-center">- <div class="bg-white rounded-lg max-w-md w-full m-4">- <div class="flex justify-between items-center p-4 border-b">- <h3 class="text-lg font-semibold">Edit Group</h3>- <button onclick="closeEditModal()" class="text-gray-500 hover:text-gray-700">- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>- </svg>- </button>- </div>- <form id="edit-form" class="p-4">- <input type="hidden" id="edit-group-id">- <div class="mb-4">- <label class="block text-sm font-medium text-gray-700 mb-1">Group Name</label>- <input type="text" id="edit-name" class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">- </div>- <div class="mb-4">- <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>- <textarea id="edit-topic" rows="3" class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500"></textarea>- </div>- <div class="flex justify-end space-x-2">- <button type="button" onclick="closeEditModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400">- Cancel- </button>- <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">- Save Changes- </button>- </div>- </form>- </div>-</div>--{% endblock %}--{% block scripts %}-<script>- let groups = [];- const groupsContainer = document.getElementById('groups-container');- const groupCount = document.getElementById('group-count');- const loading = document.getElementById('loading');- const errorMessage = document.getElementById('error-message');-- // Load groups on page load- loadGroups();-- function showLoading(show) {- loading.classList.toggle('hidden', !show);- }-- function showError(message) {- errorMessage.textContent = message;- errorMessage.classList.remove('hidden');- setTimeout(() => errorMessage.classList.add('hidden'), 5000);- }-- function loadGroups() {- showLoading(true);- groupsContainer.innerHTML = '';-- fetch('/api/groups')- .then(response => response.json())- .then(data => {- showLoading(false);- if (data.success) {- groups = data.data || [];- renderGroups();- } else {- showError(data.error || 'Failed to load groups');- groupsContainer.innerHTML = '<p class="text-gray-500 text-center py-8">Failed to load groups.</p>';- }- })- .catch(error => {- showLoading(false);- console.error('Error loading groups:', error);- showError('Failed to load groups: ' + error.message);- groupsContainer.innerHTML = '<p class="text-gray-500 text-center py-8">Failed to load groups.</p>';- });- }-- function renderGroups() {- if (groups.length === 0) {- groupsContainer.innerHTML = '<p class="text-gray-500 text-center py-8">No groups found.</p>';- groupCount.textContent = '0';- return;- }-- groupCount.textContent = groups.length;-- groupsContainer.innerHTML = groups.map(group => `- <div class="border rounded-lg p-4 hover:bg-gray-50 transition">- <div class="flex justify-between items-start">- <div class="flex-1">- <h3 class="text-lg font-semibold text-gray-800">${escapeHtml(group.name)}</h3>- <p class="text-sm text-gray-500 mt-1">${escapeHtml(group.jid)}</p>- ${group.topic ? `<p class="text-sm text-gray-600 mt-2">${escapeHtml(group.topic)}</p>` : ''}- <div class="flex items-center space-x-4 mt-2 text-sm text-gray-500">- <span>${group.size} members</span>- ${group.is_announce ? '<span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-xs">Announcement</span>' : ''}- ${group.is_locked ? '<span class="px-2 py-1 bg-red-100 text-red-800 rounded text-xs">Locked</span>' : ''}- </div>- </div>- <div class="flex space-x-2">- <button onclick="viewGroupInfo('${group.jid}')" class="px-3 py-1 bg-blue-500 text-white rounded text-sm hover:bg-blue-600">- View- </button>- <button onclick="openEditModal('${group.jid}', '${escapeHtml(group.name)}', '${escapeHtml(group.topic || '')}')" class="px-3 py-1 bg-gray-500 text-white rounded text-sm hover:bg-gray-600">- Edit- </button>- </div>- </div>- </div>- `).join('');- }-- function viewGroupInfo(groupId) {- const modal = document.getElementById('group-modal');- const modalTitle = document.getElementById('group-modal-title');- const modalContent = document.getElementById('group-modal-content');-- modal.classList.remove('hidden');- modalContent.innerHTML = '<p class="text-gray-500">Loading group details...</p>';-- fetch(`/api/groups/${encodeURIComponent(groupId)}`)- .then(response => response.json())- .then(data => {- if (data.success) {- const info = data.data;- modalTitle.textContent = info.name;- modalContent.innerHTML = `- <div class="space-y-4">- <div>- <h4 class="font-semibold text-gray-700">Group JID</h4>- <p class="text-sm text-gray-600">${escapeHtml(info.jid)}</p>- </div>- ${info.topic ? `- <div>- <h4 class="font-semibold text-gray-700">Description</h4>- <p class="text-sm text-gray-600">${escapeHtml(info.topic)}</p>- </div>- ` : ''}- <div>- <h4 class="font-semibold text-gray-700">Owner</h4>- <p class="text-sm text-gray-600">${escapeHtml(info.owner)}</p>- </div>- <div>- <h4 class="font-semibold text-gray-700">Created</h4>- <p class="text-sm text-gray-600">${new Date(info.created_at).toLocaleString()}</p>- </div>- <div class="flex space-x-4">- ${info.is_announce ? '<span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-sm">Announcement Only</span>' : ''}- ${info.is_locked ? '<span class="px-2 py-1 bg-red-100 text-red-800 rounded text-sm">Info Locked</span>' : ''}- </div>- <div>- <h4 class="font-semibold text-gray-700 mb-2">Participants (${info.participants.length})</h4>- <div class="max-h-64 overflow-y-auto border rounded">- <table class="w-full text-sm">- <thead class="bg-gray-100 sticky top-0">- <tr>- <th class="text-left px-3 py-2">Phone</th>- <th class="text-left px-3 py-2">Role</th>- </tr>- </thead>- <tbody>- ${info.participants.map(p => `- <tr class="border-t">- <td class="px-3 py-2 font-mono text-sm">${formatPhone(p.phone || p.jid)}</td>- <td class="px-3 py-2">- ${p.is_super_admin ? '<span class="px-2 py-1 bg-purple-100 text-purple-800 rounded text-xs">Owner</span>' :- p.is_admin ? '<span class="px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs">Admin</span>' :- '<span class="text-gray-500">Member</span>'}- </td>- </tr>- `).join('')}- </tbody>- </table>- </div>- </div>- </div>- `;- } else {- modalContent.innerHTML = `<p class="text-red-500">Error: ${data.error}</p>`;- }- })- .catch(error => {- modalContent.innerHTML = `<p class="text-red-500">Error: ${error.message}</p>`;- });- }-- function closeGroupModal() {- document.getElementById('group-modal').classList.add('hidden');- }-- function openEditModal(groupId, name, topic) {- document.getElementById('edit-group-id').value = groupId;- document.getElementById('edit-name').value = name;- document.getElementById('edit-topic').value = topic;- document.getElementById('edit-modal').classList.remove('hidden');- }-- function closeEditModal() {- document.getElementById('edit-modal').classList.add('hidden');- }-- document.getElementById('edit-form').addEventListener('submit', function(e) {- e.preventDefault();- const groupId = document.getElementById('edit-group-id').value;- const name = document.getElementById('edit-name').value.trim();- const topic = document.getElementById('edit-topic').value.trim();-- if (!name && !topic) {- showError('Please enter a name or description to update');- return;- }-- const payload = { group_id: groupId };- if (name) payload.name = name;- if (topic) payload.topic = topic;-- fetch('/api/groups/update', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload)- })- .then(response => response.json())- .then(data => {- if (data.success) {- closeEditModal();- loadGroups();- } else {- showError(data.error || 'Failed to update group');- }- })- .catch(error => {- showError('Failed to update group: ' + error.message);- });- });-- function escapeHtml(text) {- if (!text) return '';- const div = document.createElement('div');- div.textContent = text;- return div.innerHTML;- }-- function formatPhone(phone) {- if (!phone) return 'Unknown';- // Check if it's a LID (contains @lid or is too long to be a real phone)- const isLID = phone.includes('@lid') || (phone.replace(/\D/g, '').length > 13);- // Remove @s.whatsapp.net or @lid suffix- phone = phone.replace(/@s\.whatsapp\.net$/, '').replace(/@lid$/, '');- // Real phone numbers are 10-13 digits (with country code)- // LIDs are typically 15+ digits- if (isLID || phone.length > 13) {- // This is a LID - phone hidden due to WhatsApp privacy- return '<span class="text-gray-400" title="Phone hidden (WhatsApp Privacy)">Hidden</span>';- }- // Add + prefix for international format- if (/^\d+$/.test(phone) && phone.length >= 10) {- return '+' + phone;- }- return phone;- }-- // Close modals on escape key- document.addEventListener('keydown', function(e) {- if (e.key === 'Escape') {- closeGroupModal();- closeEditModal();- }- });-</script>-{% endblock %}diff --git a/server/whatsapp-rpc/web/templates/messages.html b/server/whatsapp-rpc/web/templates/messages.htmldeleted file mode 100644index a039d368..00000000--- a/server/whatsapp-rpc/web/templates/messages.html+++ /dev/null@@ -1,465 +0,0 @@-{% extends "base.html" %}--{% block title %}Received Messages - WhatsApp Controller{% endblock %}--{% block content %}-<div class="max-w-6xl mx-auto">- <div class="bg-white rounded-lg shadow-md p-6">- <div class="flex justify-between items-center mb-6">- <h2 class="text-2xl font-bold text-gray-800">Received Messages</h2>- <div class="flex items-center space-x-4">- <button onclick="loadMessages()" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition">- Refresh- </button>- <button onclick="clearMessages()" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition">- Clear Display- </button>- </div>- </div>-- <!-- Messages count -->- <div class="mb-4 p-3 bg-gray-100 rounded">- <p class="text-sm text-gray-600">- <span class="font-semibold">Total Messages:</span>- <span id="message-count">0</span>- </p>- </div>-- <!-- Messages container -->- <div id="messages-container" class="space-y-4 max-h-[600px] overflow-y-auto p-4 bg-gray-50 rounded">- <p class="text-gray-500 text-center py-8">No messages yet. Waiting for incoming messages...</p>- </div>- </div>-</div>--<!-- Media Viewer Modal -->-<div id="media-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50 flex items-center justify-center">- <div class="bg-white rounded-lg max-w-4xl max-h-[90vh] w-full m-4 overflow-hidden">- <div class="flex justify-between items-center p-4 border-b">- <h3 class="text-lg font-semibold" id="media-modal-title">Media Viewer</h3>- <button onclick="closeMediaModal()" class="text-gray-500 hover:text-gray-700">- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>- </svg>- </button>- </div>- <div id="media-modal-content" class="p-4 overflow-auto max-h-[calc(90vh-80px)] flex items-center justify-center bg-gray-100">- <p class="text-gray-500">Loading...</p>- </div>- </div>-</div>--{% endblock %}--{% block scripts %}-<script>- let messages = [];- let groupsCache = {}; // Cache group names by JID- const messagesContainer = document.getElementById('messages-container');- const messageCount = document.getElementById('message-count');-- // Load groups cache on page load- loadGroupsCache();-- // Subscribe to messages via WebSocket- socket.emit('subscribe_messages');-- // Load groups into cache for name lookup- async function loadGroupsCache() {- try {- const response = await fetch('/api/groups');- const data = await response.json();- if (data.success && data.data) {- data.data.forEach(group => {- groupsCache[group.jid] = group.name;- });- console.log(`Cached ${Object.keys(groupsCache).length} group names`);- }- } catch (error) {- console.error('Failed to load groups cache:', error);- }- }-- // Get group name from cache- function getGroupName(jid) {- return groupsCache[jid] || null;- }-- // Listen for new messages via WebSocket- socket.on('whatsapp_event', function(data) {- console.log('Received WhatsApp event:', data);-- if (data.type === 'message_received') {- // Add new message to the beginning- messages.unshift(data);- renderMessages();-- // Show notification- showNotification('New message received from ' + formatSender(data.data.sender));- }- });-- // Refresh just re-renders (messages come via WebSocket)- function loadMessages() {- renderMessages();- console.log('Messages display refreshed');- }-- // Render all messages- function renderMessages() {- if (messages.length === 0) {- messagesContainer.innerHTML = `- <div class="text-center py-8">- <p class="text-gray-500 mb-2">No messages yet.</p>- <p class="text-sm text-gray-400">Messages will appear here in real-time as they are received.</p>- <p class="text-xs text-gray-400 mt-2">Make sure WhatsApp is connected.</p>- </div>- `;- messageCount.textContent = '0';- return;- }-- messageCount.textContent = messages.length;-- messagesContainer.innerHTML = messages.map(msg => {- const data = msg.data || {};- return createMessageCard(data);- }).join('');- }-- // Create message card HTML- function createMessageCard(data) {- const messageType = data.message_type || 'unknown';- const timestamp = formatTimestamp(data.timestamp);- const sender = formatSender(data.sender);- const isFromMe = data.is_from_me;- const isGroup = data.is_group || false;- const isForwarded = data.is_forwarded || false;- const forwardingScore = data.forwarding_score || 0;- const chatId = data.chat_id || '';-- // Get group name if it's a group message- let groupName = null;- if (isGroup && chatId) {- groupName = getGroupName(chatId);- }-- let contentHtml = '';- let typeIcon = '';- let typeColor = 'bg-blue-100 text-blue-800';-- // Render based on message type- switch(messageType) {- case 'text':- typeIcon = '💬'; // Speech bubble- contentHtml = `<p class="text-gray-800">${escapeHtml(data.text || '')}</p>`;- break;-- case 'image':- typeIcon = '📷'; // Camera- typeColor = 'bg-purple-100 text-purple-800';- const imageInfo = data.image || {};- contentHtml = `- <div class="flex items-center space-x-3 mb-2">- <svg class="w-16 h-16 text-purple-400" fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd"></path>- </svg>- <div class="flex-1">- <p class="text-sm text-gray-600">Image message</p>- <p class="text-xs text-gray-500">${imageInfo.mime_type || 'image'} - ${formatFileSize(imageInfo.file_length || 0)}</p>- ${data.caption ? `<p class="text-gray-800 italic mt-1">${escapeHtml(data.caption)}</p>` : ''}- </div>- </div>- ${imageInfo.url ? `<button onclick="viewMedia('${escapeHtml(data.message_id)}', 'image', '${escapeHtml(imageInfo.url)}')" class="mt-2 px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600 text-sm">View Image</button>` : ''}- `;- break;-- case 'video':- typeIcon = '🎥'; // Video camera- typeColor = 'bg-pink-100 text-pink-800';- const videoInfo = data.video || {};- contentHtml = `- <div class="flex items-center space-x-3 mb-2">- <svg class="w-16 h-16 text-pink-400" fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path>- </svg>- <div class="flex-1">- <p class="text-sm text-gray-600">Video message</p>- <p class="text-xs text-gray-500">${videoInfo.mime_type || 'video'} - ${formatFileSize(videoInfo.file_length || 0)} - ${videoInfo.seconds || 0}s</p>- ${data.caption ? `<p class="text-gray-800 italic mt-1">${escapeHtml(data.caption)}</p>` : ''}- </div>- </div>- ${videoInfo.url ? `<button onclick="viewMedia('${escapeHtml(data.message_id)}', 'video', '${escapeHtml(videoInfo.url)}')" class="mt-2 px-4 py-2 bg-pink-500 text-white rounded hover:bg-pink-600 text-sm">View Video</button>` : ''}- `;- break;-- case 'audio':- typeIcon = '🎵'; // Musical note- typeColor = 'bg-green-100 text-green-800';- contentHtml = `<p class="text-sm text-gray-600">Audio message</p>`;- break;-- case 'document':- typeIcon = '📄'; // Document- typeColor = 'bg-yellow-100 text-yellow-800';- contentHtml = `- <p class="text-sm text-gray-600 mb-2">Document</p>- ${data.file_name ? `<p class="text-gray-700 font-mono text-xs">${escapeHtml(data.file_name)}</p>` : ''}- `;- break;-- case 'sticker':- typeIcon = '😎'; // Sticker emoji- typeColor = 'bg-orange-100 text-orange-800';- contentHtml = `<p class="text-sm text-gray-600">Sticker</p>`;- break;-- case 'location':- typeIcon = '📍'; // Pin- typeColor = 'bg-red-100 text-red-800';- contentHtml = `- <p class="text-sm text-gray-600 mb-2">Location</p>- ${data.location ? `- <p class="text-gray-800">- <span class="font-semibold">${escapeHtml(data.location.name || 'Unknown')}</span><br>- <span class="text-sm text-gray-600">${escapeHtml(data.location.address || '')}</span><br>- <span class="text-xs text-gray-500">Lat: ${data.location.latitude}, Lon: ${data.location.longitude}</span>- </p>- ` : ''}- `;- break;-- case 'contact':- typeIcon = '👤'; // Contact- typeColor = 'bg-indigo-100 text-indigo-800';- contentHtml = `- <p class="text-sm text-gray-600 mb-2">Contact Card</p>- ${data.contact ? `- <p class="text-gray-800 font-semibold">${escapeHtml(data.contact.display_name || 'Unknown')}</p>- ` : ''}- `;- break;-- case 'contacts':- typeIcon = '👥'; // Contacts- typeColor = 'bg-teal-100 text-teal-800';- contentHtml = `<p class="text-sm text-gray-600">Multiple contacts (${data.contacts_count || 0})</p>`;- break;-- default:- typeIcon = '❓'; // Question mark- typeColor = 'bg-gray-100 text-gray-800';- contentHtml = `<p class="text-sm text-gray-600">Unknown message type: ${messageType}</p>`;- }-- // Add quoted message if exists- let quotedHtml = '';- if (data.quoted) {- quotedHtml = `- <div class="mt-2 p-2 bg-gray-100 border-l-4 border-gray-400 rounded">- <p class="text-xs text-gray-600">Replying to:</p>- <p class="text-sm text-gray-700 italic">${escapeHtml(data.quoted.content || '')}</p>- </div>- `;- }-- // Build group info line- let groupInfoHtml = '';- if (isGroup) {- const displayGroupName = groupName || chatId.replace('@g.us', '');- groupInfoHtml = `<p class="text-xs text-purple-600">in <span class="font-medium">${escapeHtml(displayGroupName)}</span></p>`;- }-- // Build forwarded indicator- let forwardedHtml = '';- if (isForwarded) {- const forwardedLabel = forwardingScore > 4 ? 'Forwarded many times' : 'Forwarded';- forwardedHtml = `<span class="inline-block px-2 py-1 rounded text-xs font-medium bg-gray-200 text-gray-700 ml-1" title="Forwarding score: ${forwardingScore}">↷ ${forwardedLabel}</span>`;- }-- return `- <div class="bg-white border rounded-lg p-4 shadow-sm hover:shadow-md transition ${isFromMe ? 'border-l-4 border-green-500' : isGroup ? 'border-l-4 border-purple-500' : 'border-l-4 border-blue-500'}">- <div class="flex justify-between items-start mb-2">- <div class="flex items-center space-x-2">- <span class="text-2xl">${typeIcon}</span>- <div>- <p class="font-semibold text-gray-800">${sender}</p>- ${groupInfoHtml}- <span class="inline-block px-2 py-1 rounded text-xs font-medium ${typeColor}">${messageType}</span>${forwardedHtml}- </div>- </div>- <div class="text-right">- <p class="text-xs text-gray-500">${timestamp}</p>- ${isFromMe ? '<span class="text-xs text-green-600 font-medium">Sent by me</span>' : ''}- ${isGroup && !isFromMe ? '<span class="text-xs text-purple-600 font-medium">Group message</span>' : ''}- </div>- </div>- <div class="mt-2">- ${contentHtml}- ${quotedHtml}- </div>- <div class="mt-2 pt-2 border-t text-xs text-gray-400 flex justify-between items-center">- <span class="font-mono">ID: ${escapeHtml(data.message_id || 'N/A')}</span>- ${!isFromMe ? `<button onclick="markAsRead('${escapeHtml(data.message_id)}', '${escapeHtml(chatId)}', '${escapeHtml(data.sender || '')}')" class="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600">Mark Read</button>` : ''}- </div>- </div>- `;- }-- // Format timestamp- function formatTimestamp(timestamp) {- if (!timestamp) return 'Unknown time';- // Handle both ISO 8601 strings and Unix timestamps- const date = typeof timestamp === 'string' ? new Date(timestamp) : new Date(timestamp * 1000);- if (isNaN(date.getTime())) return 'Invalid Date';- return date.toLocaleString();- }-- // Format sender- function formatSender(sender) {- if (!sender) return 'Unknown';- // Remove @s.whatsapp.net suffix- return sender.replace('@s.whatsapp.net', '').replace('@c.us', '');- }-- // Escape HTML- function escapeHtml(text) {- const div = document.createElement('div');- div.textContent = text;- return div.innerHTML;- }-- // Clear messages display- function clearMessages() {- if (confirm('Clear all displayed messages? (This will not delete them from storage)')) {- messages = [];- renderMessages();- }- }-- // Format file size- function formatFileSize(bytes) {- if (!bytes || bytes === 0) return '0 B';- const k = 1024;- const sizes = ['B', 'KB', 'MB', 'GB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));- return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];- }-- // View media function- function viewMedia(messageId, mediaType, url) {- console.log('View media:', messageId, mediaType, url);-- const modal = document.getElementById('media-modal');- const modalTitle = document.getElementById('media-modal-title');- const modalContent = document.getElementById('media-modal-content');-- // Show modal- modal.classList.remove('hidden');-- // Set title- modalTitle.textContent = `Viewing ${mediaType}`;-- // Show loading- modalContent.innerHTML = '<p class="text-gray-500">Downloading and decrypting media...</p>';-- // Fetch media via Flask RPC endpoint (returns JSON with base64 data)- fetch(`/api/media/${messageId}`)- .then(response => response.json())- .then(result => {- if (!result.success) {- throw new Error(result.error || 'Failed to download media');- }-- const mediaData = result.data;- const base64Data = mediaData.data;- const mimeType = mediaData.mime_type || 'application/octet-stream';-- // Convert base64 to blob- const byteCharacters = atob(base64Data);- const byteNumbers = new Array(byteCharacters.length);- for (let i = 0; i < byteCharacters.length; i++) {- byteNumbers[i] = byteCharacters.charCodeAt(i);- }- const byteArray = new Uint8Array(byteNumbers);- const blob = new Blob([byteArray], { type: mimeType });- const blobUrl = URL.createObjectURL(blob);-- if (mediaType === 'image') {- modalContent.innerHTML = `- <img src="${blobUrl}" class="max-w-full max-h-full object-contain" alt="WhatsApp Image">- `;- } else if (mediaType === 'video') {- modalContent.innerHTML = `- <video controls class="max-w-full max-h-full" autoplay>- <source src="${blobUrl}" type="${mimeType}">- Your browser does not support the video tag.- </video>- `;- } else if (mediaType === 'audio') {- modalContent.innerHTML = `- <audio controls autoplay class="w-full">- <source src="${blobUrl}" type="${mimeType}">- Your browser does not support the audio tag.- </audio>- `;- } else {- modalContent.innerHTML = `- <div class="text-center">- <p class="text-gray-600 mb-4">Media loaded successfully</p>- <a href="${blobUrl}" download class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">- Download ${mediaType}- </a>- </div>- `;- }- })- .catch(error => {- console.error('Error loading media:', error);- modalContent.innerHTML = `- <div class="text-center text-red-600">- <p>Failed to load media: ${error.message}</p>- <p class="text-sm text-gray-500 mt-2">The message may have expired or been deleted.</p>- </div>- `;- });- }-- // Close media modal- function closeMediaModal() {- const modal = document.getElementById('media-modal');- modal.classList.add('hidden');-- // Clear content to stop videos/audio- const modalContent = document.getElementById('media-modal-content');- modalContent.innerHTML = '<p class="text-gray-500">Loading...</p>';- }-- // Show notification- function showNotification(message, type = 'info') {- // Simple console notification for now- console.log(`[${type.toUpperCase()}] ${message}`);-- // Could add a toast notification here in the future- }-- // Mark message as read via WebSocket- function markAsRead(messageId, chatJid, senderJid) {- console.log('Marking as read:', messageId, chatJid, senderJid);- socket.emit('mark_read', {- message_ids: [messageId],- chat_jid: chatJid,- sender_jid: senderJid || null- });- }-- // Listen for mark_read result- socket.on('mark_read_result', function(data) {- if (data.success) {- showNotification('Message marked as read');- } else {- showNotification('Failed to mark as read: ' + data.error, 'error');- }- });-</script>-{% endblock %}diff --git a/server/whatsapp-rpc/web/templates/messaging.html b/server/whatsapp-rpc/web/templates/messaging.htmldeleted file mode 100644index 138436ac..00000000--- a/server/whatsapp-rpc/web/templates/messaging.html+++ /dev/null@@ -1,681 +0,0 @@-{% extends "base.html" %}-{% block title %}Enhanced Messaging - WhatsApp Controller{% endblock %}--{% block content %}-<div class="space-y-8">- <!-- Page Header -->- <div>- <h1 class="text-3xl font-bold text-gray-900">Enhanced Messaging</h1>- <p class="text-gray-600 mt-1">Send messages with advanced features: media, location, stickers, contact cards, replies, and more</p>-- <!-- Connection Status Badge -->- <div id="connection-status" class="mt-3 inline-flex items-center px-4 py-2 rounded-lg">- <span class="mr-2">Checking connection...</span>- </div>- </div>-- <!-- Enhanced Message Composer -->- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-6">Compose Enhanced Message</h2>-- <form id="enhanced-message-form" class="space-y-6">- <!-- Recipient -->- <div class="grid grid-cols-1 md:grid-cols-2 gap-4">- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Send To</label>- <div class="flex space-x-4">- <label class="flex items-center">- <input type="radio" name="recipient_type" value="phone" checked class="mr-2">- <span>Phone Number</span>- </label>- <label class="flex items-center">- <input type="radio" name="recipient_type" value="group" class="mr-2">- <span>Group</span>- </label>- </div>- </div>- </div>-- <div class="grid grid-cols-1 md:grid-cols-2 gap-4">- <div id="phone-input">- <label class="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>- <input type="text" id="phone" placeholder="919876543210"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- <div id="group-input" class="hidden">- <label class="block text-sm font-medium text-gray-700 mb-2">Select Group</label>- <div class="flex space-x-2">- <select id="group_id" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- <option value="">-- Select a group --</option>- </select>- <button type="button" onclick="loadGroupsDropdown()" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 whitespace-nowrap">- Load Groups- </button>- </div>- <p id="groups-status" class="text-xs text-gray-500 mt-1"></p>- </div>- </div>-- <!-- Message Type -->- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Message Type</label>- <select id="message-type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- <option value="text">Text Message</option>- <option value="image">Image</option>- <option value="video">Video</option>- <option value="audio">Audio</option>- <option value="document">Document</option>- <option value="sticker">Sticker</option>- <option value="location">Location</option>- <option value="contact">Contact Card</option>- </select>- </div>-- <!-- Text Message -->- <div id="text-section">- <label class="block text-sm font-medium text-gray-700 mb-2">Message</label>- <textarea id="message-text" placeholder="Enter your message..."- rows="4" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>- </div>-- <!-- Media Section -->- <div id="media-section" class="hidden space-y-4">- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Select Media File</label>- <input type="file" id="media-file-input" accept="image/*,video/*,audio/*,.pdf,.doc,.docx"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">- <p class="text-sm text-gray-500 mt-1">Choose a file from your computer</p>- <div id="messaging-file-preview" class="mt-2 hidden">- <div class="flex items-center gap-2 text-sm text-gray-600 bg-gray-50 p-2 rounded">- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>- </svg>- <span id="messaging-file-name">No file selected</span>- <span id="messaging-file-size" class="text-xs text-gray-500"></span>- </div>- </div>- </div>-- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Caption (optional)</label>- <textarea id="media-caption" placeholder="Enter caption for media..."- rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>- </div>- </div>-- <!-- Location Section -->- <div id="location-section" class="hidden space-y-4">- <div class="grid grid-cols-1 md:grid-cols-2 gap-4">- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Latitude</label>- <input type="number" id="latitude" step="any" placeholder="19.0760"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Longitude</label>- <input type="number" id="longitude" step="any" placeholder="72.8777"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- </div>- <div class="grid grid-cols-1 md:grid-cols-2 gap-4">- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Location Name (optional)</label>- <input type="text" id="location-name" placeholder="Mumbai, India"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Address (optional)</label>- <input type="text" id="location-address" placeholder="Full address"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- </div>- </div>-- <!-- Contact Card Section -->- <div id="contact-section" class="hidden space-y-4">- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Display Name</label>- <input type="text" id="contact-display-name" placeholder="John Doe"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">vCard Data</label>- <textarea id="contact-vcard" placeholder="BEGIN:VCARD VERSION:3.0 FN:John Doe TEL:+1234567890 EMAIL:[email protected] END:VCARD"- rows="6" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 font-mono text-sm"></textarea>- <p class="text-sm text-gray-500 mt-1">Enter vCard format contact information</p>- </div>- <div class="bg-blue-50 p-4 rounded-lg border border-blue-200">- <h4 class="font-semibold text-blue-900 mb-2">Quick vCard Template</h4>- <button type="button" onclick="fillVCardTemplate()" class="text-sm bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">- Use Template- </button>- </div>- </div>-- <!-- Reply Section -->- <div class="border-t pt-6">- <div class="flex items-center justify-between mb-4">- <label class="flex items-center">- <input type="checkbox" id="enable-reply" class="mr-2">- <span class="font-medium text-gray-700">Reply to Message</span>- </label>- </div>-- <div id="reply-section" class="hidden space-y-4 bg-gray-50 p-4 rounded-lg">- <div class="grid grid-cols-1 md:grid-cols-2 gap-4">- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Original Message ID</label>- <input type="text" id="reply-message-id" placeholder="Message ID to reply to"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Original Sender</label>- <input type="text" id="reply-sender" placeholder="Sender JID"- class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">- </div>- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-2">Original Message Content</label>- <textarea id="reply-content" placeholder="Content of the message being replied to"- rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>- </div>- </div>- </div>-- <!-- Actions -->- <div class="flex flex-wrap gap-4 pt-6 border-t">- <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 flex items-center">- <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>- </svg>- Send Enhanced Message- </button>- <button type="button" id="send-typing" class="bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 flex items-center">- <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>- </svg>- Send Typing...- </button>- <button type="button" id="clear-form" class="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700">- Clear Form- </button>- </div>- </form>- </div>-- <!-- Message Status -->- <div id="message-status" class="hidden">- <div class="bg-white rounded-lg shadow-md p-6">- <h2 class="text-xl font-semibold mb-4">Message Status</h2>- <div id="status-content" class="space-y-2"></div>- </div>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>-const mimeTypes = {- image: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],- video: ['video/mp4', 'video/3gpp', 'video/quicktime', 'video/avi'],- audio: ['audio/mpeg', 'audio/ogg', 'audio/wav', 'audio/aac'],- document: ['application/pdf', 'text/plain', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']-};--let messagingFileBase64 = null;-let messagingFileName = '';-let messagingFileMimeType = '';--document.addEventListener('DOMContentLoaded', function() {- // Event listeners- document.getElementById('enhanced-message-form').addEventListener('submit', sendEnhancedMessage);- document.getElementById('message-type').addEventListener('change', handleMessageTypeChange);- document.getElementById('enable-reply').addEventListener('change', toggleReplySection);- document.getElementById('clear-form').addEventListener('click', clearForm);- document.getElementById('send-typing').addEventListener('click', sendTypingIndicator);-- // File selection handler- document.getElementById('media-file-input').addEventListener('change', handleFileSelection);-- // Recipient type change- document.querySelectorAll('input[name="recipient_type"]').forEach(radio => {- radio.addEventListener('change', handleRecipientTypeChange);- });-- // Initialize- handleMessageTypeChange();-- // Check connection status on load and periodically- updateConnectionStatus();- setInterval(updateConnectionStatus, 5000); // Update every 5 seconds-- // Listen for typing result- socket.on('typing_result', function(data) {- if (data.success) {- showStatus('Typing indicator sent', 'success');- } else {- showStatus('Failed: ' + data.error, 'error');- }- });-});--async function updateConnectionStatus() {- try {- const response = await fetch('/api/status');- const status = await response.json();-- const statusBadge = document.getElementById('connection-status');-- if (status.data && status.data.connected) {- statusBadge.className = 'mt-3 inline-flex items-center px-4 py-2 rounded-lg bg-green-100 border border-green-300';- statusBadge.innerHTML = `- <svg class="w-4 h-4 mr-2 text-green-600" fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>- </svg>- <span class="text-green-800 font-medium">WhatsApp Connected</span>- `;- } else {- statusBadge.className = 'mt-3 inline-flex items-center px-4 py-2 rounded-lg bg-red-100 border border-red-300';- statusBadge.innerHTML = `- <svg class="w-4 h-4 mr-2 text-red-600" fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>- </svg>- <span class="text-red-800 font-medium">WhatsApp Not Connected - <a href="/" class="underline">Go to Dashboard</a></span>- `;- }- } catch (error) {- const statusBadge = document.getElementById('connection-status');- statusBadge.className = 'mt-3 inline-flex items-center px-4 py-2 rounded-lg bg-yellow-100 border border-yellow-300';- statusBadge.innerHTML = `- <svg class="w-4 h-4 mr-2 text-yellow-600" fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>- </svg>- <span class="text-yellow-800 font-medium">Unable to check connection status</span>- `;- }-}--function handleFileSelection(e) {- const file = e.target.files[0];- if (!file) {- messagingFileBase64 = null;- messagingFileName = '';- messagingFileMimeType = '';- document.getElementById('messaging-file-preview').classList.add('hidden');- return;- }-- messagingFileName = file.name;- messagingFileMimeType = file.type;-- // Update preview- document.getElementById('messaging-file-name').textContent = file.name;- document.getElementById('messaging-file-size').textContent = formatFileSize(file.size);- document.getElementById('messaging-file-preview').classList.remove('hidden');-- // Read file as base64- const reader = new FileReader();- reader.onload = function(event) {- messagingFileBase64 = event.target.result.split(',')[1];- showStatus('File loaded: ' + file.name, 'success');- };- reader.onerror = function() {- showStatus('Failed to read file', 'error');- messagingFileBase64 = null;- };- reader.readAsDataURL(file);-}--function formatFileSize(bytes) {- if (bytes === 0) return '0 Bytes';- const k = 1024;- const sizes = ['Bytes', 'KB', 'MB', 'GB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));- return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];-}--function handleRecipientTypeChange() {- const recipientType = document.querySelector('input[name="recipient_type"]:checked').value;-- if (recipientType === 'phone') {- document.getElementById('phone-input').classList.remove('hidden');- document.getElementById('group-input').classList.add('hidden');- } else {- document.getElementById('phone-input').classList.add('hidden');- document.getElementById('group-input').classList.remove('hidden');- }-}--function handleMessageTypeChange() {- const messageType = document.getElementById('message-type').value;-- // Hide all sections- document.getElementById('text-section').classList.add('hidden');- document.getElementById('media-section').classList.add('hidden');- document.getElementById('location-section').classList.add('hidden');- document.getElementById('contact-section').classList.add('hidden');-- // Show relevant section- if (messageType === 'text') {- document.getElementById('text-section').classList.remove('hidden');- } else if (['image', 'video', 'audio', 'document', 'sticker'].includes(messageType)) {- document.getElementById('media-section').classList.remove('hidden');-- // Update file accept attribute based on type- const fileInput = document.getElementById('media-file-input');- if (messageType === 'sticker') {- fileInput.accept = 'image/webp,image/png';- } else if (messageType === 'image') {- fileInput.accept = 'image/*';- } else if (messageType === 'video') {- fileInput.accept = 'video/*';- } else if (messageType === 'audio') {- fileInput.accept = 'audio/*';- } else if (messageType === 'document') {- fileInput.accept = '.pdf,.doc,.docx,.txt,.zip';- }- } else if (messageType === 'location') {- document.getElementById('location-section').classList.remove('hidden');- } else if (messageType === 'contact') {- document.getElementById('contact-section').classList.remove('hidden');- }-}--function toggleReplySection() {- const enabled = document.getElementById('enable-reply').checked;- const section = document.getElementById('reply-section');-- if (enabled) {- section.classList.remove('hidden');- } else {- section.classList.add('hidden');- }-}--async function sendEnhancedMessage(e) {- e.preventDefault();-- // Check WhatsApp connection status first- try {- const statusResponse = await fetch('/api/status');- const status = await statusResponse.json();-- if (!status.data || !status.data.connected) {- showStatus('WhatsApp is not connected. Please connect first from the dashboard.', 'error');- return;- }- } catch (error) {- showStatus('Failed to check connection status. Please try again.', 'error');- return;- }-- const messageType = document.getElementById('message-type').value;- const recipientType = document.querySelector('input[name="recipient_type"]:checked').value;-- // Build message data- const messageData = {- type: messageType- };-- // Set recipient- if (recipientType === 'phone') {- messageData.phone = document.getElementById('phone').value.trim();- } else {- messageData.group_id = document.getElementById('group_id').value.trim();- }-- // Add content based on type- if (messageType === 'text') {- messageData.message = document.getElementById('message-text').value.trim();- } else if (['image', 'video', 'audio', 'document', 'sticker'].includes(messageType)) {- if (!messagingFileBase64) {- showStatus('Please select a file first', 'error');- return;- }-- const caption = document.getElementById('media-caption').value.trim();-- messageData.media_data = {- data: messagingFileBase64,- mime_type: messagingFileMimeType,- filename: messagingFileName,- caption: caption- };- } else if (messageType === 'location') {- messageData.location = {- latitude: parseFloat(document.getElementById('latitude').value),- longitude: parseFloat(document.getElementById('longitude').value),- name: document.getElementById('location-name').value.trim(),- address: document.getElementById('location-address').value.trim()- };- } else if (messageType === 'contact') {- const displayName = document.getElementById('contact-display-name').value.trim();- const vcard = document.getElementById('contact-vcard').value.trim();-- if (!displayName || !vcard) {- showStatus('Please enter display name and vCard data', 'error');- return;- }-- messageData.contact = {- display_name: displayName,- vcard: vcard- };- }-- // Add reply data if enabled- if (document.getElementById('enable-reply').checked) {- messageData.reply = {- message_id: document.getElementById('reply-message-id').value.trim(),- sender: document.getElementById('reply-sender').value.trim(),- content: document.getElementById('reply-content').value.trim()- };- }-- try {- showStatus('Sending message...', 'info');-- const response = await fetch('/api/send/enhanced', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify(messageData)- });-- const result = await response.json();-- // Clear the "sending" message- document.getElementById('status-content').innerHTML = '';-- // Show detailed error if available- if (!result.success) {- let errorMsg = result.error || 'Unknown error occurred';-- // Provide user-friendly messages for common errors- if (errorMsg.includes('websocket not connected')) {- errorMsg = 'WhatsApp connection lost. Please check the dashboard and reconnect.';- } else if (errorMsg.includes('not connected')) {- errorMsg = 'WhatsApp is not connected. Please connect first.';- } else if (errorMsg.includes('invalid')) {- errorMsg = 'Invalid data provided: ' + errorMsg;- }-- showMessageStatus({ success: false, error: errorMsg });- } else {- showMessageStatus(result);- // Clear form on success- clearForm();- }- } catch (error) {- console.error('Error sending message:', error);- showMessageStatus({- success: false,- error: 'Network error: Unable to reach the API server. Please check if services are running.'- });- }-}--function clearForm() {- document.getElementById('enhanced-message-form').reset();- document.getElementById('enable-reply').checked = false;- toggleReplySection();- handleMessageTypeChange();- handleRecipientTypeChange();-}--function showMessageStatus(result) {- const statusDiv = document.getElementById('message-status');- const content = document.getElementById('status-content');-- const timestamp = new Date().toLocaleString();- const statusClass = result.success ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200';-- const statusHtml = `- <div class="border rounded-lg p-4 ${statusClass}">- <div class="flex justify-between items-start">- <div class="flex-1">- <h3 class="font-semibold">${result.success ? 'Success' : 'Error'}</h3>- <p class="text-sm mt-1">${result.success ? (result.message || 'Message sent successfully') : result.error}</p>- <p class="text-xs mt-2 opacity-75">${timestamp}</p>- </div>- <button onclick="this.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>- </svg>- </button>- </div>- </div>- `;-- content.insertAdjacentHTML('afterbegin', statusHtml);- statusDiv.classList.remove('hidden');-- // Auto-remove after 10 seconds for success messages- if (result.success) {- setTimeout(() => {- const firstStatus = content.firstElementChild;- if (firstStatus) {- firstStatus.remove();- if (content.children.length === 0) {- statusDiv.classList.add('hidden');- }- }- }, 10000);- }-}--function fillVCardTemplate() {- const template = `BEGIN:VCARD-VERSION:3.0-FN:John Doe-TEL:+1234567890-EMAIL:[email protected]-ORG:Example Company-TITLE:Software Engineer-END:VCARD`;-- document.getElementById('contact-display-name').value = 'John Doe';- document.getElementById('contact-vcard').value = template;- showStatus('vCard template filled. Please customize the details.', 'success');-}--async function loadGroupsDropdown() {- const select = document.getElementById('group_id');- const status = document.getElementById('groups-status');-- status.textContent = 'Loading groups...';- status.className = 'text-xs text-blue-500 mt-1';-- try {- const response = await fetch('/api/groups');- const data = await response.json();-- if (data.success && data.data) {- const groups = data.data;- select.innerHTML = '<option value="">-- Select a group --</option>';-- groups.forEach(group => {- const option = document.createElement('option');- option.value = group.jid;- option.textContent = `${group.name} (${group.size} members)`;- select.appendChild(option);- });-- status.textContent = `${groups.length} groups loaded`;- status.className = 'text-xs text-green-600 mt-1';- } else {- status.textContent = data.error || 'Failed to load groups';- status.className = 'text-xs text-red-500 mt-1';- }- } catch (error) {- status.textContent = 'Error: ' + error.message;- status.className = 'text-xs text-red-500 mt-1';- }-}--function showStatus(message, type) {- if (type === 'info') {- // Show info message differently- const statusDiv = document.getElementById('message-status');- const content = document.getElementById('status-content');-- const statusHtml = `- <div class="border rounded-lg p-4 bg-blue-50 text-blue-800 border-blue-200">- <div class="flex items-center">- <svg class="w-5 h-5 mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>- </svg>- <span>${message}</span>- </div>- </div>- `;-- content.innerHTML = statusHtml;- statusDiv.classList.remove('hidden');- } else {- showMessageStatus({- success: type === 'success',- message: type === 'success' ? message : null,- error: type === 'error' ? message : null- });- }-}--function sendTypingIndicator() {- const recipientType = document.querySelector('input[name="recipient_type"]:checked').value;- let jid;-- if (recipientType === 'phone') {- const phone = document.getElementById('phone').value.trim();- if (!phone) {- showStatus('Please enter a phone number first', 'error');- return;- }- jid = phone + '@s.whatsapp.net';- } else {- jid = document.getElementById('group_id').value.trim();- if (!jid) {- showStatus('Please select a group first', 'error');- return;- }- }-- // Send typing indicator via WebSocket- socket.emit('typing', {- jid: jid,- state: 'composing'- });-- showStatus('Sending typing indicator...', 'info');-- // Auto-stop typing after 5 seconds- setTimeout(() => {- socket.emit('typing', {- jid: jid,- state: 'paused'- });- }, 5000);-}-</script>-{% endblock %}\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/send.html b/server/whatsapp-rpc/web/templates/send.htmldeleted file mode 100644index 48b0c79b..00000000--- a/server/whatsapp-rpc/web/templates/send.html+++ /dev/null@@ -1,259 +0,0 @@-{% extends "base.html" %}--{% block title %}Send Message - WhatsApp Controller{% endblock %}--{% block content %}-<div class="max-w-2xl mx-auto">- <div class="bg-white rounded-lg shadow-md p-6">- <h1 class="text-2xl font-semibold mb-6 flex items-center">- <svg class="w-8 h-8 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>- </svg>- Send WhatsApp Message- </h1>-- <form method="POST" class="space-y-6">- <!-- Phone Number Input -->- <div>- <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">- Phone Number- </label>- <div class="relative">- <input type="text"- id="phone"- name="phone"- placeholder="e.g., 1234567890"- required- class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:ring-2 focus:ring-green-500 focus:border-transparent">- <div class="absolute inset-y-0 right-0 pr-3 flex items-center">- <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>- </svg>- </div>- </div>- <p class="text-sm text-gray-600 mt-1">- Enter phone number with country code (without + sign)- </p>- </div>-- <!-- Message Input -->- <div>- <label for="message" class="block text-sm font-medium text-gray-700 mb-2">- Message- </label>- <textarea id="message"- name="message"- rows="6"- placeholder="Enter your message here..."- required- class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:ring-2 focus:ring-green-500 focus:border-transparent"></textarea>- <div class="flex justify-between items-center mt-1">- <p class="text-sm text-gray-600">- Type your WhatsApp message- </p>- <span id="char-count" class="text-sm text-gray-500">0 characters</span>- </div>- </div>-- <!-- Action Buttons -->- <div class="flex space-x-4">- <button type="submit"- id="send-btn"- class="flex-1 bg-green-600 text-white py-3 px-6 rounded-lg hover:bg-green-700 transition font-medium flex items-center justify-center">- <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>- </svg>- Send Message- </button>-- <button type="button"- onclick="clearForm()"- class="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition font-medium">- Clear- </button>- </div>- </form>-- <!-- Connection Status Warning -->- <div id="connection-warning" class="mt-6 hidden">- <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">- <div class="flex">- <svg class="w-5 h-5 text-yellow-400 mr-3" fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>- </svg>- <div>- <h3 class="text-sm font-medium text-yellow-800">WhatsApp Not Connected</h3>- <p class="text-sm text-yellow-700 mt-1">- Please start WhatsApp service from the <a href="{{ url_for('index') }}" class="underline">dashboard</a> before sending messages.- </p>- </div>- </div>- </div>- </div>- </div>-- <!-- Recent Messages -->- <div class="bg-white rounded-lg shadow-md p-6 mt-6">- <h2 class="text-lg font-semibold mb-4">Recent Messages</h2>- <div id="recent-messages" class="space-y-3">- <p class="text-gray-600">No recent messages</p>- </div>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>- let recentMessages = JSON.parse(localStorage.getItem('recentMessages') || '[]');-- // Character counter- document.getElementById('message').addEventListener('input', function(e) {- const count = e.target.value.length;- document.getElementById('char-count').textContent = `${count} characters`;- });-- // Form submission- document.querySelector('form').addEventListener('submit', function(e) {- e.preventDefault();-- const phone = document.getElementById('phone').value.trim();- const message = document.getElementById('message').value.trim();- const sendBtn = document.getElementById('send-btn');-- if (!phone || !message) {- alert('Please fill in both phone number and message');- return;- }-- // Disable button and show loading- sendBtn.disabled = true;- sendBtn.innerHTML = `- <svg class="w-5 h-5 mr-2 animate-spin" fill="none" viewBox="0 0 24 24">- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>- <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>- </svg>- Sending...- `;-- fetch('/api/send', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ phone, message })- })- .then(response => response.json())- .then(data => {- if (data.success) {- // Add to recent messages- addRecentMessage(phone, message, 'sent');-- // Clear message field- document.getElementById('message').value = '';- document.getElementById('char-count').textContent = '0 characters';-- // Show success message- showNotification('Message sent successfully!', 'success');- } else {- showNotification(`Failed to send message: ${data.error}`, 'error');- }- })- .catch(error => {- showNotification(`Error: ${error.message}`, 'error');- })- .finally(() => {- // Re-enable button- sendBtn.disabled = false;- sendBtn.innerHTML = `- <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>- </svg>- Send Message- `;- });- });-- function clearForm() {- document.getElementById('phone').value = '';- document.getElementById('message').value = '';- document.getElementById('char-count').textContent = '0 characters';- }-- function addRecentMessage(phone, message, status) {- const messageObj = {- phone,- message: message.substring(0, 100) + (message.length > 100 ? '...' : ''),- status,- timestamp: new Date().toLocaleString()- };-- recentMessages.unshift(messageObj);- if (recentMessages.length > 5) {- recentMessages = recentMessages.slice(0, 5);- }-- localStorage.setItem('recentMessages', JSON.stringify(recentMessages));- renderRecentMessages();- }-- function renderRecentMessages() {- const container = document.getElementById('recent-messages');-- if (recentMessages.length === 0) {- container.innerHTML = '<p class="text-gray-600">No recent messages</p>';- return;- }-- container.innerHTML = recentMessages.map(msg => `- <div class="border rounded-lg p-3 bg-gray-50">- <div class="flex justify-between items-start mb-2">- <span class="font-medium text-gray-900">${msg.phone}</span>- <span class="text-xs text-gray-500">${msg.timestamp}</span>- </div>- <p class="text-gray-700 text-sm">${msg.message}</p>- <span class="inline-block mt-2 px-2 py-1 text-xs rounded-full ${- msg.status === 'sent' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'- }">${msg.status}</span>- </div>- `).join('');- }-- function showNotification(message, type) {- // Create notification element- const notification = document.createElement('div');- notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${- type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'- }`;- notification.textContent = message;-- document.body.appendChild(notification);-- // Remove after 3 seconds- setTimeout(() => {- notification.remove();- }, 3000);- }-- // Check connection status and show warning if needed- function checkConnectionStatus() {- fetch('/api/status')- .then(response => response.json())- .then(data => {- const warning = document.getElementById('connection-warning');- if (data.success && data.data && !data.data.connected) {- warning.classList.remove('hidden');- } else {- warning.classList.add('hidden');- }- })- .catch(() => {- document.getElementById('connection-warning').classList.remove('hidden');- });- }-- // Initialize- renderRecentMessages();- checkConnectionStatus();-- // Check status periodically- setInterval(checkConnectionStatus, 30000);-</script>-{% endblock %}\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/settings.html b/server/whatsapp-rpc/web/templates/settings.htmldeleted file mode 100644index 65535dbb..00000000--- a/server/whatsapp-rpc/web/templates/settings.html+++ /dev/null@@ -1,459 +0,0 @@-{% extends "base.html" %}--{% block title %}Settings - WhatsApp Controller{% endblock %}--{% block content %}-<div class="space-y-6">- <!-- Page Header -->- <div class="flex items-center justify-between">- <div>- <h1 class="text-2xl font-bold text-gray-900">Settings</h1>- <p class="text-gray-600">Configure rate limiting and anti-ban protection</p>- </div>- <button id="refresh-stats" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center">- <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>- </svg>- Refresh- </button>- </div>-- <!-- Status Alert -->- <div id="status-alert" class="hidden"></div>-- <!-- Stats Cards -->- <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">- <!-- Messages Last Minute -->- <div class="bg-white rounded-lg shadow p-6">- <div class="flex items-center">- <div class="p-3 rounded-full bg-blue-100 text-blue-600">- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path>- </svg>- </div>- <div class="ml-4">- <p class="text-sm text-gray-500">Messages/Min</p>- <p class="text-2xl font-semibold text-gray-900"><span id="stat-messages-minute">-</span><span class="text-sm text-gray-400" id="stat-messages-minute-limit"></span></p>- </div>- </div>- </div>-- <!-- Messages Last Hour -->- <div class="bg-white rounded-lg shadow p-6">- <div class="flex items-center">- <div class="p-3 rounded-full bg-green-100 text-green-600">- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>- </svg>- </div>- <div class="ml-4">- <p class="text-sm text-gray-500">Messages/Hour</p>- <p class="text-2xl font-semibold text-gray-900"><span id="stat-messages-hour">-</span><span class="text-sm text-gray-400" id="stat-messages-hour-limit"></span></p>- </div>- </div>- </div>-- <!-- New Contacts Today -->- <div class="bg-white rounded-lg shadow p-6">- <div class="flex items-center">- <div class="p-3 rounded-full bg-purple-100 text-purple-600">- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"></path>- </svg>- </div>- <div class="ml-4">- <p class="text-sm text-gray-500">New Contacts Today</p>- <p class="text-2xl font-semibold text-gray-900"><span id="stat-new-contacts">-</span><span class="text-sm text-gray-400" id="stat-new-contacts-limit"></span></p>- </div>- </div>- </div>-- <!-- Response Rate -->- <div class="bg-white rounded-lg shadow p-6">- <div class="flex items-center">- <div class="p-3 rounded-full bg-yellow-100 text-yellow-600">- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>- </svg>- </div>- <div class="ml-4">- <p class="text-sm text-gray-500">Response Rate</p>- <p class="text-2xl font-semibold text-gray-900"><span id="stat-response-rate">-</span>%</p>- </div>- </div>- </div>- </div>-- <!-- Pause Status -->- <div id="pause-alert" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg">- <div class="flex items-center justify-between">- <div class="flex items-center">- <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>- </svg>- <span><strong>Rate Limiting Paused:</strong> <span id="pause-reason"></span></span>- </div>- <button id="unpause-btn" class="bg-red-600 text-white px-4 py-1 rounded hover:bg-red-700">- Unpause- </button>- </div>- </div>-- <!-- Configuration Section -->- <div class="bg-white rounded-lg shadow">- <div class="px-6 py-4 border-b border-gray-200">- <h2 class="text-lg font-semibold text-gray-900">Rate Limiting Configuration</h2>- <p class="text-sm text-gray-500">Configure delays and limits to avoid WhatsApp detection and bans</p>- </div>-- <form id="config-form" class="p-6 space-y-6">- <!-- Enable/Disable -->- <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">- <div>- <h3 class="font-medium text-gray-900">Enable Rate Limiting</h3>- <p class="text-sm text-gray-500">Master switch for all rate limiting features</p>- </div>- <label class="relative inline-flex items-center cursor-pointer">- <input type="checkbox" id="config-enabled" class="sr-only peer" checked>- <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>- </label>- </div>-- <!-- Delays Section -->- <div class="border-t pt-6">- <h3 class="text-md font-medium text-gray-900 mb-4">Message Delays (milliseconds)</h3>- <div class="grid grid-cols-1 md:grid-cols-2 gap-6">- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">Minimum Delay</label>- <input type="number" id="config-min-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">- <p class="text-xs text-gray-500 mt-1">Minimum time between messages (default: 3000ms)</p>- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">Maximum Delay</label>- <input type="number" id="config-max-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">- <p class="text-xs text-gray-500 mt-1">Maximum for randomization (default: 8000ms)</p>- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">Typing Indicator Duration</label>- <input type="number" id="config-typing-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">- <p class="text-xs text-gray-500 mt-1">How long to show typing (default: 2000ms)</p>- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">Extra Delay for Links</label>- <input type="number" id="config-link-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">- <p class="text-xs text-gray-500 mt-1">Additional delay for messages with URLs (default: 5000ms)</p>- </div>- </div>- </div>-- <!-- Rate Limits Section -->- <div class="border-t pt-6">- <h3 class="text-md font-medium text-gray-900 mb-4">Rate Limits</h3>- <div class="grid grid-cols-1 md:grid-cols-3 gap-6">- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">Messages per Minute</label>- <input type="number" id="config-per-minute" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0">- <p class="text-xs text-gray-500 mt-1">0 = unlimited (default: 10)</p>- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">Messages per Hour</label>- <input type="number" id="config-per-hour" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0">- <p class="text-xs text-gray-500 mt-1">0 = unlimited (default: 60)</p>- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">New Contacts per Day</label>- <input type="number" id="config-new-contacts" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0">- <p class="text-xs text-gray-500 mt-1">Critical for new accounts (default: 20)</p>- </div>- </div>- </div>-- <!-- Human Simulation Section -->- <div class="border-t pt-6">- <h3 class="text-md font-medium text-gray-900 mb-4">Human Simulation</h3>- <div class="grid grid-cols-1 md:grid-cols-2 gap-6">- <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">- <div>- <h4 class="font-medium text-gray-900">Simulate Typing</h4>- <p class="text-sm text-gray-500">Send typing indicator before messages</p>- </div>- <label class="relative inline-flex items-center cursor-pointer">- <input type="checkbox" id="config-simulate-typing" class="sr-only peer">- <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>- </label>- </div>- <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">- <div>- <h4 class="font-medium text-gray-900">Randomize Delays</h4>- <p class="text-sm text-gray-500">Add random variance to avoid patterns</p>- </div>- <label class="relative inline-flex items-center cursor-pointer">- <input type="checkbox" id="config-randomize" class="sr-only peer">- <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>- </label>- </div>- </div>- </div>-- <!-- Safety Section -->- <div class="border-t pt-6">- <h3 class="text-md font-medium text-gray-900 mb-4">Safety Settings</h3>- <div class="grid grid-cols-1 md:grid-cols-2 gap-6">- <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">- <div>- <h4 class="font-medium text-gray-900">Pause on Low Response</h4>- <p class="text-sm text-gray-500">Auto-pause if response rate drops too low</p>- </div>- <label class="relative inline-flex items-center cursor-pointer">- <input type="checkbox" id="config-pause-low-response" class="sr-only peer">- <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>- </label>- </div>- <div>- <label class="block text-sm font-medium text-gray-700 mb-1">Response Rate Threshold</label>- <div class="flex items-center">- <input type="number" id="config-response-threshold" class="w-24 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" max="100" step="5">- <span class="ml-2 text-gray-500">%</span>- </div>- <p class="text-xs text-gray-500 mt-1">Minimum acceptable response rate (default: 30%)</p>- </div>- </div>- </div>-- <!-- Actions -->- <div class="border-t pt-6 flex justify-between items-center">- <button type="button" id="reset-defaults" class="text-gray-600 hover:text-gray-800">- Reset to Defaults- </button>- <div class="flex gap-4">- <button type="button" id="cancel-changes" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">- Cancel- </button>- <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700">- Save Configuration- </button>- </div>- </div>- </form>- </div>-- <!-- Info Cards -->- <div class="grid grid-cols-1 md:grid-cols-2 gap-6">- <!-- Tips Card -->- <div class="bg-blue-50 border border-blue-200 rounded-lg p-6">- <h3 class="font-semibold text-blue-800 mb-3">Anti-Ban Tips</h3>- <ul class="text-sm text-blue-700 space-y-2">- <li>- First 10 days have highest ban risk for new numbers</li>- <li>- Keep new contacts under 20/day for new accounts</li>- <li>- Always enable typing simulation</li>- <li>- Use randomized delays to avoid patterns</li>- <li>- Messages with links need extra delay for preview generation</li>- <li>- Monitor response rate - low rates may indicate blocked messages</li>- </ul>- </div>-- <!-- Current Time Info -->- <div class="bg-gray-50 border border-gray-200 rounded-lg p-6">- <h3 class="font-semibold text-gray-800 mb-3">Timing Information</h3>- <div class="text-sm text-gray-600 space-y-2">- <p><strong>Last Message:</strong> <span id="info-last-message">-</span></p>- <p><strong>Next Allowed:</strong> <span id="info-next-allowed">-</span></p>- <p><strong>Messages Today:</strong> <span id="info-messages-today">-</span></p>- <p><strong>Responses Received:</strong> <span id="info-responses">-</span></p>- </div>- </div>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>-let currentConfig = {};-let currentStats = {};--document.addEventListener('DOMContentLoaded', function() {- // Load initial data- loadRateLimitData();-- // Event listeners- document.getElementById('refresh-stats').addEventListener('click', loadRateLimitData);- document.getElementById('config-form').addEventListener('submit', saveConfiguration);- document.getElementById('unpause-btn').addEventListener('click', unpauseRateLimiting);- document.getElementById('reset-defaults').addEventListener('click', resetToDefaults);- document.getElementById('cancel-changes').addEventListener('click', loadRateLimitData);-- // Auto-refresh every 10 seconds- setInterval(loadStats, 10000);-});--async function loadRateLimitData() {- try {- const response = await fetch('/api/rate-limit');- const result = await response.json();-- if (result.success) {- currentConfig = result.data.config;- currentStats = result.data.stats;- updateUI();- } else {- showAlert('Failed to load rate limit data: ' + result.error, 'error');- }- } catch (error) {- showAlert('Error loading rate limit data: ' + error.message, 'error');- }-}--async function loadStats() {- try {- const response = await fetch('/api/rate-limit/stats');- const result = await response.json();-- if (result.success) {- currentStats = result.data;- updateStats();- }- } catch (error) {- console.error('Error loading stats:', error);- }-}--function updateUI() {- updateStats();- updateConfigForm();-}--function updateStats() {- // Stats cards- document.getElementById('stat-messages-minute').textContent = currentStats.messages_sent_last_minute || 0;- document.getElementById('stat-messages-minute-limit').textContent = currentConfig.max_messages_per_minute ? ` / ${currentConfig.max_messages_per_minute}` : '';-- document.getElementById('stat-messages-hour').textContent = currentStats.messages_sent_last_hour || 0;- document.getElementById('stat-messages-hour-limit').textContent = currentConfig.max_messages_per_hour ? ` / ${currentConfig.max_messages_per_hour}` : '';-- document.getElementById('stat-new-contacts').textContent = currentStats.new_contacts_today || 0;- document.getElementById('stat-new-contacts-limit').textContent = currentConfig.max_new_contacts_per_day ? ` / ${currentConfig.max_new_contacts_per_day}` : '';-- document.getElementById('stat-response-rate').textContent = ((currentStats.response_rate || 0) * 100).toFixed(1);-- // Pause status- const pauseAlert = document.getElementById('pause-alert');- if (currentStats.is_paused) {- pauseAlert.classList.remove('hidden');- document.getElementById('pause-reason').textContent = currentStats.pause_reason || 'Unknown reason';- } else {- pauseAlert.classList.add('hidden');- }-- // Timing info- document.getElementById('info-last-message').textContent = currentStats.last_message_time ? formatTime(currentStats.last_message_time) : 'Never';- document.getElementById('info-next-allowed').textContent = currentStats.next_allowed_time ? formatTime(currentStats.next_allowed_time) : '-';- document.getElementById('info-messages-today').textContent = currentStats.messages_sent_today || 0;- document.getElementById('info-responses').textContent = currentStats.responses_received || 0;-}--function updateConfigForm() {- document.getElementById('config-enabled').checked = currentConfig.enabled !== false;- document.getElementById('config-min-delay').value = currentConfig.min_delay_ms || 3000;- document.getElementById('config-max-delay').value = currentConfig.max_delay_ms || 8000;- document.getElementById('config-typing-delay').value = currentConfig.typing_delay_ms || 2000;- document.getElementById('config-link-delay').value = currentConfig.link_extra_delay_ms || 5000;- document.getElementById('config-per-minute').value = currentConfig.max_messages_per_minute || 10;- document.getElementById('config-per-hour').value = currentConfig.max_messages_per_hour || 60;- document.getElementById('config-new-contacts').value = currentConfig.max_new_contacts_per_day || 20;- document.getElementById('config-simulate-typing').checked = currentConfig.simulate_typing !== false;- document.getElementById('config-randomize').checked = currentConfig.randomize_delays !== false;- document.getElementById('config-pause-low-response').checked = currentConfig.pause_on_low_response === true;- document.getElementById('config-response-threshold').value = (currentConfig.response_rate_threshold || 0.3) * 100;-}--async function saveConfiguration(e) {- e.preventDefault();-- const config = {- enabled: document.getElementById('config-enabled').checked,- min_delay_ms: parseInt(document.getElementById('config-min-delay').value) || 3000,- max_delay_ms: parseInt(document.getElementById('config-max-delay').value) || 8000,- typing_delay_ms: parseInt(document.getElementById('config-typing-delay').value) || 2000,- link_extra_delay_ms: parseInt(document.getElementById('config-link-delay').value) || 5000,- max_messages_per_minute: parseInt(document.getElementById('config-per-minute').value) || 0,- max_messages_per_hour: parseInt(document.getElementById('config-per-hour').value) || 0,- max_new_contacts_per_day: parseInt(document.getElementById('config-new-contacts').value) || 0,- simulate_typing: document.getElementById('config-simulate-typing').checked,- randomize_delays: document.getElementById('config-randomize').checked,- pause_on_low_response: document.getElementById('config-pause-low-response').checked,- response_rate_threshold: (parseInt(document.getElementById('config-response-threshold').value) || 30) / 100- };-- try {- const response = await fetch('/api/rate-limit', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(config)- });-- const result = await response.json();-- if (result.success) {- currentConfig = result.data.config;- showAlert('Configuration saved successfully', 'success');- updateUI();- } else {- showAlert('Failed to save configuration: ' + result.error, 'error');- }- } catch (error) {- showAlert('Error saving configuration: ' + error.message, 'error');- }-}--async function unpauseRateLimiting() {- try {- const response = await fetch('/api/rate-limit/unpause', { method: 'POST' });- const result = await response.json();-- if (result.success) {- currentStats = result.data.stats;- showAlert('Rate limiting unpaused', 'success');- updateStats();- } else {- showAlert('Failed to unpause: ' + result.error, 'error');- }- } catch (error) {- showAlert('Error unpausing: ' + error.message, 'error');- }-}--function resetToDefaults() {- document.getElementById('config-enabled').checked = true;- document.getElementById('config-min-delay').value = 3000;- document.getElementById('config-max-delay').value = 8000;- document.getElementById('config-typing-delay').value = 2000;- document.getElementById('config-link-delay').value = 5000;- document.getElementById('config-per-minute').value = 10;- document.getElementById('config-per-hour').value = 60;- document.getElementById('config-new-contacts').value = 20;- document.getElementById('config-simulate-typing').checked = true;- document.getElementById('config-randomize').checked = true;- document.getElementById('config-pause-low-response').checked = false;- document.getElementById('config-response-threshold').value = 30;-}--function formatTime(isoString) {- if (!isoString || isoString === '0001-01-01T00:00:00Z') return 'Never';- const date = new Date(isoString);- if (isNaN(date.getTime())) return '-';- return date.toLocaleTimeString();-}--function showAlert(message, type) {- const alertDiv = document.getElementById('status-alert');- const bgColor = type === 'success' ? 'bg-green-100 border-green-400 text-green-700' : 'bg-red-100 border-red-400 text-red-700';- alertDiv.className = `${bgColor} border px-4 py-3 rounded-lg mb-4`;- alertDiv.textContent = message;- alertDiv.classList.remove('hidden');-- setTimeout(() => {- alertDiv.classList.add('hidden');- }, 5000);-}-</script>-{% endblock %}