server.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. require('dotenv').config();
  2. const { createLogger } = require('./utils/logger');
  3. const log = createLogger('gateway');
  4. const app = require('fastify')({ logger: log });
  5. const multipart = require('@fastify/multipart');
  6. const axios = require('axios');
  7. const fs = require('fs');
  8. const path = require('path');
  9. const crypto = require('crypto');
  10. const { pipeline } = require('stream/promises');
  11. const { ObjectId } = require('mongodb');
  12. const { getDb } = require('./utils/MongoDBConnector');
  13. const { encryptToken, decryptToken, warnIfNoKey } = require('./utils/crypto');
  14. const RabbitMQProducer = require('./utils/RabbitMQProducer');
  15. const UPLOAD_DIR = process.env.UPLOAD_DIR || '/uploads';
  16. const ALLOWED_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.mp4', '.mov', '.avi']);
  17. const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
  18. fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  19. app.register(multipart, { limits: { fileSize: MAX_FILE_SIZE } });
  20. const GRAPH_API = 'https://graph.facebook.com/v22.0';
  21. // The public base URL of this app (used for OAuth redirect_uri)
  22. const APP_BASE_URL = process.env.APP_BASE_URL || 'http://localhost:8081';
  23. // ─── CORS ────────────────────────────────────────────────────────────────────
  24. app.addHook('onSend', async (request, reply) => {
  25. reply.header('Access-Control-Allow-Origin', '*');
  26. reply.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  27. reply.header('Access-Control-Allow-Headers', 'Content-Type');
  28. });
  29. app.options('*', async (request, reply) => {
  30. reply.code(204).send();
  31. });
  32. // ─── Helpers ─────────────────────────────────────────────────────────────────
  33. async function getCredentials(id) {
  34. const db = await getDb();
  35. return db.collection('platform_credentials').findOne({ _id: id });
  36. }
  37. async function setCredentials(id, data) {
  38. const db = await getDb();
  39. await db.collection('platform_credentials').updateOne(
  40. { _id: id },
  41. { $set: { _id: id, ...data, updatedAt: new Date() } },
  42. { upsert: true }
  43. );
  44. }
  45. async function deleteCredentials(id) {
  46. const db = await getDb();
  47. await db.collection('platform_credentials').deleteOne({ _id: id });
  48. }
  49. // ─── Media Upload & Library ───────────────────────────────────────────────────
  50. app.post('/upload', async (request, reply) => {
  51. const data = await request.file();
  52. if (!data) return reply.code(400).send({ error: 'No file provided' });
  53. const ext = path.extname(data.filename).toLowerCase();
  54. if (!ALLOWED_EXTENSIONS.has(ext)) {
  55. data.file.resume();
  56. return reply.code(400).send({ error: `File type "${ext}" is not allowed. Allowed: jpg, jpeg, png, gif, webp, mp4, mov, avi` });
  57. }
  58. const filename = `${crypto.randomUUID()}${ext}`;
  59. const filepath = path.join(UPLOAD_DIR, filename);
  60. try {
  61. await pipeline(data.file, fs.createWriteStream(filepath));
  62. } catch (err) {
  63. app.log.error({ action: 'media_upload', outcome: 'failure', err: err.message });
  64. return reply.code(500).send({ error: 'Failed to save file' });
  65. }
  66. const stat = fs.statSync(filepath);
  67. const record = {
  68. filename,
  69. originalName: data.filename,
  70. url: `/media/${filename}`,
  71. mimetype: data.mimetype,
  72. size: stat.size,
  73. uploadedAt: new Date(),
  74. };
  75. try {
  76. const db = await getDb();
  77. await db.collection('media_files').insertOne(record);
  78. } catch (err) {
  79. app.log.error({ action: 'media_metadata_save', outcome: 'failure', err: err.message });
  80. }
  81. return { url: record.url, filename, originalName: data.filename, mimetype: data.mimetype, size: stat.size };
  82. });
  83. // List all uploaded media files, newest first
  84. app.get('/media-library', async () => {
  85. const db = await getDb();
  86. const files = await db.collection('media_files').find({}).sort({ uploadedAt: -1 }).toArray();
  87. return { files };
  88. });
  89. // Delete a media file from disk and database
  90. app.delete('/media/:filename', async (request, reply) => {
  91. const { filename } = request.params;
  92. // Prevent path traversal
  93. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  94. return reply.code(400).send({ error: 'Invalid filename' });
  95. }
  96. const filepath = path.join(UPLOAD_DIR, filename);
  97. try {
  98. fs.unlinkSync(filepath);
  99. } catch (err) {
  100. if (err.code !== 'ENOENT') {
  101. app.log.error({ action: 'media_delete', outcome: 'failure', err: err.message });
  102. return reply.code(500).send({ error: 'Failed to delete file' });
  103. }
  104. // Already gone from disk — still clean up DB record
  105. }
  106. const db = await getDb();
  107. await db.collection('media_files').deleteOne({ filename });
  108. return { success: true };
  109. });
  110. // ─── Drafts ──────────────────────────────────────────────────────────────────
  111. app.post('/drafts', async (request, reply) => {
  112. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  113. const db = await getDb();
  114. const now = new Date();
  115. const result = await db.collection('drafts').insertOne({
  116. content, mediaUrl, scheduledAt, destinations, createdAt: now, updatedAt: now,
  117. });
  118. const draft = await db.collection('drafts').findOne({ _id: result.insertedId });
  119. return reply.code(201).send(draft);
  120. });
  121. app.get('/drafts', async () => {
  122. const db = await getDb();
  123. const drafts = await db.collection('drafts').find({}).sort({ updatedAt: -1 }).toArray();
  124. return { drafts };
  125. });
  126. app.get('/drafts/:id', async (request, reply) => {
  127. const { id } = request.params;
  128. let oid;
  129. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  130. const db = await getDb();
  131. const draft = await db.collection('drafts').findOne({ _id: oid });
  132. if (!draft) return reply.code(404).send({ error: 'Draft not found' });
  133. return draft;
  134. });
  135. app.put('/drafts/:id', async (request, reply) => {
  136. const { id } = request.params;
  137. let oid;
  138. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  139. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  140. const db = await getDb();
  141. const result = await db.collection('drafts').updateOne(
  142. { _id: oid },
  143. { $set: { content, mediaUrl, scheduledAt, destinations, updatedAt: new Date() } }
  144. );
  145. if (!result.matchedCount) return reply.code(404).send({ error: 'Draft not found' });
  146. return { success: true };
  147. });
  148. app.delete('/drafts/:id', async (request, reply) => {
  149. const { id } = request.params;
  150. let oid;
  151. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  152. const db = await getDb();
  153. await db.collection('drafts').deleteOne({ _id: oid });
  154. return { success: true };
  155. });
  156. // ─── Meta Token Expiry & Auto-Refresh ────────────────────────────────────────
  157. let _tokenExpiryCache = null;
  158. let _tokenExpiryCacheAt = 0;
  159. const TOKEN_EXPIRY_TTL = 60 * 60 * 1000; // 1 hour
  160. const TOKEN_REFRESH_THRESHOLD_DAYS = 7; // refresh when ≤ this many days remain
  161. app.get('/meta/token-expiry', async (request, reply) => {
  162. if (_tokenExpiryCache && Date.now() - _tokenExpiryCacheAt < TOKEN_EXPIRY_TTL) {
  163. return _tokenExpiryCache;
  164. }
  165. const appCred = await getCredentials('meta_app');
  166. if (!appCred?.appId || !appCred?.appSecret) return { accounts: [] };
  167. const plainAppSecret = decryptToken(appCred.appSecret);
  168. if (!plainAppSecret) return { accounts: [] };
  169. const ig = await getCredentials('instagram');
  170. const selectedAccounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  171. if (!selectedAccounts.length) return { accounts: [] };
  172. const appToken = `${appCred.appId}|${plainAppSecret}`;
  173. const accounts = [];
  174. for (const account of selectedAccounts) {
  175. const plainToken = decryptToken(account.accessToken);
  176. if (!plainToken) continue;
  177. try {
  178. const res = await axios.get(`${GRAPH_API}/debug_token`, {
  179. params: { input_token: plainToken, access_token: appToken },
  180. timeout: 10000,
  181. });
  182. const data = res.data.data;
  183. const expiresAt = data.expires_at ? new Date(data.expires_at * 1000).toISOString() : null;
  184. const daysLeft = expiresAt
  185. ? Math.ceil((new Date(expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
  186. : null;
  187. accounts.push({ id: account.id, username: account.username, expiresAt, daysLeft, isValid: !!data.is_valid });
  188. } catch (err) {
  189. app.log.warn({ action: 'token_expiry_check', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  190. }
  191. }
  192. _tokenExpiryCache = { accounts, checkedAt: new Date().toISOString() };
  193. _tokenExpiryCacheAt = Date.now();
  194. return _tokenExpiryCache;
  195. });
  196. // Refresh Instagram long-lived tokens that are within TOKEN_REFRESH_THRESHOLD_DAYS of expiry.
  197. // Called by the scheduler's daily BullMQ job; can also be triggered manually from Settings.
  198. app.post('/meta/token-refresh', async (request, reply) => {
  199. const appCred = await getCredentials('meta_app');
  200. if (!appCred?.appId || !appCred?.appSecret) {
  201. return reply.code(400).send({ success: false, error: 'Meta app credentials not configured' });
  202. }
  203. const plainAppSecret = decryptToken(appCred.appSecret);
  204. if (!plainAppSecret) {
  205. return reply.code(500).send({ success: false, error: 'Failed to decrypt app secret' });
  206. }
  207. const ig = await getCredentials('instagram');
  208. const allAccounts = ig?.accounts || [];
  209. const selectedAccounts = allAccounts.filter((a) => a.selected && a.accessToken);
  210. if (!selectedAccounts.length) {
  211. return { success: true, refreshed: 0, skipped: 0, errors: 0 };
  212. }
  213. const appToken = `${appCred.appId}|${plainAppSecret}`;
  214. const refreshed = [];
  215. const skipped = [];
  216. const errors = [];
  217. for (const account of selectedAccounts) {
  218. const plainToken = decryptToken(account.accessToken);
  219. if (!plainToken) {
  220. errors.push({ username: account.username, error: 'decrypt_failed' });
  221. continue;
  222. }
  223. // Check current token expiry via debug_token
  224. let daysLeft = null;
  225. try {
  226. const debugRes = await axios.get(`${GRAPH_API}/debug_token`, {
  227. params: { input_token: plainToken, access_token: appToken },
  228. timeout: 10000,
  229. });
  230. const data = debugRes.data.data;
  231. if (!data.is_valid) {
  232. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'skip', reason: 'invalid_token' });
  233. errors.push({ username: account.username, error: 'token_invalid' });
  234. continue;
  235. }
  236. // expires_at is a Unix timestamp; null means never-expiring (page token etc.)
  237. daysLeft = data.expires_at
  238. ? Math.ceil((data.expires_at * 1000 - Date.now()) / (1000 * 60 * 60 * 24))
  239. : null;
  240. } catch (err) {
  241. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, step: 'debug_token', outcome: 'failure', err: err.message });
  242. errors.push({ username: account.username, error: err.message });
  243. continue;
  244. }
  245. // Token never expires or has plenty of time — skip
  246. if (daysLeft !== null && daysLeft > TOKEN_REFRESH_THRESHOLD_DAYS) {
  247. skipped.push({ username: account.username, daysLeft });
  248. continue;
  249. }
  250. // Refresh: exchange current long-lived token for a new one
  251. try {
  252. const refreshRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  253. params: {
  254. grant_type: 'fb_exchange_token',
  255. client_id: appCred.appId,
  256. client_secret: plainAppSecret,
  257. fb_exchange_token: plainToken,
  258. },
  259. timeout: 15000,
  260. });
  261. // Mutates the element inside allAccounts (same object reference)
  262. account.accessToken = encryptToken(refreshRes.data.access_token);
  263. refreshed.push({ username: account.username, previousDaysLeft: daysLeft });
  264. app.log.info({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'success', previousDaysLeft: daysLeft });
  265. } catch (err) {
  266. app.log.error({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  267. errors.push({ username: account.username, error: err.message });
  268. }
  269. }
  270. if (refreshed.length > 0) {
  271. await setCredentials('instagram', { accounts: allAccounts });
  272. _tokenExpiryCache = null; // force fresh expiry check on next poll
  273. }
  274. app.log.info({ action: 'token_refresh', platform: 'meta', outcome: 'complete', refreshed: refreshed.length, skipped: skipped.length, errors: errors.length });
  275. return { success: true, refreshed: refreshed.length, skipped: skipped.length, errors: errors.length };
  276. });
  277. // ─── Account Profiles ────────────────────────────────────────────────────────
  278. app.get('/profiles', async () => {
  279. const db = await getDb();
  280. const profiles = await db.collection('account_profiles').find({}).toArray();
  281. return { profiles };
  282. });
  283. app.get('/profiles/:accountKey', async (request, reply) => {
  284. const { accountKey } = request.params;
  285. const db = await getDb();
  286. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  287. return profile ?? { _id: accountKey };
  288. });
  289. app.put('/profiles/:accountKey', async (request, reply) => {
  290. const { accountKey } = request.params;
  291. const {
  292. businessName = '', description = '', websiteUrl = '', industry = '',
  293. targetAudience = '', toneOfVoice = '', keywords = '', hashtags = '',
  294. postingGuidelines = '',
  295. } = request.body || {};
  296. const db = await getDb();
  297. await db.collection('account_profiles').updateOne(
  298. { _id: accountKey },
  299. { $set: { businessName, description, websiteUrl, industry, targetAudience, toneOfVoice, keywords, hashtags, postingGuidelines, updatedAt: new Date() } },
  300. { upsert: true }
  301. );
  302. return { success: true };
  303. });
  304. // ─── AI / Ollama ──────────────────────────────────────────────────────────────
  305. const DEFAULT_OLLAMA_ENDPOINT = process.env.OLLAMA_ENDPOINT || 'http://ollama:11434';
  306. const DEFAULT_OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2';
  307. app.get('/ai/config', async () => {
  308. const config = await getCredentials('ai_config');
  309. return {
  310. provider: config?.provider || 'ollama',
  311. endpoint: config?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  312. model: config?.model || DEFAULT_OLLAMA_MODEL,
  313. visionModel: config?.visionModel || 'llava',
  314. enabled: config?.enabled ?? true,
  315. };
  316. });
  317. app.put('/ai/config', async (request, reply) => {
  318. const { provider = 'ollama', endpoint, model, visionModel = 'llava', enabled = true } = request.body || {};
  319. if (!endpoint) return reply.code(400).send({ error: 'endpoint is required' });
  320. await setCredentials('ai_config', { provider, endpoint, model, visionModel, enabled });
  321. return { success: true };
  322. });
  323. app.get('/ai/models', async (request, reply) => {
  324. const config = await getCredentials('ai_config');
  325. // Allow caller to override endpoint for test-without-save UX
  326. const endpoint = request.query.endpoint || config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  327. try {
  328. const res = await axios.get(`${endpoint}/api/tags`, { timeout: 5000 });
  329. const models = (res.data.models || []).map((m) => m.name);
  330. return { models, endpoint };
  331. } catch (err) {
  332. return reply.code(503).send({ error: 'Could not reach Ollama — check the endpoint', detail: err.message });
  333. }
  334. });
  335. app.post('/ai/generate', async (request, reply) => {
  336. const { prompt, system, model: reqModel } = request.body || {};
  337. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  338. const config = await getCredentials('ai_config');
  339. const endpoint = config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  340. const model = reqModel || config?.model || DEFAULT_OLLAMA_MODEL;
  341. try {
  342. const res = await axios.post(`${endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  343. return { text: res.data.response, model, done: res.data.done };
  344. } catch (err) {
  345. const status = err.response?.status || 503;
  346. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  347. }
  348. });
  349. // Vision caption — fetches image, passes base64 to Ollama vision model
  350. app.post('/ai/caption', async (request, reply) => {
  351. const { imageUrl, model: reqModel } = request.body || {};
  352. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  353. const config = await getCredentials('ai_config');
  354. const endpoint = config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  355. const model = reqModel || config?.visionModel || 'llava';
  356. // Fetch image → base64
  357. let imageBase64;
  358. try {
  359. let imageBuffer;
  360. if (imageUrl.startsWith('/media/')) {
  361. const filename = path.basename(imageUrl);
  362. const filepath = path.join(UPLOAD_DIR, filename);
  363. imageBuffer = fs.readFileSync(filepath);
  364. } else {
  365. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  366. imageBuffer = Buffer.from(imgRes.data);
  367. }
  368. imageBase64 = imageBuffer.toString('base64');
  369. } catch (err) {
  370. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  371. }
  372. try {
  373. const res = await axios.post(`${endpoint}/api/generate`, {
  374. model,
  375. prompt: 'Generate an engaging, concise social media caption for this image. Write only the caption text with relevant hashtags. No explanations or preamble.',
  376. images: [imageBase64],
  377. stream: false,
  378. }, { timeout: 90000 });
  379. return { caption: res.data.response, model };
  380. } catch (err) {
  381. const status = err.response?.status || 503;
  382. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  383. }
  384. });
  385. // SSE streaming endpoint — sends token-by-token as text/event-stream
  386. app.post('/ai/stream', async (request, reply) => {
  387. const { prompt, system, model: reqModel } = request.body || {};
  388. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  389. const config = await getCredentials('ai_config');
  390. const endpoint = config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  391. const model = reqModel || config?.model || DEFAULT_OLLAMA_MODEL;
  392. reply.raw.setHeader('Content-Type', 'text/event-stream');
  393. reply.raw.setHeader('Cache-Control', 'no-cache');
  394. reply.raw.setHeader('X-Accel-Buffering', 'no');
  395. reply.raw.setHeader('Connection', 'keep-alive');
  396. reply.raw.flushHeaders();
  397. try {
  398. const ollamaRes = await axios.post(`${endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  399. ollamaRes.data.on('data', (chunk) => {
  400. try {
  401. const lines = chunk.toString().split('\n').filter(Boolean);
  402. for (const line of lines) {
  403. const data = JSON.parse(line);
  404. reply.raw.write(`data: ${JSON.stringify({ token: data.response || '', done: !!data.done })}\n\n`);
  405. }
  406. } catch (_) {}
  407. });
  408. ollamaRes.data.on('end', () => { reply.raw.end(); });
  409. ollamaRes.data.on('error', (err) => {
  410. reply.raw.write(`data: ${JSON.stringify({ error: err.message, done: true })}\n\n`);
  411. reply.raw.end();
  412. });
  413. } catch (err) {
  414. reply.raw.write(`data: ${JSON.stringify({ error: err.message, done: true })}\n\n`);
  415. reply.raw.end();
  416. }
  417. });
  418. // ─── Platform service URLs ────────────────────────────────────────────────────
  419. const PLATFORM_SERVICES = {
  420. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  421. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  422. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  423. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  424. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  425. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  426. };
  427. // Direct multi-platform post endpoint.
  428. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  429. app.post('/post', async (request, reply) => {
  430. const { content, destinations = [] } = request.body || {};
  431. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  432. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  433. const results = await Promise.allSettled(
  434. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  435. const serviceUrl = PLATFORM_SERVICES[platform];
  436. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  437. const res = await axios.post(`${serviceUrl}/post`, { content, accountId, imageUrl, videoUrl, link }, { timeout: 30000 });
  438. return { platform, accountId, ...res.data };
  439. })
  440. );
  441. const output = results.map((r, i) =>
  442. r.status === 'fulfilled'
  443. ? r.value
  444. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  445. );
  446. const anyFailed = output.some((r) => !r.success);
  447. const anySucceeded = output.some((r) => r.success);
  448. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  449. // Record the post for analytics
  450. try {
  451. const db = await getDb();
  452. await db.collection('posts').insertOne({
  453. _id: crypto.randomUUID(),
  454. type: 'immediate',
  455. content,
  456. destinations,
  457. platformResults: Object.fromEntries(
  458. output.map((r) => [
  459. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  460. { success: r.success, ...(r.error && { error: r.error }) },
  461. ])
  462. ),
  463. status: postStatus,
  464. publishedAt: new Date(),
  465. createdAt: new Date(),
  466. });
  467. } catch (err) {
  468. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  469. }
  470. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  471. });
  472. // ─── Legacy post route ────────────────────────────────────────────────────────
  473. let rabbitMQProducer = new RabbitMQProducer();
  474. app.post('/', async (request, reply) => {
  475. try {
  476. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  477. reply.send({ status: 'ok' });
  478. } catch (error) {
  479. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  480. reply.status(500).send({ error: 'Internal Server Error' });
  481. }
  482. });
  483. // ─── Meta App Credentials ────────────────────────────────────────────────────
  484. // Save Facebook App ID + Secret (entered by user in Settings UI)
  485. app.post('/credentials/meta-app', async (request, reply) => {
  486. const { appId, appSecret } = request.body || {};
  487. if (!appId || !appSecret) {
  488. return reply.code(400).send({ error: 'appId and appSecret are required' });
  489. }
  490. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  491. return { success: true };
  492. });
  493. // Get Meta App config (secret is masked for UI display)
  494. app.get('/credentials/meta-app', async () => {
  495. const cred = await getCredentials('meta_app');
  496. if (!cred) return { configured: false };
  497. const plainSecret = decryptToken(cred.appSecret) || '';
  498. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  499. });
  500. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  501. // Return the Facebook OAuth URL to redirect the user to
  502. app.get('/auth/meta/init', async (request, reply) => {
  503. const cred = await getCredentials('meta_app');
  504. if (!cred?.appId) {
  505. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  506. }
  507. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  508. const scopes = [
  509. 'pages_manage_posts',
  510. 'pages_read_engagement',
  511. 'instagram_basic',
  512. 'instagram_content_publish',
  513. 'instagram_manage_insights',
  514. ].join(',');
  515. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  516. return { url };
  517. });
  518. // OAuth callback — Facebook redirects here after user authorises
  519. app.get('/auth/meta/callback', async (request, reply) => {
  520. const { code, error: oauthError } = request.query;
  521. if (oauthError) {
  522. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  523. }
  524. if (!code) {
  525. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  526. }
  527. try {
  528. const appCred = await getCredentials('meta_app');
  529. if (!appCred?.appId) throw new Error('App credentials not configured');
  530. const appSecret = decryptToken(appCred.appSecret);
  531. if (!appSecret) throw new Error('Failed to decrypt app secret');
  532. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  533. // Exchange code for short-lived token
  534. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  535. params: {
  536. client_id: appCred.appId,
  537. client_secret: appSecret,
  538. redirect_uri: redirectUri,
  539. code,
  540. },
  541. });
  542. // Upgrade to long-lived user token (~60 days)
  543. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  544. params: {
  545. grant_type: 'fb_exchange_token',
  546. client_id: appCred.appId,
  547. client_secret: appSecret,
  548. fb_exchange_token: shortRes.data.access_token,
  549. },
  550. });
  551. const userToken = longRes.data.access_token;
  552. // Fetch all managed Facebook Pages
  553. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  554. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  555. });
  556. const pages = [];
  557. const igAccounts = [];
  558. for (const page of pagesRes.data.data || []) {
  559. pages.push({
  560. id: page.id,
  561. name: page.name,
  562. accessToken: encryptToken(page.access_token),
  563. picture: page.picture?.data?.url || null,
  564. selected: false,
  565. });
  566. // Check for linked Instagram Business Account
  567. try {
  568. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  569. params: {
  570. fields: 'instagram_business_account',
  571. access_token: page.access_token,
  572. },
  573. });
  574. if (igRes.data.instagram_business_account?.id) {
  575. const igId = igRes.data.instagram_business_account.id;
  576. // Fetch IG account details
  577. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  578. params: {
  579. fields: 'id,username,name,profile_picture_url',
  580. access_token: userToken,
  581. },
  582. });
  583. igAccounts.push({
  584. id: igId,
  585. username: igProfile.data.username || igProfile.data.name,
  586. name: igProfile.data.name,
  587. avatar: igProfile.data.profile_picture_url || null,
  588. accessToken: encryptToken(userToken),
  589. pageId: page.id,
  590. selected: false,
  591. });
  592. }
  593. } catch (_) {
  594. // Page has no linked Instagram account — skip
  595. }
  596. }
  597. // Store discovery results for the UI to pick from
  598. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  599. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  600. } catch (err) {
  601. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  602. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  603. }
  604. });
  605. // Return pending discovery results so the UI can render the page picker
  606. app.get('/auth/meta/discovered', async () => {
  607. const discovery = await getCredentials('meta_discovery');
  608. if (!discovery) return { pages: [], igAccounts: [] };
  609. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  610. });
  611. // User has chosen which pages/accounts to connect
  612. app.post('/auth/meta/save', async (request, reply) => {
  613. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  614. const discovery = await getCredentials('meta_discovery');
  615. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  616. const fbPages = (discovery.pages || []).map((p) => ({
  617. ...p,
  618. selected: selectedPageIds.includes(p.id),
  619. }));
  620. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  621. ...a,
  622. selected: selectedIgAccountIds.includes(a.id),
  623. }));
  624. await setCredentials('facebook', { pages: fbPages });
  625. await setCredentials('instagram', { accounts: igAccounts });
  626. await deleteCredentials('meta_discovery');
  627. _tokenExpiryCache = null; // invalidate cache after reconnect
  628. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  629. });
  630. // Disconnect all Meta platforms
  631. app.delete('/credentials/meta', async () => {
  632. await deleteCredentials('facebook');
  633. await deleteCredentials('instagram');
  634. await deleteCredentials('meta_discovery');
  635. return { success: true };
  636. });
  637. // ─── Credential Status ────────────────────────────────────────────────────────
  638. // Aggregate connection status for all DB-managed platforms
  639. app.get('/credentials', async () => {
  640. const [metaApp, fb, ig] = await Promise.all([
  641. getCredentials('meta_app'),
  642. getCredentials('facebook'),
  643. getCredentials('instagram'),
  644. ]);
  645. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  646. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  647. return {
  648. metaApp: { configured: !!(metaApp?.appId) },
  649. facebook: {
  650. connected: fbPages.length > 0,
  651. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  652. },
  653. instagram: {
  654. connected: igAccounts.length > 0,
  655. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  656. },
  657. };
  658. });
  659. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  660. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  661. const INDUSTRY_DEFAULTS = {
  662. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  663. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  664. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  665. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  666. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  667. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  668. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  669. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  670. };
  671. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  672. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  673. // at least `afterMs` milliseconds in the future.
  674. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  675. const candidate = new Date(afterMs);
  676. candidate.setUTCHours(hourUTC, 0, 0, 0);
  677. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  678. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  679. candidate.setUTCDate(candidate.getUTCDate() + 7);
  680. } else {
  681. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  682. }
  683. return candidate;
  684. }
  685. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  686. app.get('/schedule/suggestions', async (request, reply) => {
  687. const { platform, accountId } = request.query;
  688. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  689. const db = await getDb();
  690. const query = { platform, ...(accountId && { accountId }) };
  691. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  692. let slots;
  693. let source;
  694. if (dataPoints >= 10) {
  695. const agg = await db.collection('post_metrics').aggregate([
  696. { $match: query },
  697. { $group: {
  698. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  699. avgEngagement: { $avg: '$metrics.engagementTotal' },
  700. count: { $sum: 1 },
  701. }},
  702. { $sort: { avgEngagement: -1 } },
  703. { $limit: 5 },
  704. ]).toArray();
  705. slots = agg.map((r) => [r._id.day, r._id.hour]);
  706. source = 'history';
  707. } else {
  708. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  709. source = 'default';
  710. }
  711. // 30-minute lead time so the user has time to finish writing
  712. const afterMs = Date.now() + 30 * 60 * 1000;
  713. const suggestions = slots
  714. .map(([day, hour]) => {
  715. const dt = nextOccurrence(day, hour, afterMs);
  716. const h12 = hour % 12 || 12;
  717. const ampm = hour < 12 ? 'am' : 'pm';
  718. return {
  719. utc: dt.toISOString(),
  720. dayOfWeek: day,
  721. hour,
  722. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  723. };
  724. })
  725. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  726. .slice(0, 4);
  727. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  728. return { source, suggestions };
  729. });
  730. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  731. async function crawlFacebookMetrics(db) {
  732. const fb = await getCredentials('facebook');
  733. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  734. if (!pages.length) return { count: 0 };
  735. let count = 0;
  736. for (const page of pages) {
  737. const token = decryptToken(page.accessToken);
  738. if (!token) continue;
  739. try {
  740. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  741. params: {
  742. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  743. limit: 100,
  744. access_token: token,
  745. },
  746. timeout: 30000,
  747. });
  748. for (const post of res.data.data || []) {
  749. const likes = post.reactions?.summary?.total_count || 0;
  750. const comments = post.comments?.summary?.total_count || 0;
  751. const shares = post.shares?.count || 0;
  752. const publishedAt = new Date(post.created_time);
  753. await db.collection('post_metrics').updateOne(
  754. { platform: 'facebook', postId: post.id },
  755. {
  756. $set: {
  757. platform: 'facebook',
  758. accountId: page.id,
  759. accountName: page.name,
  760. postId: post.id,
  761. content: post.message || null,
  762. publishedAt,
  763. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  764. hourOfDay: publishedAt.getUTCHours(),
  765. dayOfWeek: publishedAt.getUTCDay(),
  766. fetchedAt: new Date(),
  767. },
  768. },
  769. { upsert: true }
  770. );
  771. count++;
  772. }
  773. } catch (err) {
  774. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  775. }
  776. }
  777. return { count };
  778. }
  779. async function crawlInstagramMetrics(db) {
  780. const ig = await getCredentials('instagram');
  781. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  782. if (!accounts.length) return { count: 0 };
  783. let count = 0;
  784. for (const account of accounts) {
  785. const token = decryptToken(account.accessToken);
  786. if (!token) continue;
  787. try {
  788. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  789. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  790. timeout: 30000,
  791. });
  792. for (const media of mediaRes.data.data || []) {
  793. const likes = media.like_count || 0;
  794. const comments = media.comments_count || 0;
  795. const publishedAt = new Date(media.timestamp);
  796. let views = 0;
  797. let saves = 0;
  798. try {
  799. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  800. params: { metric: 'reach,saved', access_token: token },
  801. timeout: 10000,
  802. });
  803. for (const ins of insRes.data.data || []) {
  804. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  805. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  806. }
  807. } catch (_) {}
  808. await db.collection('post_metrics').updateOne(
  809. { platform: 'instagram', postId: media.id },
  810. {
  811. $set: {
  812. platform: 'instagram',
  813. accountId: account.id,
  814. accountName: account.username,
  815. postId: media.id,
  816. content: media.caption || null,
  817. publishedAt,
  818. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  819. hourOfDay: publishedAt.getUTCHours(),
  820. dayOfWeek: publishedAt.getUTCDay(),
  821. fetchedAt: new Date(),
  822. },
  823. },
  824. { upsert: true }
  825. );
  826. count++;
  827. }
  828. } catch (err) {
  829. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  830. }
  831. }
  832. return { count };
  833. }
  834. app.post('/analytics/crawl', async () => {
  835. const db = await getDb();
  836. const results = {};
  837. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  838. try {
  839. results[platform] = await crawler(db);
  840. } catch (err) {
  841. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  842. results[platform] = { count: 0, error: err.message };
  843. }
  844. }
  845. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  846. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  847. return { success: true, total, byPlatform: results };
  848. });
  849. app.get('/analytics/insights', async () => {
  850. const db = await getDb();
  851. const total = await db.collection('post_metrics').countDocuments({});
  852. if (total === 0) return { empty: true };
  853. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  854. db.collection('post_metrics').aggregate([
  855. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  856. { $sort: { _id: 1 } },
  857. ]).toArray(),
  858. db.collection('post_metrics').aggregate([
  859. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  860. { $sort: { _id: 1 } },
  861. ]).toArray(),
  862. db.collection('post_metrics').find({}).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  863. db.collection('post_metrics').aggregate([
  864. { $group: {
  865. _id: '$platform',
  866. avgEngagement: { $avg: '$metrics.engagementTotal' },
  867. avgLikes: { $avg: '$metrics.likes' },
  868. avgComments: { $avg: '$metrics.comments' },
  869. avgShares: { $avg: '$metrics.shares' },
  870. totalPosts: { $sum: 1 },
  871. }},
  872. { $sort: { avgEngagement: -1 } },
  873. ]).toArray(),
  874. db.collection('post_metrics').aggregate([
  875. { $group: {
  876. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  877. avgEngagement: { $avg: '$metrics.engagementTotal' },
  878. count: { $sum: 1 },
  879. }},
  880. ]).toArray(),
  881. ]);
  882. const byHour = Array.from({ length: 24 }, (_, h) => {
  883. const e = byHourRaw.find((r) => r._id === h);
  884. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  885. });
  886. const byDay = Array.from({ length: 7 }, (_, d) => {
  887. const e = byDayRaw.find((r) => r._id === d);
  888. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  889. });
  890. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  891. const day = Math.floor(i / 24);
  892. const hour = i % 24;
  893. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  894. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  895. });
  896. return {
  897. empty: false,
  898. total,
  899. byHour,
  900. byDay,
  901. heatmap,
  902. topPosts: topPosts.map((p) => ({
  903. platform: p.platform, accountName: p.accountName, postId: p.postId,
  904. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  905. })),
  906. platformComparison: platformComparison.map((p) => ({
  907. platform: p._id,
  908. avgEngagement: Math.round(p.avgEngagement),
  909. avgLikes: Math.round(p.avgLikes),
  910. avgComments: Math.round(p.avgComments),
  911. avgShares: Math.round(p.avgShares),
  912. totalPosts: p.totalPosts,
  913. })),
  914. };
  915. });
  916. // ─── Analytics ────────────────────────────────────────────────────────────────
  917. app.get('/analytics/summary', async () => {
  918. const db = await getDb();
  919. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  920. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  921. // scheduled_jobs is the primary source — it holds the full history of all
  922. // scheduled posts. posts (type: immediate) supplements it for direct dispatches.
  923. const [
  924. schedCompleted, schedFailed,
  925. immPublished, immFailed,
  926. recentSched, recentImm,
  927. schedPlatformRaw, immPlatformRaw,
  928. schedDayRaw, immDayRaw,
  929. ] = await Promise.all([
  930. db.collection('scheduled_jobs').countDocuments({ status: 'completed' }),
  931. db.collection('scheduled_jobs').countDocuments({ status: 'failed' }),
  932. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] } }),
  933. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed' }),
  934. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo } }),
  935. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo } }),
  936. // Platform breakdown from scheduled_jobs destinations
  937. db.collection('scheduled_jobs').aggregate([
  938. { $match: { status: 'completed' } },
  939. { $unwind: '$destinations' },
  940. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  941. { $sort: { count: -1 } },
  942. ]).toArray(),
  943. // Platform breakdown from immediate posts platformResults
  944. db.collection('posts').aggregate([
  945. { $match: { type: 'immediate' } },
  946. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  947. { $unwind: '$results' },
  948. { $match: { 'results.v.success': true } },
  949. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  950. { $group: { _id: '$platform', count: { $sum: 1 } } },
  951. ]).toArray(),
  952. // Activity by day from scheduled_jobs (using completedAt)
  953. db.collection('scheduled_jobs').aggregate([
  954. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo } } },
  955. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  956. { $sort: { _id: 1 } },
  957. ]).toArray(),
  958. // Activity by day from immediate posts
  959. db.collection('posts').aggregate([
  960. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo } } },
  961. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  962. { $sort: { _id: 1 } },
  963. ]).toArray(),
  964. ]);
  965. // Merge byDay from both sources
  966. const dayMap = {};
  967. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  968. dayMap[_id] = (dayMap[_id] || 0) + count;
  969. }
  970. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  971. // Merge byPlatform from both sources
  972. const platformMap = {};
  973. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  974. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  975. }
  976. const published = schedCompleted + immPublished;
  977. const failed = schedFailed + immFailed;
  978. const total = published + failed;
  979. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  980. const recentCount = recentSched + recentImm;
  981. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  982. });
  983. app.get('/analytics/posts', async (request) => {
  984. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  985. const skip = parseInt(request.query.skip || '0', 10);
  986. const db = await getDb();
  987. // scheduled_jobs holds all scheduled-post history (content stored from now on;
  988. // older records have content: undefined). Immediate posts come from the posts collection.
  989. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  990. db.collection('scheduled_jobs')
  991. .find({ status: { $in: ['completed', 'failed'] } })
  992. .sort({ completedAt: -1, scheduledAt: -1 })
  993. .skip(skip)
  994. .limit(limit)
  995. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  996. .toArray(),
  997. db.collection('posts')
  998. .find({ type: 'immediate' })
  999. .sort({ publishedAt: -1 })
  1000. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1001. .toArray(),
  1002. db.collection('scheduled_jobs').countDocuments({ status: { $in: ['completed', 'failed'] } }),
  1003. db.collection('posts').countDocuments({ type: 'immediate' }),
  1004. ]);
  1005. // Normalise to a single shape expected by the frontend
  1006. const normalised = [
  1007. ...scheduledJobs.map((j) => ({
  1008. _id: String(j._id),
  1009. type: 'scheduled',
  1010. content: j.content || null,
  1011. destinations: j.destinations || [],
  1012. platformResults: null,
  1013. status: j.status === 'completed' ? 'published' : 'failed',
  1014. publishedAt: j.completedAt || j.scheduledAt,
  1015. })),
  1016. ...immediatePosts.map((p) => ({
  1017. _id: String(p._id),
  1018. type: 'immediate',
  1019. content: p.content || null,
  1020. destinations: p.destinations || [],
  1021. platformResults: p.platformResults || null,
  1022. status: p.status,
  1023. publishedAt: p.publishedAt,
  1024. })),
  1025. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  1026. .slice(0, limit);
  1027. return { posts: normalised, total: schedTotal + immTotal };
  1028. });
  1029. module.exports = app;