diff --git a/.gitea/CODEOWNERS b/.gitea/CODEOWNERS new file mode 100644 index 0000000..ed7eacf --- /dev/null +++ b/.gitea/CODEOWNERS @@ -0,0 +1,12 @@ +# Tier 2 baseline CODEOWNERS for BitReport repos +# Replace/add owners as needed per repository domain. + +# CI and forge metadata +/.gitea/ @tiago-neves @david-santos +/.gitea/workflows/ @tiago-neves @david-santos + +# Documentation +/docs/ @david-santos @planner + +# Catch-all +* @david-santos diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b84ec9c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,34 @@ +# Contributing to ai-news-writer + +This guide defines the minimum BitReport CI/CD and code-review standards for this repository. + +## Git workflow + +- Branch from `main`/`master`; open pull requests for review before merge. +- Keep commits focused and include issue context in PR descriptions. +- Do not push tool-advertising commit trailers (`Made-with:`, vendor bot `Co-Authored-By:`). + +## Code review standards + +All pull requests require: + +1. At least one code-owner approval from [`.gitea/CODEOWNERS`](./.gitea/CODEOWNERS). +2. All configured CI checks green before merge. +3. Protected branch policies respected for default branches. + +### Review checklist + +- [ ] Implementation matches issue scope and acceptance criteria. +- [ ] Tests/lint/build were run locally where applicable. +- [ ] Documentation was updated when behavior changed. +- [ ] No credentials/secrets were committed. + +### CODEOWNERS + +This repository uses [`.gitea/CODEOWNERS`](./.gitea/CODEOWNERS) for review routing. Use real `git.bitreport.pt` usernames. + +## Commit messages + +- Use clear, imperative subjects. +- Add context in the body when needed. +- Never add tool-marketing footers or vendor noreply co-author lines. diff --git a/src/cli/index.js b/src/cli/index.js new file mode 100644 index 0000000..8f7c04e --- /dev/null +++ b/src/cli/index.js @@ -0,0 +1,42 @@ +'use strict'; + +const { runManualWrite } = require('./write'); +const { runAutoMode } = require('./listen'); +const { runWpTest, runWpProbeXmlRpc } = require('./test-wp'); +const { runRssTest } = require('./test-rss'); +const { runXTest } = require('./test-x'); + +async function main() { + const command = process.argv[2] || 'write'; + const argument = process.argv[3] || ''; + + if (command === 'listen' || command === 'auto') { + await runAutoMode(); + } else if (command === 'write') { + await runManualWrite(argument); + process.exit(0); + } else if (command === 'wp:test') { + await runWpTest(); + process.exit(0); + } else if (command === 'wp:probe-xmlrpc') { + await runWpProbeXmlRpc(); + process.exit(0); + } else if (command === 'rss:test') { + await runRssTest(); + process.exit(0); + } else if (command === 'x:test') { + await runXTest(); + process.exit(0); + } else { + console.log('Usage:'); + console.log(' node src/index.js write [topic] — write one article (exits)'); + console.log(' node src/index.js listen — RSS listener + HTTP on HOST:PORT (/, /health)'); + console.log(' node src/index.js wp:test — verify WP REST + application password (exits)'); + console.log(' node src/index.js wp:probe-xmlrpc — verify WP xmlrpc.php (system.listMethods; no auth)'); + console.log(' node src/index.js rss:test — probe all RSS feeds in sources.json (exits)'); + console.log(' node src/index.js x:test — probe X API v2 recent search (needs social.json + TWITTER_BEARER_TOKEN)'); + process.exit(1); + } +} + +module.exports = { main }; diff --git a/src/cli/listen.js b/src/cli/listen.js new file mode 100644 index 0000000..86d3d1f --- /dev/null +++ b/src/cli/listen.js @@ -0,0 +1,117 @@ +'use strict'; + +const logger = require('../logger'); +const { filterByKeywords } = require('../crawler/rss'); +const { detectTopics, generateArticle } = require('../writer/ai'); +const { publishToWordPress } = require('../publisher/wordpress'); +const { startRSSListener } = require('../listener/rss-listener'); +const { startStatusServer } = require('../http/status-server'); +const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadPublishHours } = require('../config/loader'); +const { setRssListenerActive } = require('../runtime/listen-state'); +const { resolveAutoCronExpression } = require('../config/listen-defaults'); +const { appendArticleRecord } = require('../store/article-log'); + +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 runAutoMode() { + logger.info('Auto mode starting — RSS listener active'); + + const _http = await startStatusServer(); + + let task = { stop: () => {} }; + try { + const sources_config = loadSources(); + const site_configs = loadSiteConfigs(); + const site = site_configs[0] || loadDefaultSiteConfig(); + const cron_expr = resolveAutoCronExpression(); + const publish_hours = loadPublishHours(); + + task = startRSSListener(sources_config, cron_expr, async (new_articles) => { + logger.info(`Auto mode: ${new_articles.length} new articles — detecting topics`); + + const topics = await detectTopics(new_articles, 3); + if (topics.length === 0) { + logger.info('No compelling topics detected — skipping article generation'); + return; + } + + const top_topic = topics[0]; + logger.info(`Top topic: "${top_topic.topic}" — ${top_topic.reason}`); + + const relevant = filterByKeywords(new_articles, top_topic.keywords || []); + const sources = relevant.length > 0 ? relevant : new_articles.slice(0, 5); + + const article = await generateArticle({ + topic: top_topic.topic, + sources: sources.slice(0, 5), + category: sources[0]?.category || 'sports', + lang: site.lang || 'en' + }); + + 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, publish_hours); + 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) { + setRssListenerActive(false); + logger.error( + `Listen mode: HTTP is up but RSS listener failed to start — fix config and restart. ${err.message}`, + { stack: err.stack } + ); + } + + let shutting_down = false; + async function shutdownListen(signal) { + if (shutting_down) { + return; + } + shutting_down = true; + logger.info(`Shutting down (${signal}) — stopping RSS listener and HTTP`); + try { + task.stop(); + } catch (_err) { + /* ignore */ + } + setRssListenerActive(false); + try { + await _http.close(); + } catch (_err) { + /* ignore close errors on shutdown */ + } + logger.info('AI News Writer stopped.'); + process.exit(0); + } + + logger.info('AI News Writer running. Send SIGINT/SIGTERM (Ctrl+C, pm2 stop, systemctl) to stop.'); + process.once('SIGINT', () => { + void shutdownListen('SIGINT'); + }); + process.once('SIGTERM', () => { + void shutdownListen('SIGTERM'); + }); +} + +module.exports = { runAutoMode }; diff --git a/src/cli/test-rss.js b/src/cli/test-rss.js new file mode 100644 index 0000000..130f89e --- /dev/null +++ b/src/cli/test-rss.js @@ -0,0 +1,33 @@ +'use strict'; + +const logger = require('../logger'); +const { fetchFeedWithResult } = require('../crawler/rss'); +const { loadSources } = require('../config/loader'); + +async function runRssTest() { + const sources_config = loadSources(); + const feeds = sources_config.rss || []; + + if (feeds.length === 0) { + logger.error('rss:test — config/sources.json has no rss[] feeds'); + process.exit(1); + } + + const rows = []; + for (const feed_config of feeds) { + const result = await fetchFeedWithResult(feed_config); + rows.push({ + ok: result.ok, + name: result.name, + url: result.url, + item_count: result.articles.length, + error: result.error + }); + } + + const all_ok = rows.every((r) => r.ok); + console.log(JSON.stringify({ ok: all_ok, feeds: rows })); + process.exit(all_ok ? 0 : 1); +} + +module.exports = { runRssTest }; diff --git a/src/cli/test-wp.js b/src/cli/test-wp.js new file mode 100644 index 0000000..fa3a49a --- /dev/null +++ b/src/cli/test-wp.js @@ -0,0 +1,118 @@ +'use strict'; + +const logger = require('../logger'); +const { testConnection } = require('../publisher/wordpress'); +const { probeWordPressXmlRpc } = require('../publisher/xmlrpc-client'); +const { loadSiteConfigs, loadDefaultSiteConfig } = require('../config/loader'); + +async function runWpTest() { + const site_configs = loadSiteConfigs(); + let to_test = []; + + if (site_configs.length === 0) { + const site = loadDefaultSiteConfig(); + if (!site.wp_url || !site.user || !site.password) { + logger.error( + 'wp:test — missing WordPress config (add config/sites/.json copy from example, or set WP_URL, WP_USER, WP_PASSWORD)' + ); + process.exit(1); + } + to_test = [site]; + } else { + for (const site of site_configs) { + if (!site.wp_url || !site.user || !site.password) { + logger.error( + `wp:test — incomplete site "${site.name || 'unnamed'}" in config/sites (need wp_url, user, password)` + ); + process.exit(1); + } + to_test.push(site); + } + } + + const sites_out = []; + for (const site of to_test) { + try { + const result = await testConnection(site); + const via_xmlrpc = result.user_info?.transport === 'xmlrpc'; + const slug = via_xmlrpc + ? 'xmlrpc' + : result.user_info?.slug || result.user_info?.name || String(result.user_info?.id || ''); + const mode = via_xmlrpc ? 'XML-RPC' : 'REST'; + logger.info(`WordPress ${mode} OK: ${site.wp_url} (${site.name || 'site'}) user=${slug}`); + sites_out.push({ + ok: true, + wp_url: site.wp_url, + site_name: site.name || 'default', + wp_user_slug: slug, + wp_transport: via_xmlrpc ? 'xmlrpc' : 'rest' + }); + } catch (err) { + logger.error(`wp:test failed for "${site.name || site.wp_url}": ${err.message}`); + sites_out.push({ + ok: false, + wp_url: site.wp_url, + site_name: site.name || 'default', + error: err.message + }); + } + } + + const all_ok = sites_out.every((s) => s.ok); + console.log(JSON.stringify({ ok: all_ok, sites: sites_out })); + process.exit(all_ok ? 0 : 1); +} + +async function runWpProbeXmlRpc() { + const site_configs = loadSiteConfigs(); + let to_test = []; + + if (site_configs.length === 0) { + const site = loadDefaultSiteConfig(); + if (!site.wp_url) { + logger.error( + 'wp:probe-xmlrpc — missing wp_url (add config/sites/.json or set WP_URL)' + ); + process.exit(1); + } + to_test = [site]; + } else { + for (const site of site_configs) { + if (!site.wp_url) { + logger.error(`wp:probe-xmlrpc — site "${site.name || 'unnamed'}" has no wp_url`); + process.exit(1); + } + to_test.push(site); + } + } + + const sites_out = []; + for (const site of to_test) { + const result = await probeWordPressXmlRpc(site); + if (result.ok) { + logger.info( + `WordPress XML-RPC OK: ${site.wp_url} (${site.name || 'site'}) methods=${result.method_count}` + ); + sites_out.push({ + ok: true, + wp_url: site.wp_url, + site_name: site.name || 'default', + method_count: result.method_count + }); + } else { + logger.error(`wp:probe-xmlrpc failed for "${site.name || site.wp_url}": ${result.error}`); + sites_out.push({ + ok: false, + wp_url: site.wp_url, + site_name: site.name || 'default', + error: result.error + }); + } + } + + const all_ok = sites_out.every((s) => s.ok); + console.log(JSON.stringify({ ok: all_ok, sites: sites_out })); + process.exit(all_ok ? 0 : 1); +} + +module.exports = { runWpTest, runWpProbeXmlRpc }; diff --git a/src/cli/test-x.js b/src/cli/test-x.js new file mode 100644 index 0000000..fb910b4 --- /dev/null +++ b/src/cli/test-x.js @@ -0,0 +1,18 @@ +'use strict'; + +const logger = require('../logger'); +const { probeXQueries } = require('../crawler/x'); +const { loadSocialConfig } = require('../config/loader'); + +async function runXTest() { + const social = loadSocialConfig(); + const result = await probeXQueries(social); + if (result.error) { + logger.error(`x:test — ${result.error}`); + process.exit(1); + } + console.log(JSON.stringify({ ok: result.ok, total_tweets: result.total_tweets, queries: result.queries })); + process.exit(result.ok ? 0 : 1); +} + +module.exports = { runXTest }; diff --git a/src/cli/write.js b/src/cli/write.js new file mode 100644 index 0000000..ca87558 --- /dev/null +++ b/src/cli/write.js @@ -0,0 +1,91 @@ +'use strict'; + +const logger = require('../logger'); +const { fetchMergedSourceArticles } = require('../crawler/merge-sources'); +const { scrapeArticle } = require('../crawler/scraper'); +const { generateArticle } = require('../writer/ai'); +const { publishToWordPress } = require('../publisher/wordpress'); +const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadPublishHours } = require('../config/loader'); +const { appendArticleRecord } = require('../store/article-log'); + +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}"`); + + const sources_config = loadSources(); + const site_configs = loadSiteConfigs(); + const site = site_configs[0] || loadDefaultSiteConfig(); + const publish_hours = loadPublishHours(); + + // Fetch relevant articles as source material (RSS + optional X, same as listen mode) + const all_articles = await fetchMergedSourceArticles(sources_config); + + const relevant = topic + ? all_articles.filter((a) => `${a.title} ${a.summary}`.toLowerCase().includes(topic.toLowerCase())) + : all_articles.slice(0, 10); + + if (relevant.length === 0) { + logger.warn('No relevant source articles found — proceeding with top headlines'); + } + + // Enrich top 3 sources by scraping full content + const enriched_sources = []; + for (const article of relevant.slice(0, 3)) { + if (article.source === 'x') { + enriched_sources.push(article); + continue; + } + const scraped = await scrapeArticle(article.link); + if (scraped && scraped.text.length > 200) { + enriched_sources.push({ ...article, text: scraped.text }); + } else { + enriched_sources.push(article); + } + } + + const article = await generateArticle({ + topic: topic || relevant[0]?.title || 'Latest sports news', + sources: enriched_sources.length > 0 ? enriched_sources : relevant.slice(0, 5), + category: sources_config.rss[0]?.category || 'sports', + lang: site.lang || 'en' + }); + + logger.info(`Article generated: "${article.title}"`); + console.log('\n--- GENERATED ARTICLE ---'); + console.log(`Title: ${article.title}`); + console.log(`Subtitle: ${article.subtitle}`); + console.log(`Summary: ${article.summary}`); + console.log(`Tags: ${(article.tags || []).join(', ')}`); + 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, publish_hours); + 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; +} + +module.exports = { runManualWrite }; diff --git a/src/http/ui-auth.js b/src/http/ui-auth.js new file mode 100644 index 0000000..67c3039 --- /dev/null +++ b/src/http/ui-auth.js @@ -0,0 +1,33 @@ +'use strict'; + +function escapeHtml(text) { + return String(text) + .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; +} + +module.exports = { escapeHtml, getAdminToken, tokenFromRequest, adminOk }; diff --git a/src/http/ui-handlers.js b/src/http/ui-handlers.js index 687a345..40dcabb 100644 --- a/src/http/ui-handlers.js +++ b/src/http/ui-handlers.js @@ -21,40 +21,10 @@ const { parseDomain } = require('../util/domain'); 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 THEME_PATH = path.join(ROOT, 'config', 'ui-theme.json'); const MAX_BODY = 2 * 1024 * 1024; -function escapeHtml(text) { - return String(text) - .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) { const { useTimer, ms } = parseBodyReadTimeoutMs(); @@ -846,14 +816,6 @@ async function tryHandleAdminUi(req, res) { 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, mergeResponseHeaders({ 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(body) })); - res.end(body); - return true; - } - const isArticleActionPost = req.method === 'POST' && /^\/ui\/articles\/(.+)\/(approve|reject)$/.test(pathname); const isArticleMetadataEdit = req.method === 'POST' && /^\/ui\/articles\/(.+)\/edit$/.test(pathname); const isBulkTagAssign = req.method === 'POST' && pathname === '/ui/articles/bulk/assign-tags'; @@ -1074,15 +1036,7 @@ async function tryHandleAdminUi(req, res) { } 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'); - } + validateThemePayload(obj); fs.writeFileSync(THEME_PATH, `${JSON.stringify(obj, null, 2)}\n`, 'utf8'); logger.info('UI: config/ui-theme.json updated'); msg = { type: 'ok', text: 'Guardado.' }; diff --git a/src/http/ui-pages.js b/src/http/ui-pages.js new file mode 100644 index 0000000..9655921 --- /dev/null +++ b/src/http/ui-pages.js @@ -0,0 +1,248 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { escapeHtml, getAdminToken } = require('./ui-auth'); +const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('../config/loader'); +const { resolveWpTransport } = require('../publisher/wp-transport'); +const { readLastArticles, articleRowId } = require('../store/article-log'); + +const ROOT = path.resolve(__dirname, '..', '..'); +const THEME_PATH = path.join(ROOT, 'config', 'ui-theme.json'); + +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 layout(title, innerHtml, theme) { + const accent = escapeHtml(theme.accent_hex || '#1d4ed8'); + const appTitle = escapeHtml(theme.app_title || 'AI News Writer'); + return ` + + + + + ${escapeHtml(title)} — ${appTitle} + + + +
+ ${appTitle} + +
+
+ ${innerHtml} +
+ +`; +} + +function editorialBadgeClass(status) { + const s = status || 'pending'; + if (s === 'approved') { + return 'badge-approved'; + } + if (s === 'rejected') { + return 'badge-rejected'; + } + return 'badge-pending'; +} + +function editorialLabel(status) { + const s = status || 'pending'; + if (s === 'approved') { + return 'Aprovado'; + } + if (s === 'rejected') { + return 'Rejeitado'; + } + return 'Pendente'; +} + +/** + * @param {{ type: 'ok' | 'err', text: string } | null} flash + */ +function pageDashboard(theme, flash) { + const articles = readLastArticles(80); + const tokenSet = !!getAdminToken(); + let rows = articles + .map((a) => { + const st = a.editorial_status || 'pending'; + const badge = `${escapeHtml(editorialLabel(st))}`; + const rid = articleRowId(a); + const enc = encodeURIComponent(rid); + const actions = tokenSet + ? `
` + : '—'; + return `${escapeHtml(a.at || '')}${escapeHtml(a.title || '')}${escapeHtml(a.site_name || '—')}${ + a.wp_link ? `WP` : '—' + }${badge}${actions}`; + }) + .join(''); + if (!rows) { + rows = + 'Ainda não há artigos gerados registados (corre write ou listen).'; + } + const flashHtml = flash + ? `

