server.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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 (request) => {
  850. const filter = parseAccountFilter(request.query.account);
  851. const metricsMatch = filter
  852. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  853. : {};
  854. const db = await getDb();
  855. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  856. if (total === 0) return { empty: true };
  857. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  858. db.collection('post_metrics').aggregate([
  859. { $match: metricsMatch },
  860. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  861. { $sort: { _id: 1 } },
  862. ]).toArray(),
  863. db.collection('post_metrics').aggregate([
  864. { $match: metricsMatch },
  865. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  866. { $sort: { _id: 1 } },
  867. ]).toArray(),
  868. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  869. db.collection('post_metrics').aggregate([
  870. { $match: metricsMatch },
  871. { $group: {
  872. _id: '$platform',
  873. avgEngagement: { $avg: '$metrics.engagementTotal' },
  874. avgLikes: { $avg: '$metrics.likes' },
  875. avgComments: { $avg: '$metrics.comments' },
  876. avgShares: { $avg: '$metrics.shares' },
  877. totalPosts: { $sum: 1 },
  878. }},
  879. { $sort: { avgEngagement: -1 } },
  880. ]).toArray(),
  881. db.collection('post_metrics').aggregate([
  882. { $match: metricsMatch },
  883. { $group: {
  884. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  885. avgEngagement: { $avg: '$metrics.engagementTotal' },
  886. count: { $sum: 1 },
  887. }},
  888. ]).toArray(),
  889. ]);
  890. const byHour = Array.from({ length: 24 }, (_, h) => {
  891. const e = byHourRaw.find((r) => r._id === h);
  892. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  893. });
  894. const byDay = Array.from({ length: 7 }, (_, d) => {
  895. const e = byDayRaw.find((r) => r._id === d);
  896. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  897. });
  898. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  899. const day = Math.floor(i / 24);
  900. const hour = i % 24;
  901. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  902. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  903. });
  904. return {
  905. empty: false,
  906. total,
  907. byHour,
  908. byDay,
  909. heatmap,
  910. topPosts: topPosts.map((p) => ({
  911. platform: p.platform, accountName: p.accountName, postId: p.postId,
  912. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  913. })),
  914. platformComparison: platformComparison.map((p) => ({
  915. platform: p._id,
  916. avgEngagement: Math.round(p.avgEngagement),
  917. avgLikes: Math.round(p.avgLikes),
  918. avgComments: Math.round(p.avgComments),
  919. avgShares: Math.round(p.avgShares),
  920. totalPosts: p.totalPosts,
  921. })),
  922. };
  923. });
  924. // ─── Analytics ────────────────────────────────────────────────────────────────
  925. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  926. function parseAccountFilter(account) {
  927. if (!account) return null;
  928. const idx = account.indexOf(':');
  929. if (idx === -1) return { platform: account };
  930. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  931. }
  932. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  933. function sjFilter(filter) {
  934. if (!filter) return {};
  935. return {
  936. 'destinations.platform': filter.platform,
  937. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  938. };
  939. }
  940. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  941. function ipFilter(filter) {
  942. if (!filter) return {};
  943. return {
  944. 'destinations.platform': filter.platform,
  945. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  946. };
  947. }
  948. app.get('/analytics/summary', async (request) => {
  949. const filter = parseAccountFilter(request.query.account);
  950. const db = await getDb();
  951. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  952. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  953. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  954. // account filter after $unwind so a job targeting multiple platforms only
  955. // counts the platform(s) that match the filter.
  956. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  957. const [
  958. schedCompleted, schedFailed,
  959. immPublished, immFailed,
  960. recentSched, recentImm,
  961. schedPlatformRaw, immPlatformRaw,
  962. schedDayRaw, immDayRaw,
  963. ] = await Promise.all([
  964. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  965. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  966. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  967. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  968. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  969. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  970. // Platform breakdown from scheduled_jobs destinations
  971. db.collection('scheduled_jobs').aggregate([
  972. { $match: { status: 'completed', ...sjFilter(filter) } },
  973. { $unwind: '$destinations' },
  974. ...unwindFilter,
  975. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  976. { $sort: { count: -1 } },
  977. ]).toArray(),
  978. // Platform breakdown from immediate posts platformResults
  979. db.collection('posts').aggregate([
  980. { $match: { type: 'immediate', ...ipFilter(filter) } },
  981. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  982. { $unwind: '$results' },
  983. { $match: { 'results.v.success': true } },
  984. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  985. { $group: { _id: '$platform', count: { $sum: 1 } } },
  986. ]).toArray(),
  987. // Activity by day from scheduled_jobs (using completedAt)
  988. db.collection('scheduled_jobs').aggregate([
  989. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  990. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  991. { $sort: { _id: 1 } },
  992. ]).toArray(),
  993. // Activity by day from immediate posts
  994. db.collection('posts').aggregate([
  995. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  996. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  997. { $sort: { _id: 1 } },
  998. ]).toArray(),
  999. ]);
  1000. const dayMap = {};
  1001. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1002. dayMap[_id] = (dayMap[_id] || 0) + count;
  1003. }
  1004. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1005. const platformMap = {};
  1006. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1007. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1008. }
  1009. const published = schedCompleted + immPublished;
  1010. const failed = schedFailed + immFailed;
  1011. const total = published + failed;
  1012. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1013. const recentCount = recentSched + recentImm;
  1014. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1015. });
  1016. app.get('/analytics/posts', async (request) => {
  1017. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1018. const skip = parseInt(request.query.skip || '0', 10);
  1019. const filter = parseAccountFilter(request.query.account);
  1020. const db = await getDb();
  1021. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1022. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1023. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1024. db.collection('scheduled_jobs')
  1025. .find(sjMatch)
  1026. .sort({ completedAt: -1, scheduledAt: -1 })
  1027. .skip(skip)
  1028. .limit(limit)
  1029. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1030. .toArray(),
  1031. db.collection('posts')
  1032. .find(ipMatch)
  1033. .sort({ publishedAt: -1 })
  1034. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1035. .toArray(),
  1036. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1037. db.collection('posts').countDocuments(ipMatch),
  1038. ]);
  1039. const normalised = [
  1040. ...scheduledJobs.map((j) => ({
  1041. _id: String(j._id),
  1042. type: 'scheduled',
  1043. content: j.content || null,
  1044. destinations: j.destinations || [],
  1045. platformResults: null,
  1046. status: j.status === 'completed' ? 'published' : 'failed',
  1047. publishedAt: j.completedAt || j.scheduledAt,
  1048. })),
  1049. ...immediatePosts.map((p) => ({
  1050. _id: String(p._id),
  1051. type: 'immediate',
  1052. content: p.content || null,
  1053. destinations: p.destinations || [],
  1054. platformResults: p.platformResults || null,
  1055. status: p.status,
  1056. publishedAt: p.publishedAt,
  1057. })),
  1058. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  1059. .slice(0, limit);
  1060. return { posts: normalised, total: schedTotal + immTotal };
  1061. });
  1062. module.exports = app;