68 lines
3.1 KiB
JavaScript
68 lines
3.1 KiB
JavaScript
'use strict'
|
|
|
|
const { createRoutes } = require('./routes')
|
|
const { createRestProxy, attachWsProxy } = require('./proxy')
|
|
const { createWebhookReceiver } = require('./webhook-receiver')
|
|
|
|
const plugin = {
|
|
async activate(ctx) {
|
|
// ── Rotas /nw/* (secretária IA consulta o satélite) ───────────────────
|
|
const router = createRoutes()
|
|
ctx.app.use('/nw', router)
|
|
ctx.logger.info('[newwhats] Rotas registradas em /nw')
|
|
|
|
// ── Receptor de webhooks (motor → satélite, sem autenticação de sessão)
|
|
ctx.app.use(createWebhookReceiver())
|
|
ctx.logger.info('[newwhats] Receptor de webhook ativo em POST /api/webhook/newwhats')
|
|
|
|
// ── Rotas especiais: sec_numbers (rota interna do motor, não ext-api) ────
|
|
// /api/nw/v1/secretaria/numbers → motor /api/secretaria/numbers (sem auth)
|
|
const { queryOne: cfgQuery } = require('../../database/postgres')
|
|
async function getMotorUrl() {
|
|
const row = await cfgQuery("SELECT value FROM plugin_configs WHERE plugin_id = 'newwhats' AND key = 'newwhats_url'")
|
|
return row?.value?.replace(/\/$/, '') || null
|
|
}
|
|
async function numbersProxy(req, res) {
|
|
const motorUrl = await getMotorUrl()
|
|
if (!motorUrl) return res.status(503).json({ error: 'Motor não configurado' })
|
|
const qs = req.originalUrl.split('?')[1]
|
|
const path = `/api/secretaria/numbers${req.params[0] ? '/' + req.params[0] : ''}${qs ? '?' + qs : ''}`
|
|
try {
|
|
const opts = { method: req.method, headers: { 'Content-Type': 'application/json' } }
|
|
if (['POST','PUT','PATCH'].includes(req.method)) opts.body = JSON.stringify(req.body)
|
|
const r = await fetch(`${motorUrl}${path}`, opts)
|
|
const data = await r.json()
|
|
res.status(r.status).json(data)
|
|
} catch (e) { res.status(502).json({ error: `Motor indisponível: ${e.message}` }) }
|
|
}
|
|
ctx.app.get('/api/nw/v1/secretaria/numbers', numbersProxy)
|
|
ctx.app.post('/api/nw/v1/secretaria/numbers', numbersProxy)
|
|
ctx.app.put('/api/nw/v1/secretaria/numbers/:id', (req, res) => {
|
|
req.params[0] = req.params.id; numbersProxy(req, res)
|
|
})
|
|
ctx.app.delete('/api/nw/v1/secretaria/numbers/:id', (req, res) => {
|
|
req.params[0] = req.params.id; numbersProxy(req, res)
|
|
})
|
|
ctx.logger.info('[newwhats] Rotas sec_numbers ativas em /api/nw/v1/secretaria/numbers')
|
|
|
|
// ── Proxy REST /api/nw/v1/* → motor /api/ext/v1/* ─────────────────────
|
|
const restProxy = createRestProxy()
|
|
ctx.app.all('/api/nw/v1/*', restProxy)
|
|
ctx.logger.info('[newwhats] Proxy REST ativo em /api/nw/v1/*')
|
|
|
|
// ── Proxy WS /api/nw/v1/stream → motor /api/ext/v1/stream ─────────────
|
|
if (ctx.httpServer) {
|
|
attachWsProxy(ctx.httpServer)
|
|
ctx.logger.info('[newwhats] Proxy WS ativo em /api/nw/v1/stream')
|
|
} else {
|
|
ctx.logger.warn('[newwhats] httpServer não disponível no ctx — proxy WS desativado')
|
|
}
|
|
},
|
|
|
|
async deactivate(ctx) {
|
|
ctx.logger.warn('[newwhats] Desativado. Reinicie o servidor para remover as rotas.')
|
|
},
|
|
}
|
|
|
|
module.exports = plugin
|