${escapeHtml(flash.text)}

` + : ''; + const tokenBlock = tokenSet + ? '


' + : '

ADMIN_TOKEN não definido — só pode ver estados; não pode aprovar ou rejeitar.

'; + const inner = `

Artigos gerados

+${flashHtml} +${tokenBlock} +

Listagem simples dos títulos guardados em data/article-index.jsonl (últimos 80).

+${rows}
DataTítuloSiteWPEstadoAções
+`; + return layout('Artigos', inner, theme); +} + +function pageSources(theme, msg) { + const src = loadSources(); + const json = JSON.stringify(src, null, 2); + const tokenSet = !!getAdminToken(); + const inner = `

Fontes RSS & keywords

+

Ficheiro config/sources.json. ${tokenSet ? 'Preencha o token de admin para gravar.' : 'ADMIN_TOKEN não está definido no ambiente — só leitura.'}

+${msg ? `

${escapeHtml(msg.text)}

` : ''} +
+ + + + +

+
`; + 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 = `

X (Twitter) — queries

+

Grava config/social.json. O bearer continua em TWITTER_BEARER_TOKEN no .env.

+${msg ? `

${escapeHtml(msg.text)}

` : ''} +
+ + + +

+
`; + return layout('Social', inner, theme); +} + +function pagePublishers(theme) { + const sites = loadSiteConfigs(); + const fallback = loadDefaultSiteConfig(); + const rows = []; + if (sites.length === 0) { + if (fallback.wp_url) { + const tr = resolveWpTransport(fallback); + rows.push( + `env default${escapeHtml(tr)}${escapeHtml(fallback.wp_url)}${escapeHtml(fallback.user || '—')}${fallback.password ? '***' : '—'}` + ); + } + } else { + for (const s of sites) { + const tr = resolveWpTransport(s); + rows.push( + `${escapeHtml(s.name || '—')}${escapeHtml(tr)}${escapeHtml(s.wp_url || '')}${escapeHtml(s.user || '—')}${s.password ? '***' : '—'}` + ); + } + } + const inner = `

