feat(ui): simple admin pages /ui for titles, sources, social, theme
- Append generated article metadata to data/article-index.jsonl for listing - HTML UI: /ui, /ui/sources, /ui/social, /ui/publishers, /ui/theme - Saves require ADMIN_TOKEN; optional Bearer for future API use - GET /api/ui/articles JSON; config/ui-theme.example.json for accents - README and .env.example document access control expectations Made-with: Cursor
This commit is contained in:
1 parent
77024a71d4
commit
8f2ad454e9
8 files changed
+569
-35
No files matched your search
@@ -33,6 +33,8 @@ SCRAPER_TIMEOUT_MS=12000
|
||||
HOST=0.0.0.0
|
||||
PORT=3200
|
||||
LOG_LEVEL=info
|
||||
# Optional: required to save changes from /ui (sources, social, theme). Use a long random value in production.
|
||||
ADMIN_TOKEN=
|
||||
# auto | manual
|
||||
MODE=manual
|
||||
# Cron for auto mode, e.g. "*/30 * * * *" (every 30 min)
|
||||
|
||||
@@ -5,4 +5,5 @@ logs/
|
||||
config/sites/*.json
|
||||
!config/sites/example.json
|
||||
config/social.json
|
||||
data/
|
||||
.DS_Store
|
||||
@@ -43,8 +43,16 @@ Only when the app runs in **`listen`** mode (long-running service behind NPM):
|
||||
| `GET /` | Read-only **ops** landing page (version, uptime, RSS/X/WP flags — no secrets) |
|
||||
| `GET /dashboard` | Same as `/` |
|
||||
| `GET /health` | JSON for load balancers and monitoring |
|
||||
| `GET /ui` | Simple **admin UI**: table of generated article titles (from `data/article-index.jsonl`), nav to sources / social / publishers / theme |
|
||||
| `GET /ui/sources` | View or edit `config/sources.json` (needs `ADMIN_TOKEN` to save) |
|
||||
| `GET /ui/social` | View or edit `config/social.json` (X queries only; bearer stays in `.env`) |
|
||||
| `GET /ui/publishers` | Read-only WordPress targets (no passwords shown) |
|
||||
| `GET /ui/theme` | View or edit `config/ui-theme.json` (title + accent colour) |
|
||||
| `GET /api/ui/articles?limit=50` | JSON list of logged articles (titles/metadata; restrict NPM access if sensitive) |
|
||||
|
||||
There is **no** editorial dashboard yet (approve / reject / edit articles in the browser). That remains optional per BIT-353; today you use the CLI (`npm run write`), logs, and WordPress for review. After deploy, open e.g. `https://ainews.bitreport.pt/` once NPM points at the LXC.
|
||||
Set **`ADMIN_TOKEN`** in `.env` to enable saving from the browser forms. Without it, pages are read-only. Protect `/ui` at the reverse proxy (VPN, SSO, IP allowlist) in production — this is a functional stopgap, not a hardened CMS.
|
||||
|
||||
There is **no** full editorial workflow yet (approve / reject / rich edit). That remains optional per BIT-353; combine `/ui` with CLI (`npm run write`), logs, and WordPress as needed.
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"app_title": "AI News Writer",
|
||||
"accent_hex": "#1d4ed8"
|
||||
}
|
||||
+51
-34
@@ -5,6 +5,7 @@ const path = require('path');
|
||||
const logger = require('../logger');
|
||||
const { loadSources, loadSocialConfig, loadSiteConfigs, loadDefaultSiteConfig } = require('../config/loader');
|
||||
const { isRssListenerActive } = require('../runtime/listen-state');
|
||||
const { tryHandleAdminUi } = require('./ui-handlers');
|
||||
|
||||
const PACKAGE_JSON = require(path.join(__dirname, '..', '..', 'package.json'));
|
||||
|
||||
@@ -127,8 +128,8 @@ function buildLandingHtml() {
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>UI editorial (dashboard)</h2>
|
||||
<p style="margin:0">Ainda <strong>não</strong> existe o painel do issue (aprovar / rejeitar / editar artigos). O serviço corre em CLI (<code>write</code>) e modo automático (<code>listen</code>). O dashboard está na roadmap (opcional em BIT-353).</p>
|
||||
<h2>UI simples (admin)</h2>
|
||||
<p style="margin:0">Listagem de títulos gerados, edição de <code>sources.json</code>, queries X, tema e vista só de leitura dos publishers: <a href="/ui"><strong>/ui</strong></a>. Gravações exigem <code>ADMIN_TOKEN</code> no servidor.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
@@ -137,6 +138,8 @@ function buildLandingHtml() {
|
||||
<li><code>GET /</code> — esta página</li>
|
||||
<li><code>GET /dashboard</code> — igual a <code>/</code></li>
|
||||
<li><code>GET /health</code> — JSON de estado</li>
|
||||
<li><code>GET /ui</code> — painel simples</li>
|
||||
<li><code>GET /api/ui/articles</code> — JSON dos títulos registados</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -159,44 +162,58 @@ function startStatusServer() {
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = req.url || '/';
|
||||
if (
|
||||
(req.method === 'GET' || req.method === 'HEAD') &&
|
||||
(url === '/health' || url === '/health/')
|
||||
) {
|
||||
const body = JSON.stringify({
|
||||
ok: true,
|
||||
service: 'ai-news-writer',
|
||||
version: PACKAGE_JSON.version || '0.0.0',
|
||||
mode: 'listen',
|
||||
uptime_sec: Math.floor(process.uptime()),
|
||||
...getListenFeatureFlags(),
|
||||
});
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(body) });
|
||||
if (req.method === 'HEAD') {
|
||||
res.end();
|
||||
return;
|
||||
void (async () => {
|
||||
try {
|
||||
if (await tryHandleAdminUi(req, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const url = req.url || '/';
|
||||
if (
|
||||
(req.method === 'GET' || req.method === 'HEAD') &&
|
||||
(url === '/health' || url === '/health/')
|
||||
) {
|
||||
const body = JSON.stringify({
|
||||
ok: true,
|
||||
service: 'ai-news-writer',
|
||||
version: PACKAGE_JSON.version || '0.0.0',
|
||||
mode: 'listen',
|
||||
uptime_sec: Math.floor(process.uptime()),
|
||||
...getListenFeatureFlags(),
|
||||
});
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(body) });
|
||||
if (req.method === 'HEAD') {
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
res.end(body);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
req.method === 'GET' &&
|
||||
(url === '/' || url === '/index.html' || url === '/dashboard' || url === '/dashboard/')
|
||||
) {
|
||||
const html = buildLandingHtml();
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return;
|
||||
}
|
||||
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
||||
res.end('Not found');
|
||||
} catch (err) {
|
||||
logger.error(`HTTP handler error: ${err.message}`, { stack: err.stack });
|
||||
if (!res.writableEnded) {
|
||||
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
||||
res.end('Internal error');
|
||||
}
|
||||
}
|
||||
res.end(body);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
req.method === 'GET' &&
|
||||
(url === '/' || url === '/index.html' || url === '/dashboard' || url === '/dashboard/')
|
||||
) {
|
||||
const html = buildLandingHtml();
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return;
|
||||
}
|
||||
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
||||
res.end('Not found');
|
||||
})();
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(port, host, () => {
|
||||
logger.info(`HTTP status server listening on http://${host}:${port} (GET /, /dashboard, /health)`);
|
||||
logger.info(`HTTP listening on http://${host}:${port} (/, /ui, /dashboard, /health)`);
|
||||
resolve({
|
||||
server,
|
||||
close: () =>
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const logger = require('../logger');
|
||||
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('../config/loader');
|
||||
const { readLastArticles } = require('../store/article-log');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..', '..');
|
||||
const SOURCES_PATH = path.join(ROOT, 'config', 'sources.json');
|
||||
const THEME_PATH = path.join(ROOT, 'config', 'ui-theme.json');
|
||||
const SOCIAL_PATH = path.join(ROOT, 'config', 'social.json');
|
||||
const MAX_BODY = 2 * 1024 * 1024;
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function getAdminToken() {
|
||||
return (process.env.ADMIN_TOKEN || '').trim();
|
||||
}
|
||||
|
||||
function tokenFromRequest(req) {
|
||||
const auth = req.headers.authorization || '';
|
||||
const m = /^Bearer\s+(.+)$/i.exec(auth);
|
||||
if (m) {
|
||||
return m[1].trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function adminOk(req, bodyToken) {
|
||||
const expected = getAdminToken();
|
||||
if (!expected) {
|
||||
return false;
|
||||
}
|
||||
const got = bodyToken || tokenFromRequest(req);
|
||||
return got === expected;
|
||||
}
|
||||
|
||||
function collectBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let size = 0;
|
||||
const chunks = [];
|
||||
req.on('data', (c) => {
|
||||
size += c.length;
|
||||
if (size > MAX_BODY) {
|
||||
reject(new Error('Payload too large'));
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function loadUiTheme() {
|
||||
try {
|
||||
if (fs.existsSync(THEME_PATH)) {
|
||||
const t = JSON.parse(fs.readFileSync(THEME_PATH, 'utf8'));
|
||||
const accent = (t.accent_hex || '').trim();
|
||||
return {
|
||||
app_title: typeof t.app_title === 'string' ? t.app_title.slice(0, 120) : 'AI News Writer',
|
||||
accent_hex: /^#[0-9a-fA-F]{6}$/.test(accent) ? accent : '#1d4ed8',
|
||||
};
|
||||
}
|
||||
} catch (_err) {
|
||||
/* fall through */
|
||||
}
|
||||
return { app_title: 'AI News Writer', accent_hex: '#1d4ed8' };
|
||||
}
|
||||
|
||||
function validateSourcesPayload(obj) {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
throw new Error('JSON inválido: raiz tem de ser um objeto');
|
||||
}
|
||||
if (!Array.isArray(obj.rss)) {
|
||||
throw new Error('O campo rss tem de ser um array');
|
||||
}
|
||||
for (const r of obj.rss) {
|
||||
if (!r || typeof r !== 'object') {
|
||||
throw new Error('Entrada rss inválida');
|
||||
}
|
||||
if (typeof r.name !== 'string' || !r.name.trim()) {
|
||||
throw new Error('Cada feed precisa de name');
|
||||
}
|
||||
if (typeof r.url !== 'string' || !/^https?:\/\//i.test(r.url.trim())) {
|
||||
throw new Error(`URL inválida para o feed "${r.name}"`);
|
||||
}
|
||||
}
|
||||
if (obj.keywords != null && !Array.isArray(obj.keywords)) {
|
||||
throw new Error('keywords tem de ser um array de strings');
|
||||
}
|
||||
if (obj.trusted_domains != null && !Array.isArray(obj.trusted_domains)) {
|
||||
throw new Error('trusted_domains tem de ser um array');
|
||||
}
|
||||
}
|
||||
|
||||
function validateSocialPayload(obj) {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
throw new Error('JSON inválido');
|
||||
}
|
||||
const x = obj.x;
|
||||
if (!x || typeof x !== 'object') {
|
||||
throw new Error('Falta o objeto x');
|
||||
}
|
||||
if (!Array.isArray(x.queries)) {
|
||||
throw new Error('x.queries tem de ser um array');
|
||||
}
|
||||
for (const q of x.queries) {
|
||||
if (typeof q !== 'string') {
|
||||
throw new Error('Cada query tem de ser texto');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function layout(title, innerHtml, theme) {
|
||||
const accent = escapeHtml(theme.accent_hex || '#1d4ed8');
|
||||
const appTitle = escapeHtml(theme.app_title || 'AI News Writer');
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="pt">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${escapeHtml(title)} — ${appTitle}</title>
|
||||
<style>
|
||||
:root { --accent: ${accent}; --fg: #111; --muted: #555; --bd: #ddd; --bg: #f8fafc; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root { --fg: #eee; --muted: #aaa; --bd: #444; --bg: #0f1419; }
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: system-ui, sans-serif; margin: 0; color: var(--fg); background: var(--bg); line-height: 1.45; }
|
||||
header { background: var(--accent); color: #fff; padding: 0.75rem 1rem; }
|
||||
header a { color: #fff; text-decoration: none; margin-right: 1rem; font-weight: 600; }
|
||||
header nav a { font-weight: 400; opacity: 0.95; }
|
||||
main { max-width: 52rem; margin: 0 auto; padding: 1rem 1rem 2rem; }
|
||||
h1 { font-size: 1.25rem; margin: 0 0 1rem; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
|
||||
th, td { border: 1px solid var(--bd); padding: 0.45rem 0.5rem; text-align: left; vertical-align: top; }
|
||||
th { background: rgba(127,127,127,0.12); }
|
||||
textarea { width: 100%; min-height: 18rem; font-family: ui-monospace, monospace; font-size: 0.8rem; padding: 0.5rem; }
|
||||
.btn { display: inline-block; background: var(--accent); color: #fff; border: 0; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.95rem; }
|
||||
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.note { color: var(--muted); font-size: 0.9rem; margin: 0.5rem 0 1rem; }
|
||||
.err { color: #b91c1c; margin: 0.5rem 0; }
|
||||
.ok { color: #15803d; margin: 0.5rem 0; }
|
||||
label { display: block; margin: 0.75rem 0 0.25rem; font-size: 0.9rem; }
|
||||
input[type="password"], input[type="text"] { width: 100%; max-width: 24rem; padding: 0.4rem 0.5rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<a href="/ui">${appTitle}</a>
|
||||
<nav>
|
||||
<a href="/ui">Artigos</a>
|
||||
<a href="/ui/sources">Fontes & keywords</a>
|
||||
<a href="/ui/social">X / social</a>
|
||||
<a href="/ui/publishers">Publishers</a>
|
||||
<a href="/ui/theme">Tema</a>
|
||||
<a href="/">Ops</a>
|
||||
<a href="/health">Health</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
${innerHtml}
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
function pageDashboard(theme) {
|
||||
const articles = readLastArticles(80);
|
||||
let rows = articles
|
||||
.map(
|
||||
(a) =>
|
||||
`<tr><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${
|
||||
a.wp_link
|
||||
? `<a href="${escapeHtml(a.wp_link)}" rel="noopener">WP</a>`
|
||||
: '—'
|
||||
}</td></tr>`
|
||||
)
|
||||
.join('');
|
||||
if (!rows) {
|
||||
rows = '<tr><td colspan="4">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
}
|
||||
const inner = `<h1>Artigos gerados</h1>
|
||||
<p class="note">Listagem simples dos títulos guardados em <code>data/article-index.jsonl</code> (últimos 80).</p>
|
||||
<table><thead><tr><th>Data</th><th>Título</th><th>Site</th><th>WP</th></tr></thead><tbody>${rows}</tbody></table>`;
|
||||
return layout('Artigos', inner, theme);
|
||||
}
|
||||
|
||||
function pageSources(theme, msg) {
|
||||
const src = loadSources();
|
||||
const json = JSON.stringify(src, null, 2);
|
||||
const tokenSet = !!getAdminToken();
|
||||
const inner = `<h1>Fontes RSS & keywords</h1>
|
||||
<p class="note">Ficheiro <code>config/sources.json</code>. ${tokenSet ? 'Preencha o token de admin para gravar.' : '<strong>ADMIN_TOKEN</strong> não está definido no ambiente — só leitura.'}</p>
|
||||
${msg ? `<p class="${msg.type === 'err' ? 'err' : 'ok'}">${escapeHtml(msg.text)}</p>` : ''}
|
||||
<form method="post" action="/ui/sources">
|
||||
<label for="sources_json">JSON</label>
|
||||
<textarea id="sources_json" name="sources_json" ${tokenSet ? '' : 'readonly'}>${escapeHtml(json)}</textarea>
|
||||
<label for="admin_token">Token admin</label>
|
||||
<input type="password" id="admin_token" name="admin_token" autocomplete="off" placeholder="ADMIN_TOKEN" ${tokenSet ? '' : 'disabled'} />
|
||||
<p><button type="submit" class="btn" ${tokenSet ? '' : 'disabled'}>Guardar</button></p>
|
||||
</form>`;
|
||||
return layout('Fontes', inner, theme);
|
||||
}
|
||||
|
||||
function pageSocial(theme, msg) {
|
||||
const social = loadSocialConfig();
|
||||
const payload = { x: { queries: social?.x?.queries || [], max_results_per_query: social?.x?.max_results_per_query || 10 } };
|
||||
const json = JSON.stringify(payload, null, 2);
|
||||
const tokenSet = !!getAdminToken();
|
||||
const inner = `<h1>X (Twitter) — queries</h1>
|
||||
<p class="note">Grava <code>config/social.json</code>. O bearer continua em <code>TWITTER_BEARER_TOKEN</code> no <code>.env</code>.</p>
|
||||
${msg ? `<p class="${msg.type === 'err' ? 'err' : 'ok'}">${escapeHtml(msg.text)}</p>` : ''}
|
||||
<form method="post" action="/ui/social">
|
||||
<textarea name="social_json" ${tokenSet ? '' : 'readonly'}>${escapeHtml(json)}</textarea>
|
||||
<label for="admin_token_s">Token admin</label>
|
||||
<input type="password" name="admin_token" id="admin_token_s" ${tokenSet ? '' : 'disabled'} />
|
||||
<p><button type="submit" class="btn" ${tokenSet ? '' : 'disabled'}>Guardar</button></p>
|
||||
</form>`;
|
||||
return layout('Social', inner, theme);
|
||||
}
|
||||
|
||||
function pagePublishers(theme) {
|
||||
const sites = loadSiteConfigs();
|
||||
const fallback = loadDefaultSiteConfig();
|
||||
const rows = [];
|
||||
if (sites.length === 0) {
|
||||
if (fallback.wp_url) {
|
||||
rows.push(
|
||||
`<tr><td>env default</td><td>${escapeHtml(fallback.wp_url)}</td><td>${escapeHtml(fallback.user || '—')}</td><td>${fallback.password ? '***' : '—'}</td></tr>`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for (const s of sites) {
|
||||
rows.push(
|
||||
`<tr><td>${escapeHtml(s.name || '—')}</td><td>${escapeHtml(s.wp_url || '')}</td><td>${escapeHtml(s.user || '—')}</td><td>${s.password ? '***' : '—'}</td></tr>`
|
||||
);
|
||||
}
|
||||
}
|
||||
const inner = `<h1>Publishers (WordPress)</h1>
|
||||
<p class="note">Somente leitura na UI. Credenciais em <code>config/sites/*.json</code> (não versionados) ou variáveis <code>WP_*</code> no servidor.</p>
|
||||
<table><thead><tr><th>Nome</th><th>URL</th><th>Utilizador</th><th>Password</th></tr></thead><tbody>${
|
||||
rows.length ? rows.join('') : '<tr><td colspan="4">Nenhum site configurado.</td></tr>'
|
||||
}</tbody></table>`;
|
||||
return layout('Publishers', inner, theme);
|
||||
}
|
||||
|
||||
function pageTheme(theme, msg) {
|
||||
const t = loadUiTheme();
|
||||
const json = JSON.stringify(t, null, 2);
|
||||
const tokenSet = !!getAdminToken();
|
||||
const inner = `<h1>Tema da UI</h1>
|
||||
<p class="note">Ficheiro <code>config/ui-theme.json</code> (título da barra, cor de destaque).</p>
|
||||
${msg ? `<p class="${msg.type === 'err' ? 'err' : 'ok'}">${escapeHtml(msg.text)}</p>` : ''}
|
||||
<form method="post" action="/ui/theme">
|
||||
<textarea name="theme_json" ${tokenSet ? '' : 'readonly'}>${escapeHtml(json)}</textarea>
|
||||
<label for="admin_token_t">Token admin</label>
|
||||
<input type="password" name="admin_token" id="admin_token_t" ${tokenSet ? '' : 'disabled'} />
|
||||
<p><button type="submit" class="btn" ${tokenSet ? '' : 'disabled'}>Guardar</button></p>
|
||||
</form>`;
|
||||
return layout('Tema', inner, theme);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<boolean>} true if handled
|
||||
*/
|
||||
async function tryHandleAdminUi(req, res) {
|
||||
const u = new URL(req.url || '/', 'http://127.0.0.1');
|
||||
let pathname = u.pathname;
|
||||
if (pathname.length > 1 && pathname.endsWith('/')) {
|
||||
pathname = pathname.slice(0, -1);
|
||||
}
|
||||
|
||||
const theme = loadUiTheme();
|
||||
|
||||
if (req.method === 'GET' && pathname === '/ui') {
|
||||
const html = pageDashboard(theme);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && pathname === '/ui/sources') {
|
||||
const html = pageSources(theme, null);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && pathname === '/ui/social') {
|
||||
const html = pageSocial(theme, null);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && pathname === '/ui/publishers') {
|
||||
const html = pagePublishers(theme);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && pathname === '/ui/theme') {
|
||||
const html = pageTheme(theme, null);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && pathname === '/api/ui/articles') {
|
||||
const limit = Math.min(200, Math.max(1, parseInt(u.searchParams.get('limit') || '50', 10) || 50));
|
||||
const body = JSON.stringify({ ok: true, articles: readLastArticles(limit) });
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(body) });
|
||||
res.end(body);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/ui/sources') {
|
||||
let msg = null;
|
||||
try {
|
||||
const raw = await collectBody(req);
|
||||
const params = new URLSearchParams(raw.toString('utf8'));
|
||||
const token = params.get('admin_token') || '';
|
||||
if (!adminOk(req, token)) {
|
||||
msg = { type: 'err', text: 'Token inválido ou ADMIN_TOKEN não configurado no servidor.' };
|
||||
} else {
|
||||
const text = params.get('sources_json') || '';
|
||||
const obj = JSON.parse(text);
|
||||
validateSourcesPayload(obj);
|
||||
fs.writeFileSync(SOURCES_PATH, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
|
||||
logger.info('UI: config/sources.json updated via /ui/sources');
|
||||
msg = { type: 'ok', text: 'Guardado. Reinicie o listener se necessário para aplicar feeds.' };
|
||||
}
|
||||
} catch (err) {
|
||||
msg = { type: 'err', text: err.message || String(err) };
|
||||
}
|
||||
const html = pageSources(loadUiTheme(), msg);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/ui/social') {
|
||||
let msg = null;
|
||||
try {
|
||||
const raw = await collectBody(req);
|
||||
const params = new URLSearchParams(raw.toString('utf8'));
|
||||
const token = params.get('admin_token') || '';
|
||||
if (!adminOk(req, token)) {
|
||||
msg = { type: 'err', text: 'Token inválido ou ADMIN_TOKEN não configurado.' };
|
||||
} else {
|
||||
const text = params.get('social_json') || '';
|
||||
const obj = JSON.parse(text);
|
||||
validateSocialPayload(obj);
|
||||
fs.writeFileSync(SOCIAL_PATH, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
|
||||
logger.info('UI: config/social.json updated via /ui/social');
|
||||
msg = { type: 'ok', text: 'Guardado.' };
|
||||
}
|
||||
} catch (err) {
|
||||
msg = { type: 'err', text: err.message || String(err) };
|
||||
}
|
||||
const html = pageSocial(loadUiTheme(), msg);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/ui/theme') {
|
||||
let msg = null;
|
||||
try {
|
||||
const raw = await collectBody(req);
|
||||
const params = new URLSearchParams(raw.toString('utf8'));
|
||||
const token = params.get('admin_token') || '';
|
||||
if (!adminOk(req, token)) {
|
||||
msg = { type: 'err', text: 'Token inválido ou ADMIN_TOKEN não configurado.' };
|
||||
} else {
|
||||
const text = params.get('theme_json') || '';
|
||||
const obj = JSON.parse(text);
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
throw new Error('JSON inválido');
|
||||
}
|
||||
if (typeof obj.app_title !== 'string' || !obj.app_title.trim()) {
|
||||
throw new Error('app_title obrigatório');
|
||||
}
|
||||
if (typeof obj.accent_hex !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(obj.accent_hex.trim())) {
|
||||
throw new Error('accent_hex tem de ser #RRGGBB');
|
||||
}
|
||||
fs.writeFileSync(THEME_PATH, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
|
||||
logger.info('UI: config/ui-theme.json updated');
|
||||
msg = { type: 'ok', text: 'Guardado.' };
|
||||
}
|
||||
} catch (err) {
|
||||
msg = { type: 'err', text: err.message || String(err) };
|
||||
}
|
||||
const html = pageTheme(loadUiTheme(), msg);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) });
|
||||
res.end(html);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = { tryHandleAdminUi };
|
||||
@@ -13,12 +13,29 @@ const { startStatusServer } = require('./http/status-server');
|
||||
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('./config/loader');
|
||||
const { probeXQueries } = require('./crawler/x');
|
||||
const { setRssListenerActive } = require('./runtime/listen-state');
|
||||
const { appendArticleRecord } = require('./store/article-log');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const LOGS_DIR = path.join(__dirname, '..', 'logs');
|
||||
if (!fs.existsSync(LOGS_DIR)) fs.mkdirSync(LOGS_DIR, { recursive: true });
|
||||
|
||||
function safeAppendArticle(article, site, mode, wp_link) {
|
||||
try {
|
||||
appendArticleRecord({
|
||||
title: article.title,
|
||||
subtitle: article.subtitle,
|
||||
slug: article.slug,
|
||||
summary: article.summary,
|
||||
wp_link: wp_link || null,
|
||||
site_name: site?.name || 'default',
|
||||
mode,
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn(`article log append failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runManualWrite(topic) {
|
||||
logger.info(`Manual write mode — topic: "${topic}"`);
|
||||
|
||||
@@ -68,14 +85,17 @@ async function runManualWrite(topic) {
|
||||
console.log(`SEO: ${article.seo_description}`);
|
||||
console.log(`\nBody:\n${article.body}`);
|
||||
|
||||
let wp_link = null;
|
||||
if (site.wp_url && site.user && site.password) {
|
||||
logger.info('Publishing to WordPress...');
|
||||
const wp_post = await publishToWordPress(article, site);
|
||||
wp_link = wp_post.link || null;
|
||||
logger.info(`Published: ${wp_post.link}`);
|
||||
} else {
|
||||
logger.warn('No WordPress config found — article not published (set WP_URL, WP_USER, WP_PASSWORD)');
|
||||
}
|
||||
|
||||
safeAppendArticle(article, site, 'write', wp_link);
|
||||
return article;
|
||||
}
|
||||
|
||||
@@ -205,12 +225,15 @@ async function runAutoMode() {
|
||||
|
||||
logger.info(`Auto article generated: "${article.title}"`);
|
||||
|
||||
let wp_link = null;
|
||||
if (site.wp_url && site.user && site.password) {
|
||||
const wp_post = await publishToWordPress(article, site);
|
||||
wp_link = wp_post.link || null;
|
||||
logger.info(`Auto published: ${wp_post.link || wp_post.id}`);
|
||||
} else {
|
||||
logger.warn('No WP config — article saved to logs only');
|
||||
}
|
||||
safeAppendArticle(article, site, 'listen', wp_link);
|
||||
});
|
||||
setRssListenerActive(true);
|
||||
} catch (err) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..', '..');
|
||||
const DATA_DIR = path.join(ROOT, 'data');
|
||||
const LOG_FILE = path.join(DATA_DIR, 'article-index.jsonl');
|
||||
|
||||
function ensureDataDir() {
|
||||
if (!fs.existsSync(DATA_DIR)) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append one generated article metadata line (JSONL). No secrets.
|
||||
*
|
||||
* @param {Object} rec
|
||||
* @param {string} rec.title
|
||||
* @param {string} [rec.subtitle]
|
||||
* @param {string} [rec.slug]
|
||||
* @param {string} [rec.summary]
|
||||
* @param {string} [rec.wp_link]
|
||||
* @param {string} [rec.site_name]
|
||||
* @param {string} [rec.mode] write | listen
|
||||
*/
|
||||
function appendArticleRecord(rec) {
|
||||
ensureDataDir();
|
||||
const line = JSON.stringify({
|
||||
at: new Date().toISOString(),
|
||||
title: rec.title || '',
|
||||
subtitle: rec.subtitle || '',
|
||||
slug: rec.slug || '',
|
||||
summary: (rec.summary || '').slice(0, 500),
|
||||
wp_link: rec.wp_link || null,
|
||||
site_name: rec.site_name || null,
|
||||
mode: rec.mode || 'unknown',
|
||||
});
|
||||
fs.appendFileSync(LOG_FILE, `${line}\n`, 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} limit
|
||||
* @returns {object[]} newest first
|
||||
*/
|
||||
function readLastArticles(limit = 100) {
|
||||
if (!fs.existsSync(LOG_FILE)) {
|
||||
return [];
|
||||
}
|
||||
const raw = fs.readFileSync(LOG_FILE, 'utf8');
|
||||
const lines = raw.split('\n').filter((l) => l.trim().length > 0);
|
||||
const rows = [];
|
||||
for (const line of lines) {
|
||||
try {
|
||||
rows.push(JSON.parse(line));
|
||||
} catch (_err) {
|
||||
/* skip corrupt line */
|
||||
}
|
||||
}
|
||||
rows.reverse();
|
||||
return rows.slice(0, Math.max(1, Math.min(500, limit)));
|
||||
}
|
||||
|
||||
module.exports = { appendArticleRecord, readLastArticles, LOG_FILE };
|
||||
Reference in new issue
Block a user