156 lines
3.9 KiB
TypeScript
156 lines
3.9 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { Client, LocalAuth } from 'whatsapp-web.js'
|
|
import * as fs from 'fs'
|
|
import * as path from 'path'
|
|
|
|
let client: Client | null = null
|
|
let qrCode: string | null = null
|
|
let status: 'disconnected' | 'loading' | 'qr' | 'ready' = 'disconnected'
|
|
let syncedContacts = 0
|
|
const MAX_CONTACTS = 5
|
|
|
|
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'
|
|
const clientDir = path.join(process.cwd(), '.wwebjs_auth_crm')
|
|
|
|
function isAuthenticated(): boolean {
|
|
const sessionDir = path.join(clientDir, 'session')
|
|
if (!fs.existsSync(sessionDir)) return false
|
|
const files = fs.readdirSync(sessionDir)
|
|
return files.length > 0
|
|
}
|
|
|
|
function killExistingBrowser(): void {
|
|
try {
|
|
const { execSync } = require('child_process')
|
|
execSync(`pkill -f "wwebjs"`, { stdio: 'ignore' })
|
|
execSync(`pkill -f "chromium"`, { stdio: 'ignore' })
|
|
} catch (e) {}
|
|
}
|
|
|
|
function startClient() {
|
|
if (client) return
|
|
|
|
killExistingBrowser()
|
|
|
|
if (!fs.existsSync(clientDir)) {
|
|
fs.mkdirSync(clientDir, { recursive: true })
|
|
}
|
|
|
|
status = 'loading'
|
|
qrCode = null
|
|
|
|
client = new Client({
|
|
authStrategy: new LocalAuth({ dataPath: clientDir }),
|
|
puppeteer: {
|
|
executablePath: '/usr/sbin/chromium',
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
|
|
}
|
|
})
|
|
|
|
client.on('qr', (qr) => {
|
|
status = 'qr'
|
|
qrCode = qr
|
|
console.log('QR Code received')
|
|
})
|
|
|
|
client.on('ready', async () => {
|
|
status = 'ready'
|
|
qrCode = null
|
|
console.log('WhatsApp client ready')
|
|
|
|
const chats = await client!.getChats()
|
|
syncedContacts = 0
|
|
const existingPhones = new Set<string>()
|
|
|
|
for (const chat of chats) {
|
|
if (chat.isGroup) continue
|
|
if (syncedContacts >= MAX_CONTACTS) break
|
|
|
|
const msgs = await chat.fetchMessages({ limit: 10 })
|
|
for (const msg of msgs) {
|
|
if (syncedContacts >= MAX_CONTACTS) break
|
|
if (!msg.body || !msg.body.trim()) continue
|
|
|
|
const phone = msg.from.split('@')[0]
|
|
if (existingPhones.has(phone)) continue
|
|
|
|
try {
|
|
const res = await fetch(`${apiUrl}/api/contacts`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ name: chat.name, phone })
|
|
})
|
|
if (res.ok) {
|
|
syncedContacts++
|
|
existingPhones.add(phone)
|
|
}
|
|
} catch (e) {}
|
|
}
|
|
}
|
|
console.log(`Synced ${syncedContacts} contacts`)
|
|
})
|
|
|
|
client.on('message', async (msg) => {
|
|
if (syncedContacts >= MAX_CONTACTS) return
|
|
|
|
const chat = await msg.getChat()
|
|
if (chat.isGroup) return
|
|
if (!msg.body || !msg.body.trim()) return
|
|
|
|
const phone = msg.from.split('@')[0]
|
|
try {
|
|
const res = await fetch(`${apiUrl}/api/contacts`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ name: chat.name, phone })
|
|
})
|
|
if (res.ok) syncedContacts++
|
|
} catch (e) {}
|
|
})
|
|
|
|
client.on('disconnected', () => {
|
|
status = 'disconnected'
|
|
client = null
|
|
})
|
|
|
|
client.initialize()
|
|
}
|
|
|
|
export async function GET() {
|
|
if (!client && isAuthenticated()) {
|
|
startClient()
|
|
await new Promise(resolve => setTimeout(resolve, 5000))
|
|
}
|
|
|
|
const currentStatus = client ? (status === 'loading' ? 'connecting' : status) : 'disconnected'
|
|
|
|
return NextResponse.json({
|
|
status: currentStatus,
|
|
qrCode,
|
|
syncedContacts,
|
|
isAuthenticated: isAuthenticated(),
|
|
clientReady: client !== null
|
|
})
|
|
}
|
|
|
|
export async function POST() {
|
|
if (!client) {
|
|
startClient()
|
|
}
|
|
return NextResponse.json({ success: true })
|
|
}
|
|
|
|
export async function DELETE() {
|
|
if (client) {
|
|
client.destroy()
|
|
client = null
|
|
}
|
|
if (fs.existsSync(clientDir)) {
|
|
fs.rmSync(clientDir, { recursive: true, force: true })
|
|
}
|
|
status = 'disconnected'
|
|
qrCode = null
|
|
syncedContacts = 0
|
|
return NextResponse.json({ success: true })
|
|
}
|