Publishers (WordPress)

+

Somente leitura na UI. Credenciais em config/sites/*.json (não versionados) ou variáveis WP_* no servidor. Transporte: wp_transport no JSON ou WP_TRANSPORT no env (rest ou xmlrpc).

+${ + rows.length ? rows.join('') : '' +}
NomeTransporteURLUtilizadorPassword
Nenhum site configurado.
`; + return layout('Publishers', inner, theme); +} + +function pageTheme(theme, msg) { + const t = loadUiTheme(); + const json = JSON.stringify(t, null, 2); + const tokenSet = !!getAdminToken(); + const inner = `

Tema da UI

+

Ficheiro config/ui-theme.json (título da barra, cor de destaque).

+${msg ? `

${escapeHtml(msg.text)}

` : ''} +
+ + + +

+
`; + return layout('Tema', inner, theme); +} + +module.exports = { + loadUiTheme, + layout, + editorialBadgeClass, + editorialLabel, + pageDashboard, + pageSources, + pageSocial, + pagePublishers, + pageTheme +}; diff --git a/src/http/ui-validators.js b/src/http/ui-validators.js new file mode 100644 index 0000000..6335d02 --- /dev/null +++ b/src/http/ui-validators.js @@ -0,0 +1,63 @@ +'use strict'; + +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 !== undefined && obj.keywords !== null && !Array.isArray(obj.keywords)) { + throw new Error('keywords tem de ser um array de strings'); + } + if ( + obj.trusted_domains !== undefined && + 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 validateThemePayload(obj) { + 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'); + } +} + +module.exports = { validateSourcesPayload, validateSocialPayload, validateThemePayload };