server.js 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  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 folder = request.query.folder || null;
  52. const data = await request.file();
  53. if (!data) return reply.code(400).send({ error: 'No file provided' });
  54. const ext = path.extname(data.filename).toLowerCase();
  55. if (!ALLOWED_EXTENSIONS.has(ext)) {
  56. data.file.resume();
  57. return reply.code(400).send({ error: `File type "${ext}" is not allowed. Allowed: jpg, jpeg, png, gif, webp, mp4, mov, avi` });
  58. }
  59. const filename = `${crypto.randomUUID()}${ext}`;
  60. const filepath = path.join(UPLOAD_DIR, filename);
  61. try {
  62. await pipeline(data.file, fs.createWriteStream(filepath));
  63. } catch (err) {
  64. app.log.error({ action: 'media_upload', outcome: 'failure', err: err.message });
  65. return reply.code(500).send({ error: 'Failed to save file' });
  66. }
  67. const stat = fs.statSync(filepath);
  68. const record = {
  69. filename,
  70. originalName: data.filename,
  71. url: `/media/${filename}`,
  72. mimetype: data.mimetype,
  73. size: stat.size,
  74. folder: folder || null,
  75. uploadedAt: new Date(),
  76. };
  77. try {
  78. const db = await getDb();
  79. await db.collection('media_files').insertOne(record);
  80. } catch (err) {
  81. app.log.error({ action: 'media_metadata_save', outcome: 'failure', err: err.message });
  82. }
  83. return { url: record.url, filename, originalName: data.filename, mimetype: data.mimetype, size: stat.size, folder: record.folder };
  84. });
  85. // List uploaded media files, newest first; optionally filter by folder
  86. // folder=__none__ → unorganized (null/missing); folder=<name> → that folder; omit → all
  87. app.get('/media-library', async (request) => {
  88. const db = await getDb();
  89. const { folder } = request.query;
  90. const query = {};
  91. if (folder === '__none__') {
  92. query.$or = [{ folder: { $exists: false } }, { folder: null }, { folder: '' }];
  93. } else if (folder) {
  94. query.folder = folder;
  95. }
  96. const files = await db.collection('media_files').find(query).sort({ uploadedAt: -1 }).toArray();
  97. return { files };
  98. });
  99. // List custom folders with per-folder file counts
  100. app.get('/media-folders', async () => {
  101. const db = await getDb();
  102. const [folders, counts] = await Promise.all([
  103. db.collection('media_folders').find({}).sort({ createdAt: 1 }).toArray(),
  104. db.collection('media_files').aggregate([
  105. { $group: { _id: { $ifNull: ['$folder', '__none__'] }, count: { $sum: 1 } } },
  106. ]).toArray(),
  107. ]);
  108. const countMap = Object.fromEntries(counts.map((c) => [c._id, c.count]));
  109. const total = counts.reduce((s, c) => s + c.count, 0);
  110. return {
  111. folders: folders.map((f) => ({ name: f.name, count: countMap[f.name] || 0 })),
  112. totalCount: total,
  113. unorganizedCount: countMap['__none__'] || 0,
  114. folderCounts: countMap,
  115. };
  116. });
  117. // Create a custom folder
  118. app.post('/media-folders', async (request, reply) => {
  119. const { name } = request.body || {};
  120. if (!name?.trim()) return reply.code(400).send({ error: 'Folder name is required' });
  121. const trimmed = name.trim();
  122. const db = await getDb();
  123. if (await db.collection('media_folders').findOne({ name: trimmed })) {
  124. return reply.code(409).send({ error: 'Folder already exists' });
  125. }
  126. await db.collection('media_folders').insertOne({ name: trimmed, createdAt: new Date() });
  127. return { name: trimmed };
  128. });
  129. // Delete a custom folder; files in it become unorganized
  130. app.delete('/media-folders/:name', async (request, reply) => {
  131. const name = decodeURIComponent(request.params.name);
  132. const db = await getDb();
  133. await db.collection('media_folders').deleteOne({ name });
  134. await db.collection('media_files').updateMany({ folder: name }, { $set: { folder: null } });
  135. return { success: true };
  136. });
  137. // Update a file's folder assignment
  138. app.patch('/media/:filename', async (request, reply) => {
  139. const { filename } = request.params;
  140. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  141. return reply.code(400).send({ error: 'Invalid filename' });
  142. }
  143. const { folder } = request.body || {};
  144. const db = await getDb();
  145. const result = await db.collection('media_files').updateOne(
  146. { filename },
  147. { $set: { folder: folder || null } },
  148. );
  149. if (!result.matchedCount) return reply.code(404).send({ error: 'File not found' });
  150. return { success: true };
  151. });
  152. // Delete a media file from disk and database
  153. app.delete('/media/:filename', async (request, reply) => {
  154. const { filename } = request.params;
  155. // Prevent path traversal
  156. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  157. return reply.code(400).send({ error: 'Invalid filename' });
  158. }
  159. const filepath = path.join(UPLOAD_DIR, filename);
  160. try {
  161. fs.unlinkSync(filepath);
  162. } catch (err) {
  163. if (err.code !== 'ENOENT') {
  164. app.log.error({ action: 'media_delete', outcome: 'failure', err: err.message });
  165. return reply.code(500).send({ error: 'Failed to delete file' });
  166. }
  167. // Already gone from disk — still clean up DB record
  168. }
  169. const db = await getDb();
  170. await db.collection('media_files').deleteOne({ filename });
  171. return { success: true };
  172. });
  173. // ─── Drafts ──────────────────────────────────────────────────────────────────
  174. app.post('/drafts', async (request, reply) => {
  175. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  176. const db = await getDb();
  177. const now = new Date();
  178. const result = await db.collection('drafts').insertOne({
  179. content, mediaUrl, scheduledAt, destinations, createdAt: now, updatedAt: now,
  180. });
  181. const draft = await db.collection('drafts').findOne({ _id: result.insertedId });
  182. return reply.code(201).send(draft);
  183. });
  184. app.get('/drafts', async () => {
  185. const db = await getDb();
  186. const drafts = await db.collection('drafts').find({}).sort({ updatedAt: -1 }).toArray();
  187. return { drafts };
  188. });
  189. app.get('/drafts/:id', async (request, reply) => {
  190. const { id } = request.params;
  191. let oid;
  192. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  193. const db = await getDb();
  194. const draft = await db.collection('drafts').findOne({ _id: oid });
  195. if (!draft) return reply.code(404).send({ error: 'Draft not found' });
  196. return draft;
  197. });
  198. app.put('/drafts/:id', async (request, reply) => {
  199. const { id } = request.params;
  200. let oid;
  201. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  202. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  203. const db = await getDb();
  204. const result = await db.collection('drafts').updateOne(
  205. { _id: oid },
  206. { $set: { content, mediaUrl, scheduledAt, destinations, updatedAt: new Date() } }
  207. );
  208. if (!result.matchedCount) return reply.code(404).send({ error: 'Draft not found' });
  209. return { success: true };
  210. });
  211. app.delete('/drafts/:id', async (request, reply) => {
  212. const { id } = request.params;
  213. let oid;
  214. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  215. const db = await getDb();
  216. await db.collection('drafts').deleteOne({ _id: oid });
  217. return { success: true };
  218. });
  219. // ─── Meta Token Expiry & Auto-Refresh ────────────────────────────────────────
  220. let _tokenExpiryCache = null;
  221. let _tokenExpiryCacheAt = 0;
  222. const TOKEN_EXPIRY_TTL = 60 * 60 * 1000; // 1 hour
  223. const TOKEN_REFRESH_THRESHOLD_DAYS = 7; // refresh when ≤ this many days remain
  224. app.get('/meta/token-expiry', async (request, reply) => {
  225. if (_tokenExpiryCache && Date.now() - _tokenExpiryCacheAt < TOKEN_EXPIRY_TTL) {
  226. return _tokenExpiryCache;
  227. }
  228. const appCred = await getCredentials('meta_app');
  229. if (!appCred?.appId || !appCred?.appSecret) return { accounts: [] };
  230. const plainAppSecret = decryptToken(appCred.appSecret);
  231. if (!plainAppSecret) return { accounts: [] };
  232. const ig = await getCredentials('instagram');
  233. const selectedAccounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  234. if (!selectedAccounts.length) return { accounts: [] };
  235. const appToken = `${appCred.appId}|${plainAppSecret}`;
  236. const accounts = [];
  237. for (const account of selectedAccounts) {
  238. const plainToken = decryptToken(account.accessToken);
  239. if (!plainToken) continue;
  240. try {
  241. const res = await axios.get(`${GRAPH_API}/debug_token`, {
  242. params: { input_token: plainToken, access_token: appToken },
  243. timeout: 10000,
  244. });
  245. const data = res.data.data;
  246. const expiresAt = data.expires_at ? new Date(data.expires_at * 1000).toISOString() : null;
  247. const daysLeft = expiresAt
  248. ? Math.ceil((new Date(expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
  249. : null;
  250. accounts.push({ id: account.id, username: account.username, expiresAt, daysLeft, isValid: !!data.is_valid });
  251. } catch (err) {
  252. app.log.warn({ action: 'token_expiry_check', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  253. }
  254. }
  255. _tokenExpiryCache = { accounts, checkedAt: new Date().toISOString() };
  256. _tokenExpiryCacheAt = Date.now();
  257. return _tokenExpiryCache;
  258. });
  259. // Refresh Instagram long-lived tokens that are within TOKEN_REFRESH_THRESHOLD_DAYS of expiry.
  260. // Called by the scheduler's daily BullMQ job; can also be triggered manually from Settings.
  261. app.post('/meta/token-refresh', async (request, reply) => {
  262. const appCred = await getCredentials('meta_app');
  263. if (!appCred?.appId || !appCred?.appSecret) {
  264. return reply.code(400).send({ success: false, error: 'Meta app credentials not configured' });
  265. }
  266. const plainAppSecret = decryptToken(appCred.appSecret);
  267. if (!plainAppSecret) {
  268. return reply.code(500).send({ success: false, error: 'Failed to decrypt app secret' });
  269. }
  270. const ig = await getCredentials('instagram');
  271. const allAccounts = ig?.accounts || [];
  272. const selectedAccounts = allAccounts.filter((a) => a.selected && a.accessToken);
  273. if (!selectedAccounts.length) {
  274. return { success: true, refreshed: 0, skipped: 0, errors: 0 };
  275. }
  276. const appToken = `${appCred.appId}|${plainAppSecret}`;
  277. const refreshed = [];
  278. const skipped = [];
  279. const errors = [];
  280. for (const account of selectedAccounts) {
  281. const plainToken = decryptToken(account.accessToken);
  282. if (!plainToken) {
  283. errors.push({ username: account.username, error: 'decrypt_failed' });
  284. continue;
  285. }
  286. // Check current token expiry via debug_token
  287. let daysLeft = null;
  288. try {
  289. const debugRes = await axios.get(`${GRAPH_API}/debug_token`, {
  290. params: { input_token: plainToken, access_token: appToken },
  291. timeout: 10000,
  292. });
  293. const data = debugRes.data.data;
  294. if (!data.is_valid) {
  295. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'skip', reason: 'invalid_token' });
  296. errors.push({ username: account.username, error: 'token_invalid' });
  297. continue;
  298. }
  299. // expires_at is a Unix timestamp; null means never-expiring (page token etc.)
  300. daysLeft = data.expires_at
  301. ? Math.ceil((data.expires_at * 1000 - Date.now()) / (1000 * 60 * 60 * 24))
  302. : null;
  303. } catch (err) {
  304. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, step: 'debug_token', outcome: 'failure', err: err.message });
  305. errors.push({ username: account.username, error: err.message });
  306. continue;
  307. }
  308. // Token never expires or has plenty of time — skip
  309. if (daysLeft !== null && daysLeft > TOKEN_REFRESH_THRESHOLD_DAYS) {
  310. skipped.push({ username: account.username, daysLeft });
  311. continue;
  312. }
  313. // Refresh: exchange current long-lived token for a new one
  314. try {
  315. const refreshRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  316. params: {
  317. grant_type: 'fb_exchange_token',
  318. client_id: appCred.appId,
  319. client_secret: plainAppSecret,
  320. fb_exchange_token: plainToken,
  321. },
  322. timeout: 15000,
  323. });
  324. // Mutates the element inside allAccounts (same object reference)
  325. account.accessToken = encryptToken(refreshRes.data.access_token);
  326. refreshed.push({ username: account.username, previousDaysLeft: daysLeft });
  327. app.log.info({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'success', previousDaysLeft: daysLeft });
  328. } catch (err) {
  329. app.log.error({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  330. errors.push({ username: account.username, error: err.message });
  331. }
  332. }
  333. if (refreshed.length > 0) {
  334. await setCredentials('instagram', { accounts: allAccounts });
  335. _tokenExpiryCache = null; // force fresh expiry check on next poll
  336. }
  337. app.log.info({ action: 'token_refresh', platform: 'meta', outcome: 'complete', refreshed: refreshed.length, skipped: skipped.length, errors: errors.length });
  338. return { success: true, refreshed: refreshed.length, skipped: skipped.length, errors: errors.length };
  339. });
  340. // ─── Account Profiles ────────────────────────────────────────────────────────
  341. app.get('/profiles', async () => {
  342. const db = await getDb();
  343. const profiles = await db.collection('account_profiles').find({}).toArray();
  344. return { profiles };
  345. });
  346. app.get('/profiles/:accountKey', async (request, reply) => {
  347. const { accountKey } = request.params;
  348. const db = await getDb();
  349. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  350. return profile ?? { _id: accountKey };
  351. });
  352. app.put('/profiles/:accountKey', async (request, reply) => {
  353. const { accountKey } = request.params;
  354. const {
  355. businessName = '', description = '', websiteUrl = '', industry = '',
  356. targetAudience = '', toneOfVoice = '', keywords = '', hashtags = '',
  357. postingGuidelines = '',
  358. } = request.body || {};
  359. const db = await getDb();
  360. await db.collection('account_profiles').updateOne(
  361. { _id: accountKey },
  362. { $set: { businessName, description, websiteUrl, industry, targetAudience, toneOfVoice, keywords, hashtags, postingGuidelines, updatedAt: new Date() } },
  363. { upsert: true }
  364. );
  365. return { success: true };
  366. });
  367. // ─── AI / Multi-provider ─────────────────────────────────────────────────────
  368. const DEFAULT_OLLAMA_ENDPOINT = process.env.OLLAMA_ENDPOINT || 'http://ollama:11434';
  369. const DEFAULT_OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2';
  370. const PROVIDER_MODELS = {
  371. openai: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-3.5-turbo'],
  372. groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768', 'gemma2-9b-it'],
  373. gemini: ['gemini-2.0-flash', 'gemini-1.5-flash', 'gemini-1.5-pro'],
  374. };
  375. const PROVIDER_BASE_URLS = {
  376. openai: 'https://api.openai.com/v1',
  377. groq: 'https://api.groq.com/openai/v1',
  378. };
  379. // Returns decrypted runtime config for the currently active provider
  380. async function getActiveProviderConfig() {
  381. const aiConfig = await getCredentials('ai_config');
  382. const provider = aiConfig?.provider || 'ollama';
  383. if (provider === 'openai' || provider === 'groq') {
  384. const doc = await getCredentials(`${provider}_config`);
  385. return {
  386. provider,
  387. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  388. model: doc?.model || PROVIDER_MODELS[provider][0],
  389. baseUrl: PROVIDER_BASE_URLS[provider],
  390. };
  391. }
  392. if (provider === 'gemini') {
  393. const doc = await getCredentials('gemini_config');
  394. return {
  395. provider,
  396. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  397. model: doc?.model || PROVIDER_MODELS.gemini[0],
  398. };
  399. }
  400. return {
  401. provider: 'ollama',
  402. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  403. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  404. visionModel: aiConfig?.visionModel || 'llava',
  405. };
  406. }
  407. function buildOpenAIMessages(prompt, system) {
  408. const messages = [];
  409. if (system) messages.push({ role: 'system', content: system });
  410. messages.push({ role: 'user', content: prompt });
  411. return messages;
  412. }
  413. // Gemini encodes system as a leading user/model conversation pair
  414. function buildGeminiContents(prompt, system) {
  415. const contents = [];
  416. if (system) {
  417. contents.push({ role: 'user', parts: [{ text: system }] });
  418. contents.push({ role: 'model', parts: [{ text: 'Understood.' }] });
  419. }
  420. contents.push({ role: 'user', parts: [{ text: prompt }] });
  421. return contents;
  422. }
  423. app.get('/ai/config', async () => {
  424. const config = await getCredentials('ai_config');
  425. return {
  426. provider: config?.provider || 'ollama',
  427. endpoint: config?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  428. model: config?.model || DEFAULT_OLLAMA_MODEL,
  429. visionModel: config?.visionModel || 'llava',
  430. enabled: config?.enabled ?? true,
  431. };
  432. });
  433. app.put('/ai/config', async (request, reply) => {
  434. const { provider = 'ollama', endpoint, model, visionModel = 'llava', enabled = true } = request.body || {};
  435. if (provider === 'ollama' && !endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  436. await setCredentials('ai_config', { provider, endpoint, model, visionModel, enabled });
  437. return { success: true };
  438. });
  439. // ─── Provider management routes ───────────────────────────────────────────────
  440. app.get('/ai/providers', async () => {
  441. const aiConfig = await getCredentials('ai_config');
  442. const active = aiConfig?.provider || 'ollama';
  443. const [openaiDoc, groqDoc, geminiDoc] = await Promise.all([
  444. getCredentials('openai_config'),
  445. getCredentials('groq_config'),
  446. getCredentials('gemini_config'),
  447. ]);
  448. return {
  449. active,
  450. providers: [
  451. {
  452. name: 'ollama',
  453. configured: true,
  454. active: active === 'ollama',
  455. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  456. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  457. visionModel: aiConfig?.visionModel || 'llava',
  458. },
  459. {
  460. name: 'openai',
  461. configured: !!openaiDoc?.apiKey,
  462. active: active === 'openai',
  463. model: openaiDoc?.model || PROVIDER_MODELS.openai[0],
  464. apiKeyHint: openaiDoc?.apiKey ? `sk-...${decryptToken(openaiDoc.apiKey).slice(-4)}` : null,
  465. },
  466. {
  467. name: 'groq',
  468. configured: !!groqDoc?.apiKey,
  469. active: active === 'groq',
  470. model: groqDoc?.model || PROVIDER_MODELS.groq[0],
  471. apiKeyHint: groqDoc?.apiKey ? `gsk_...${decryptToken(groqDoc.apiKey).slice(-4)}` : null,
  472. },
  473. {
  474. name: 'gemini',
  475. configured: !!geminiDoc?.apiKey,
  476. active: active === 'gemini',
  477. model: geminiDoc?.model || PROVIDER_MODELS.gemini[0],
  478. apiKeyHint: geminiDoc?.apiKey ? `AIza...${decryptToken(geminiDoc.apiKey).slice(-4)}` : null,
  479. },
  480. ],
  481. };
  482. });
  483. // PUT /ai/provider/:name — save credentials and optionally set as active
  484. // ollama body: { endpoint, model, visionModel, setActive? }
  485. // others body: { apiKey, model, setActive? }
  486. app.put('/ai/provider/:name', async (request, reply) => {
  487. const { name } = request.params;
  488. const { apiKey, model, endpoint, visionModel, setActive = false } = request.body || {};
  489. if (name === 'ollama') {
  490. if (!endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  491. const existing = await getCredentials('ai_config') || {};
  492. await setCredentials('ai_config', {
  493. ...existing,
  494. provider: setActive ? 'ollama' : (existing.provider || 'ollama'),
  495. endpoint,
  496. model: model || DEFAULT_OLLAMA_MODEL,
  497. visionModel: visionModel || 'llava',
  498. });
  499. } else if (['openai', 'groq', 'gemini'].includes(name)) {
  500. if (!apiKey) return reply.code(400).send({ error: 'apiKey is required' });
  501. await setCredentials(`${name}_config`, {
  502. apiKey: encryptToken(apiKey),
  503. model: model || PROVIDER_MODELS[name][0],
  504. });
  505. if (setActive) {
  506. const existing = await getCredentials('ai_config') || {};
  507. await setCredentials('ai_config', { ...existing, provider: name });
  508. }
  509. } else {
  510. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  511. }
  512. return { success: true };
  513. });
  514. // DELETE /ai/provider/:name — remove provider credentials; falls back to ollama if it was active
  515. app.delete('/ai/provider/:name', async (request, reply) => {
  516. const { name } = request.params;
  517. if (name === 'ollama') return reply.code(400).send({ error: 'Cannot remove Ollama provider' });
  518. if (!['openai', 'groq', 'gemini'].includes(name)) return reply.code(404).send({ error: `Unknown provider: ${name}` });
  519. const db = await getDb();
  520. await db.collection('platform_credentials').deleteOne({ _id: `${name}_config` });
  521. const aiConfig = await getCredentials('ai_config') || {};
  522. if (aiConfig.provider === name) {
  523. await setCredentials('ai_config', { ...aiConfig, provider: 'ollama' });
  524. }
  525. return { success: true };
  526. });
  527. // POST /ai/provider/:name/models — list models for a provider (test without saving key)
  528. app.post('/ai/provider/:name/models', async (request, reply) => {
  529. const { name } = request.params;
  530. const { apiKey: bodyApiKey, endpoint: bodyEndpoint } = request.body || {};
  531. if (name === 'ollama') {
  532. const aiConfig = await getCredentials('ai_config');
  533. const ep = bodyEndpoint || aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  534. try {
  535. const res = await axios.get(`${ep}/api/tags`, { timeout: 5000 });
  536. return { models: (res.data.models || []).map((m) => m.name) };
  537. } catch (err) {
  538. return reply.code(503).send({ error: 'Could not reach Ollama', detail: err.message });
  539. }
  540. }
  541. if (['openai', 'groq', 'gemini'].includes(name)) {
  542. return { models: PROVIDER_MODELS[name] };
  543. }
  544. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  545. });
  546. app.get('/ai/models', async (request, reply) => {
  547. const config = await getCredentials('ai_config');
  548. const provider = config?.provider || 'ollama';
  549. if (provider !== 'ollama') {
  550. return { models: PROVIDER_MODELS[provider] || [], provider };
  551. }
  552. const endpoint = request.query.endpoint || config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  553. try {
  554. const res = await axios.get(`${endpoint}/api/tags`, { timeout: 5000 });
  555. const models = (res.data.models || []).map((m) => m.name);
  556. return { models, endpoint };
  557. } catch (err) {
  558. return reply.code(503).send({ error: 'Could not reach Ollama — check the endpoint', detail: err.message });
  559. }
  560. });
  561. app.post('/ai/generate', async (request, reply) => {
  562. const { prompt, system, model: reqModel } = request.body || {};
  563. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  564. const pconf = await getActiveProviderConfig();
  565. const model = reqModel || pconf.model;
  566. try {
  567. if (pconf.provider === 'ollama') {
  568. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  569. return { text: res.data.response, model, done: res.data.done };
  570. }
  571. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  572. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  573. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  574. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  575. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  576. return { text: res.data.choices[0]?.message?.content || '', model, done: true };
  577. }
  578. if (pconf.provider === 'gemini') {
  579. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  580. const res = await axios.post(
  581. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  582. { contents: buildGeminiContents(prompt, system) },
  583. { timeout: 90000 },
  584. );
  585. return { text: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model, done: true };
  586. }
  587. return reply.code(400).send({ error: `Unknown provider: ${pconf.provider}` });
  588. } catch (err) {
  589. const status = err.response?.status || 503;
  590. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  591. }
  592. });
  593. const CAPTION_PROMPT = 'Generate an engaging, concise social media caption for this image. Write only the caption text with relevant hashtags. No explanations or preamble.';
  594. // Vision caption — supports ollama, openai, gemini (groq has no vision)
  595. app.post('/ai/caption', async (request, reply) => {
  596. const { imageUrl, model: reqModel } = request.body || {};
  597. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  598. const pconf = await getActiveProviderConfig();
  599. let imageBase64, imageMime;
  600. try {
  601. let imageBuffer;
  602. if (imageUrl.startsWith('/media/')) {
  603. const filename = path.basename(imageUrl);
  604. imageBuffer = fs.readFileSync(path.join(UPLOAD_DIR, filename));
  605. } else {
  606. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  607. imageBuffer = Buffer.from(imgRes.data);
  608. imageMime = imgRes.headers['content-type'] || 'image/jpeg';
  609. }
  610. imageBase64 = imageBuffer.toString('base64');
  611. if (!imageMime) imageMime = 'image/jpeg';
  612. } catch (err) {
  613. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  614. }
  615. try {
  616. const model = reqModel || pconf.visionModel || pconf.model;
  617. if (pconf.provider === 'ollama') {
  618. const res = await axios.post(`${pconf.endpoint}/api/generate`, {
  619. model, prompt: CAPTION_PROMPT, images: [imageBase64], stream: false,
  620. }, { timeout: 90000 });
  621. return { caption: res.data.response, model };
  622. }
  623. if (pconf.provider === 'openai') {
  624. if (!pconf.apiKey) return reply.code(503).send({ error: 'OpenAI API key not configured' });
  625. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  626. model: model || 'gpt-4o',
  627. messages: [{ role: 'user', content: [
  628. { type: 'text', text: CAPTION_PROMPT },
  629. { type: 'image_url', image_url: { url: `data:${imageMime};base64,${imageBase64}` } },
  630. ]}],
  631. stream: false,
  632. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  633. return { caption: res.data.choices[0]?.message?.content || '', model };
  634. }
  635. if (pconf.provider === 'gemini') {
  636. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  637. const geminiModel = model || 'gemini-1.5-flash';
  638. const res = await axios.post(
  639. `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${pconf.apiKey}`,
  640. { contents: [{ role: 'user', parts: [
  641. { text: CAPTION_PROMPT },
  642. { inlineData: { mimeType: imageMime, data: imageBase64 } },
  643. ]}]},
  644. { timeout: 90000 },
  645. );
  646. return { caption: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model: geminiModel };
  647. }
  648. return reply.code(400).send({ error: `Provider ${pconf.provider} does not support vision captions` });
  649. } catch (err) {
  650. const status = err.response?.status || 503;
  651. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  652. }
  653. });
  654. // SSE streaming endpoint — normalized data: { token, done } format for all providers
  655. app.post('/ai/stream', async (request, reply) => {
  656. const { prompt, system, model: reqModel } = request.body || {};
  657. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  658. const pconf = await getActiveProviderConfig();
  659. const model = reqModel || pconf.model;
  660. reply.raw.setHeader('Content-Type', 'text/event-stream');
  661. reply.raw.setHeader('Cache-Control', 'no-cache');
  662. reply.raw.setHeader('X-Accel-Buffering', 'no');
  663. reply.raw.setHeader('Connection', 'keep-alive');
  664. reply.raw.flushHeaders();
  665. const writeToken = (token, done = false) => reply.raw.write(`data: ${JSON.stringify({ token, done })}\n\n`);
  666. const writeError = (msg) => { reply.raw.write(`data: ${JSON.stringify({ error: msg, done: true })}\n\n`); reply.raw.end(); };
  667. try {
  668. if (pconf.provider === 'ollama') {
  669. const ollamaRes = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  670. ollamaRes.data.on('data', (chunk) => {
  671. try {
  672. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  673. const data = JSON.parse(line);
  674. writeToken(data.response || '', !!data.done);
  675. }
  676. } catch (_) {}
  677. });
  678. ollamaRes.data.on('end', () => reply.raw.end());
  679. ollamaRes.data.on('error', (err) => writeError(err.message));
  680. return;
  681. }
  682. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  683. if (!pconf.apiKey) return writeError(`${pconf.provider} API key not configured`);
  684. const upstreamRes = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  685. model, messages: buildOpenAIMessages(prompt, system), stream: true,
  686. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, responseType: 'stream', timeout: 120000 });
  687. upstreamRes.data.on('data', (chunk) => {
  688. try {
  689. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  690. if (!line.startsWith('data: ')) continue;
  691. const payload = line.slice(6).trim();
  692. if (payload === '[DONE]') { writeToken('', true); return; }
  693. const data = JSON.parse(payload);
  694. const token = data.choices?.[0]?.delta?.content || '';
  695. if (token) writeToken(token);
  696. }
  697. } catch (_) {}
  698. });
  699. upstreamRes.data.on('end', () => reply.raw.end());
  700. upstreamRes.data.on('error', (err) => writeError(err.message));
  701. return;
  702. }
  703. if (pconf.provider === 'gemini') {
  704. if (!pconf.apiKey) return writeError('Gemini API key not configured');
  705. const geminiRes = await axios.post(
  706. `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${pconf.apiKey}`,
  707. { contents: buildGeminiContents(prompt, system) },
  708. { responseType: 'stream', timeout: 120000 },
  709. );
  710. geminiRes.data.on('data', (chunk) => {
  711. try {
  712. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  713. if (!line.startsWith('data: ')) continue;
  714. const data = JSON.parse(line.slice(6));
  715. const token = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  716. if (token) writeToken(token);
  717. }
  718. } catch (_) {}
  719. });
  720. geminiRes.data.on('end', () => { writeToken('', true); reply.raw.end(); });
  721. geminiRes.data.on('error', (err) => writeError(err.message));
  722. return;
  723. }
  724. writeError(`Unknown provider: ${pconf.provider}`);
  725. } catch (err) {
  726. writeError(err.message);
  727. }
  728. });
  729. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  730. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  731. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  732. app.post('/ai/bulk-draft', async (request, reply) => {
  733. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  734. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  735. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  736. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  737. const db = await getDb();
  738. const batchId = new ObjectId();
  739. const now = new Date();
  740. await db.collection('bulk_draft_batches').insertOne({
  741. _id: batchId,
  742. total: filteredTopics.length,
  743. completed: 0,
  744. failed: 0,
  745. status: 'processing',
  746. createdAt: now,
  747. updatedAt: now,
  748. });
  749. const selectedDests = destinations.filter((d) => d.selected);
  750. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  751. const system = `You are a social media content writer. Create engaging, concise posts that perform well. ${toneClause} Write only the post text with relevant hashtags. No explanations or preamble.`;
  752. // Fire-and-forget — process topics sequentially in the background
  753. (async () => {
  754. const pconf = await getActiveProviderConfig();
  755. const model = reqModel || pconf.model;
  756. for (const topic of filteredTopics) {
  757. try {
  758. const prompt = `Write a social media post about: ${topic}`;
  759. let content = '';
  760. if (pconf.provider === 'ollama') {
  761. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  762. content = res.data.response || '';
  763. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  764. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  765. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  766. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  767. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  768. content = res.data.choices[0]?.message?.content || '';
  769. } else if (pconf.provider === 'gemini') {
  770. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  771. const res = await axios.post(
  772. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  773. { contents: buildGeminiContents(prompt, system) },
  774. { timeout: 90000 },
  775. );
  776. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  777. }
  778. if (content.trim()) {
  779. const draftNow = new Date();
  780. await db.collection('drafts').insertOne({
  781. content: content.trim(),
  782. mediaUrl: '',
  783. scheduledAt: '',
  784. destinations: selectedDests,
  785. batchId: batchId.toString(),
  786. topic,
  787. createdAt: draftNow,
  788. updatedAt: draftNow,
  789. });
  790. }
  791. await db.collection('bulk_draft_batches').updateOne(
  792. { _id: batchId },
  793. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  794. );
  795. } catch (err) {
  796. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  797. await db.collection('bulk_draft_batches').updateOne(
  798. { _id: batchId },
  799. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  800. );
  801. }
  802. }
  803. await db.collection('bulk_draft_batches').updateOne(
  804. { _id: batchId },
  805. { $set: { status: 'done', updatedAt: new Date() } },
  806. );
  807. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  808. })().catch((err) => {
  809. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  810. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  811. { _id: batchId },
  812. { $set: { status: 'failed', updatedAt: new Date() } },
  813. )).catch(() => {});
  814. });
  815. return reply.code(202).send({ batchId: batchId.toString() });
  816. });
  817. // GET /ai/bulk-draft/:batchId — poll batch progress
  818. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  819. const { batchId } = request.params;
  820. let oid;
  821. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  822. const db = await getDb();
  823. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid });
  824. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  825. return {
  826. batchId: batch._id.toString(),
  827. total: batch.total,
  828. completed: batch.completed,
  829. failed: batch.failed,
  830. status: batch.status,
  831. processed: batch.completed + batch.failed,
  832. };
  833. });
  834. // ─── Platform service URLs ────────────────────────────────────────────────────
  835. const PLATFORM_SERVICES = {
  836. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  837. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  838. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  839. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  840. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  841. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  842. };
  843. // Direct multi-platform post endpoint.
  844. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  845. app.post('/post', async (request, reply) => {
  846. const { content, destinations = [] } = request.body || {};
  847. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  848. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  849. const results = await Promise.allSettled(
  850. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  851. const serviceUrl = PLATFORM_SERVICES[platform];
  852. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  853. const res = await axios.post(`${serviceUrl}/post`, { content, accountId, imageUrl, videoUrl, link }, { timeout: 30000 });
  854. return { platform, accountId, ...res.data };
  855. })
  856. );
  857. const output = results.map((r, i) =>
  858. r.status === 'fulfilled'
  859. ? r.value
  860. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  861. );
  862. const anyFailed = output.some((r) => !r.success);
  863. const anySucceeded = output.some((r) => r.success);
  864. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  865. // Record the post for analytics
  866. try {
  867. const db = await getDb();
  868. await db.collection('posts').insertOne({
  869. _id: crypto.randomUUID(),
  870. type: 'immediate',
  871. content,
  872. destinations,
  873. platformResults: Object.fromEntries(
  874. output.map((r) => [
  875. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  876. { success: r.success, ...(r.error && { error: r.error }) },
  877. ])
  878. ),
  879. status: postStatus,
  880. publishedAt: new Date(),
  881. createdAt: new Date(),
  882. });
  883. } catch (err) {
  884. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  885. }
  886. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  887. });
  888. // ─── Legacy post route ────────────────────────────────────────────────────────
  889. let rabbitMQProducer = new RabbitMQProducer();
  890. app.post('/', async (request, reply) => {
  891. try {
  892. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  893. reply.send({ status: 'ok' });
  894. } catch (error) {
  895. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  896. reply.status(500).send({ error: 'Internal Server Error' });
  897. }
  898. });
  899. // ─── Meta App Credentials ────────────────────────────────────────────────────
  900. // Save Facebook App ID + Secret (entered by user in Settings UI)
  901. app.post('/credentials/meta-app', async (request, reply) => {
  902. const { appId, appSecret } = request.body || {};
  903. if (!appId || !appSecret) {
  904. return reply.code(400).send({ error: 'appId and appSecret are required' });
  905. }
  906. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  907. return { success: true };
  908. });
  909. // Get Meta App config (secret is masked for UI display)
  910. app.get('/credentials/meta-app', async () => {
  911. const cred = await getCredentials('meta_app');
  912. if (!cred) return { configured: false };
  913. const plainSecret = decryptToken(cred.appSecret) || '';
  914. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  915. });
  916. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  917. // Return the Facebook OAuth URL to redirect the user to
  918. app.get('/auth/meta/init', async (request, reply) => {
  919. const cred = await getCredentials('meta_app');
  920. if (!cred?.appId) {
  921. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  922. }
  923. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  924. const scopes = [
  925. 'pages_manage_posts',
  926. 'pages_read_engagement',
  927. 'instagram_basic',
  928. 'instagram_content_publish',
  929. 'instagram_manage_insights',
  930. ].join(',');
  931. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  932. return { url };
  933. });
  934. // OAuth callback — Facebook redirects here after user authorises
  935. app.get('/auth/meta/callback', async (request, reply) => {
  936. const { code, error: oauthError } = request.query;
  937. if (oauthError) {
  938. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  939. }
  940. if (!code) {
  941. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  942. }
  943. try {
  944. const appCred = await getCredentials('meta_app');
  945. if (!appCred?.appId) throw new Error('App credentials not configured');
  946. const appSecret = decryptToken(appCred.appSecret);
  947. if (!appSecret) throw new Error('Failed to decrypt app secret');
  948. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  949. // Exchange code for short-lived token
  950. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  951. params: {
  952. client_id: appCred.appId,
  953. client_secret: appSecret,
  954. redirect_uri: redirectUri,
  955. code,
  956. },
  957. });
  958. // Upgrade to long-lived user token (~60 days)
  959. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  960. params: {
  961. grant_type: 'fb_exchange_token',
  962. client_id: appCred.appId,
  963. client_secret: appSecret,
  964. fb_exchange_token: shortRes.data.access_token,
  965. },
  966. });
  967. const userToken = longRes.data.access_token;
  968. // Fetch all managed Facebook Pages
  969. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  970. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  971. });
  972. const pages = [];
  973. const igAccounts = [];
  974. for (const page of pagesRes.data.data || []) {
  975. pages.push({
  976. id: page.id,
  977. name: page.name,
  978. accessToken: encryptToken(page.access_token),
  979. picture: page.picture?.data?.url || null,
  980. selected: false,
  981. });
  982. // Check for linked Instagram Business Account
  983. try {
  984. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  985. params: {
  986. fields: 'instagram_business_account',
  987. access_token: page.access_token,
  988. },
  989. });
  990. if (igRes.data.instagram_business_account?.id) {
  991. const igId = igRes.data.instagram_business_account.id;
  992. // Fetch IG account details
  993. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  994. params: {
  995. fields: 'id,username,name,profile_picture_url',
  996. access_token: userToken,
  997. },
  998. });
  999. igAccounts.push({
  1000. id: igId,
  1001. username: igProfile.data.username || igProfile.data.name,
  1002. name: igProfile.data.name,
  1003. avatar: igProfile.data.profile_picture_url || null,
  1004. accessToken: encryptToken(userToken),
  1005. pageId: page.id,
  1006. selected: false,
  1007. });
  1008. }
  1009. } catch (_) {
  1010. // Page has no linked Instagram account — skip
  1011. }
  1012. }
  1013. // Store discovery results for the UI to pick from
  1014. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1015. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1016. } catch (err) {
  1017. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1018. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1019. }
  1020. });
  1021. // Return pending discovery results so the UI can render the page picker
  1022. app.get('/auth/meta/discovered', async () => {
  1023. const discovery = await getCredentials('meta_discovery');
  1024. if (!discovery) return { pages: [], igAccounts: [] };
  1025. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1026. });
  1027. // User has chosen which pages/accounts to connect
  1028. app.post('/auth/meta/save', async (request, reply) => {
  1029. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1030. const discovery = await getCredentials('meta_discovery');
  1031. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1032. const fbPages = (discovery.pages || []).map((p) => ({
  1033. ...p,
  1034. selected: selectedPageIds.includes(p.id),
  1035. }));
  1036. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1037. ...a,
  1038. selected: selectedIgAccountIds.includes(a.id),
  1039. }));
  1040. await setCredentials('facebook', { pages: fbPages });
  1041. await setCredentials('instagram', { accounts: igAccounts });
  1042. await deleteCredentials('meta_discovery');
  1043. _tokenExpiryCache = null; // invalidate cache after reconnect
  1044. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1045. });
  1046. // Disconnect all Meta platforms
  1047. app.delete('/credentials/meta', async () => {
  1048. await deleteCredentials('facebook');
  1049. await deleteCredentials('instagram');
  1050. await deleteCredentials('meta_discovery');
  1051. return { success: true };
  1052. });
  1053. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1054. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1055. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1056. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1057. app.post('/credentials/pinterest-app', async (request, reply) => {
  1058. const { clientId, clientSecret } = request.body || {};
  1059. if (!clientId || !clientSecret) {
  1060. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1061. }
  1062. await setCredentials('pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1063. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1064. return { success: true };
  1065. });
  1066. app.get('/credentials/pinterest-app', async () => {
  1067. const cred = await getCredentials('pinterest_app');
  1068. if (!cred) return { configured: false };
  1069. const plain = decryptToken(cred.clientSecret) || '';
  1070. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1071. });
  1072. app.get('/auth/pinterest/init', async (request, reply) => {
  1073. const cred = await getCredentials('pinterest_app');
  1074. if (!cred?.clientId) {
  1075. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1076. }
  1077. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1078. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1079. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1080. return { url };
  1081. });
  1082. app.get('/auth/pinterest/callback', async (request, reply) => {
  1083. const { code, error: oauthError } = request.query;
  1084. if (oauthError) {
  1085. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1086. }
  1087. if (!code) {
  1088. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1089. }
  1090. try {
  1091. const appCred = await getCredentials('pinterest_app');
  1092. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1093. const clientSecret = decryptToken(appCred.clientSecret);
  1094. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1095. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1096. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1097. const tokenRes = await axios.post(
  1098. PINTEREST_TOKEN_URL,
  1099. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1100. {
  1101. headers: {
  1102. Authorization: `Basic ${basicAuth}`,
  1103. 'Content-Type': 'application/x-www-form-urlencoded',
  1104. },
  1105. timeout: 15000,
  1106. }
  1107. );
  1108. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1109. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1110. const [userRes, boardsRes] = await Promise.all([
  1111. axios.get(`${PINTEREST_API}/user_account`, {
  1112. headers: { Authorization: `Bearer ${access_token}` },
  1113. timeout: 10000,
  1114. }),
  1115. axios.get(`${PINTEREST_API}/boards`, {
  1116. headers: { Authorization: `Bearer ${access_token}` },
  1117. params: { page_size: 100 },
  1118. timeout: 15000,
  1119. }),
  1120. ]);
  1121. const boards = (boardsRes.data.items || []).map((b) => ({
  1122. id: b.id,
  1123. name: b.name,
  1124. privacy: b.privacy,
  1125. selected: false,
  1126. }));
  1127. await setCredentials('pinterest', {
  1128. userId: userRes.data.username,
  1129. username: userRes.data.username,
  1130. displayName: userRes.data.business_name || userRes.data.username,
  1131. avatar: userRes.data.profile_image,
  1132. accessToken: encryptToken(access_token),
  1133. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1134. tokenExpiry,
  1135. boards,
  1136. });
  1137. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1138. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1139. } catch (err) {
  1140. const msg = err.response?.data?.message || err.message;
  1141. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1142. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1143. }
  1144. });
  1145. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1146. const { selectedBoardIds = [] } = request.body || {};
  1147. const cred = await getCredentials('pinterest');
  1148. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1149. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1150. await setCredentials('pinterest', { ...cred, boards });
  1151. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1152. return { success: true, selected: boards.filter((b) => b.selected).length };
  1153. });
  1154. app.delete('/credentials/pinterest', async () => {
  1155. await deleteCredentials('pinterest');
  1156. return { success: true };
  1157. });
  1158. // ─── Credential Status ────────────────────────────────────────────────────────
  1159. // Aggregate connection status for all DB-managed platforms
  1160. app.get('/credentials', async () => {
  1161. const [metaApp, fb, ig, pinterest] = await Promise.all([
  1162. getCredentials('meta_app'),
  1163. getCredentials('facebook'),
  1164. getCredentials('instagram'),
  1165. getCredentials('pinterest'),
  1166. ]);
  1167. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1168. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1169. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1170. return {
  1171. metaApp: { configured: !!(metaApp?.appId) },
  1172. facebook: {
  1173. connected: fbPages.length > 0,
  1174. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1175. },
  1176. instagram: {
  1177. connected: igAccounts.length > 0,
  1178. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1179. },
  1180. pinterest: {
  1181. connected: pinterestBoards.length > 0,
  1182. username: pinterest?.username || null,
  1183. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1184. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1185. },
  1186. };
  1187. });
  1188. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1189. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1190. const INDUSTRY_DEFAULTS = {
  1191. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1192. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1193. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1194. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1195. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1196. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1197. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1198. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1199. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1200. };
  1201. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  1202. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  1203. // at least `afterMs` milliseconds in the future.
  1204. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  1205. const candidate = new Date(afterMs);
  1206. candidate.setUTCHours(hourUTC, 0, 0, 0);
  1207. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  1208. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  1209. candidate.setUTCDate(candidate.getUTCDate() + 7);
  1210. } else {
  1211. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  1212. }
  1213. return candidate;
  1214. }
  1215. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  1216. app.get('/schedule/suggestions', async (request, reply) => {
  1217. const { platform, accountId } = request.query;
  1218. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  1219. const db = await getDb();
  1220. const query = { platform, ...(accountId && { accountId }) };
  1221. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  1222. let slots;
  1223. let source;
  1224. if (dataPoints >= 10) {
  1225. const agg = await db.collection('post_metrics').aggregate([
  1226. { $match: query },
  1227. { $group: {
  1228. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1229. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1230. count: { $sum: 1 },
  1231. }},
  1232. { $sort: { avgEngagement: -1 } },
  1233. { $limit: 5 },
  1234. ]).toArray();
  1235. slots = agg.map((r) => [r._id.day, r._id.hour]);
  1236. source = 'history';
  1237. } else {
  1238. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  1239. source = 'default';
  1240. }
  1241. // 30-minute lead time so the user has time to finish writing
  1242. const afterMs = Date.now() + 30 * 60 * 1000;
  1243. const suggestions = slots
  1244. .map(([day, hour]) => {
  1245. const dt = nextOccurrence(day, hour, afterMs);
  1246. const h12 = hour % 12 || 12;
  1247. const ampm = hour < 12 ? 'am' : 'pm';
  1248. return {
  1249. utc: dt.toISOString(),
  1250. dayOfWeek: day,
  1251. hour,
  1252. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  1253. };
  1254. })
  1255. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  1256. .slice(0, 4);
  1257. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  1258. return { source, suggestions };
  1259. });
  1260. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  1261. async function crawlFacebookMetrics(db) {
  1262. const fb = await getCredentials('facebook');
  1263. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  1264. if (!pages.length) return { count: 0 };
  1265. let count = 0;
  1266. for (const page of pages) {
  1267. const token = decryptToken(page.accessToken);
  1268. if (!token) continue;
  1269. try {
  1270. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  1271. params: {
  1272. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  1273. limit: 100,
  1274. access_token: token,
  1275. },
  1276. timeout: 30000,
  1277. });
  1278. for (const post of res.data.data || []) {
  1279. const likes = post.reactions?.summary?.total_count || 0;
  1280. const comments = post.comments?.summary?.total_count || 0;
  1281. const shares = post.shares?.count || 0;
  1282. const publishedAt = new Date(post.created_time);
  1283. await db.collection('post_metrics').updateOne(
  1284. { platform: 'facebook', postId: post.id },
  1285. {
  1286. $set: {
  1287. platform: 'facebook',
  1288. accountId: page.id,
  1289. accountName: page.name,
  1290. postId: post.id,
  1291. content: post.message || null,
  1292. publishedAt,
  1293. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  1294. hourOfDay: publishedAt.getUTCHours(),
  1295. dayOfWeek: publishedAt.getUTCDay(),
  1296. fetchedAt: new Date(),
  1297. },
  1298. },
  1299. { upsert: true }
  1300. );
  1301. count++;
  1302. }
  1303. } catch (err) {
  1304. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  1305. }
  1306. }
  1307. return { count };
  1308. }
  1309. async function crawlInstagramMetrics(db) {
  1310. const ig = await getCredentials('instagram');
  1311. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  1312. if (!accounts.length) return { count: 0 };
  1313. let count = 0;
  1314. for (const account of accounts) {
  1315. const token = decryptToken(account.accessToken);
  1316. if (!token) continue;
  1317. try {
  1318. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  1319. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  1320. timeout: 30000,
  1321. });
  1322. for (const media of mediaRes.data.data || []) {
  1323. const likes = media.like_count || 0;
  1324. const comments = media.comments_count || 0;
  1325. const publishedAt = new Date(media.timestamp);
  1326. let views = 0;
  1327. let saves = 0;
  1328. try {
  1329. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  1330. params: { metric: 'reach,saved', access_token: token },
  1331. timeout: 10000,
  1332. });
  1333. for (const ins of insRes.data.data || []) {
  1334. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  1335. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  1336. }
  1337. } catch (_) {}
  1338. await db.collection('post_metrics').updateOne(
  1339. { platform: 'instagram', postId: media.id },
  1340. {
  1341. $set: {
  1342. platform: 'instagram',
  1343. accountId: account.id,
  1344. accountName: account.username,
  1345. postId: media.id,
  1346. content: media.caption || null,
  1347. publishedAt,
  1348. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  1349. hourOfDay: publishedAt.getUTCHours(),
  1350. dayOfWeek: publishedAt.getUTCDay(),
  1351. fetchedAt: new Date(),
  1352. },
  1353. },
  1354. { upsert: true }
  1355. );
  1356. count++;
  1357. }
  1358. } catch (err) {
  1359. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  1360. }
  1361. }
  1362. return { count };
  1363. }
  1364. app.post('/analytics/crawl', async () => {
  1365. const db = await getDb();
  1366. const results = {};
  1367. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  1368. try {
  1369. results[platform] = await crawler(db);
  1370. } catch (err) {
  1371. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  1372. results[platform] = { count: 0, error: err.message };
  1373. }
  1374. }
  1375. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  1376. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  1377. return { success: true, total, byPlatform: results };
  1378. });
  1379. app.get('/analytics/insights', async (request) => {
  1380. const filter = parseAccountFilter(request.query.account);
  1381. const metricsMatch = filter
  1382. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1383. : {};
  1384. const db = await getDb();
  1385. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  1386. if (total === 0) return { empty: true };
  1387. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  1388. db.collection('post_metrics').aggregate([
  1389. { $match: metricsMatch },
  1390. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1391. { $sort: { _id: 1 } },
  1392. ]).toArray(),
  1393. db.collection('post_metrics').aggregate([
  1394. { $match: metricsMatch },
  1395. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1396. { $sort: { _id: 1 } },
  1397. ]).toArray(),
  1398. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  1399. db.collection('post_metrics').aggregate([
  1400. { $match: metricsMatch },
  1401. { $group: {
  1402. _id: '$platform',
  1403. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1404. avgLikes: { $avg: '$metrics.likes' },
  1405. avgComments: { $avg: '$metrics.comments' },
  1406. avgShares: { $avg: '$metrics.shares' },
  1407. totalPosts: { $sum: 1 },
  1408. }},
  1409. { $sort: { avgEngagement: -1 } },
  1410. ]).toArray(),
  1411. db.collection('post_metrics').aggregate([
  1412. { $match: metricsMatch },
  1413. { $group: {
  1414. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1415. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1416. count: { $sum: 1 },
  1417. }},
  1418. ]).toArray(),
  1419. ]);
  1420. const byHour = Array.from({ length: 24 }, (_, h) => {
  1421. const e = byHourRaw.find((r) => r._id === h);
  1422. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1423. });
  1424. const byDay = Array.from({ length: 7 }, (_, d) => {
  1425. const e = byDayRaw.find((r) => r._id === d);
  1426. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1427. });
  1428. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  1429. const day = Math.floor(i / 24);
  1430. const hour = i % 24;
  1431. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  1432. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1433. });
  1434. return {
  1435. empty: false,
  1436. total,
  1437. byHour,
  1438. byDay,
  1439. heatmap,
  1440. topPosts: topPosts.map((p) => ({
  1441. platform: p.platform, accountName: p.accountName, postId: p.postId,
  1442. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  1443. })),
  1444. platformComparison: platformComparison.map((p) => ({
  1445. platform: p._id,
  1446. avgEngagement: Math.round(p.avgEngagement),
  1447. avgLikes: Math.round(p.avgLikes),
  1448. avgComments: Math.round(p.avgComments),
  1449. avgShares: Math.round(p.avgShares),
  1450. totalPosts: p.totalPosts,
  1451. })),
  1452. };
  1453. });
  1454. // ─── Analytics ────────────────────────────────────────────────────────────────
  1455. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  1456. function parseAccountFilter(account) {
  1457. if (!account) return null;
  1458. const idx = account.indexOf(':');
  1459. if (idx === -1) return { platform: account };
  1460. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  1461. }
  1462. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  1463. function sjFilter(filter) {
  1464. if (!filter) return {};
  1465. return {
  1466. 'destinations.platform': filter.platform,
  1467. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1468. };
  1469. }
  1470. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  1471. function ipFilter(filter) {
  1472. if (!filter) return {};
  1473. return {
  1474. 'destinations.platform': filter.platform,
  1475. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1476. };
  1477. }
  1478. app.get('/analytics/summary', async (request) => {
  1479. const filter = parseAccountFilter(request.query.account);
  1480. const db = await getDb();
  1481. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1482. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1483. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  1484. // account filter after $unwind so a job targeting multiple platforms only
  1485. // counts the platform(s) that match the filter.
  1486. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  1487. const [
  1488. schedCompleted, schedFailed,
  1489. immPublished, immFailed,
  1490. recentSched, recentImm,
  1491. schedPlatformRaw, immPlatformRaw,
  1492. schedDayRaw, immDayRaw,
  1493. ] = await Promise.all([
  1494. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  1495. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  1496. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  1497. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  1498. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  1499. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  1500. // Platform breakdown from scheduled_jobs destinations
  1501. db.collection('scheduled_jobs').aggregate([
  1502. { $match: { status: 'completed', ...sjFilter(filter) } },
  1503. { $unwind: '$destinations' },
  1504. ...unwindFilter,
  1505. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  1506. { $sort: { count: -1 } },
  1507. ]).toArray(),
  1508. // Platform breakdown from immediate posts platformResults
  1509. db.collection('posts').aggregate([
  1510. { $match: { type: 'immediate', ...ipFilter(filter) } },
  1511. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  1512. { $unwind: '$results' },
  1513. { $match: { 'results.v.success': true } },
  1514. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  1515. { $group: { _id: '$platform', count: { $sum: 1 } } },
  1516. ]).toArray(),
  1517. // Activity by day from scheduled_jobs (using completedAt)
  1518. db.collection('scheduled_jobs').aggregate([
  1519. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  1520. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  1521. { $sort: { _id: 1 } },
  1522. ]).toArray(),
  1523. // Activity by day from immediate posts
  1524. db.collection('posts').aggregate([
  1525. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  1526. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  1527. { $sort: { _id: 1 } },
  1528. ]).toArray(),
  1529. ]);
  1530. const dayMap = {};
  1531. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1532. dayMap[_id] = (dayMap[_id] || 0) + count;
  1533. }
  1534. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1535. const platformMap = {};
  1536. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1537. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1538. }
  1539. const published = schedCompleted + immPublished;
  1540. const failed = schedFailed + immFailed;
  1541. const total = published + failed;
  1542. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1543. const recentCount = recentSched + recentImm;
  1544. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1545. });
  1546. app.get('/analytics/posts', async (request) => {
  1547. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1548. const skip = parseInt(request.query.skip || '0', 10);
  1549. const filter = parseAccountFilter(request.query.account);
  1550. const db = await getDb();
  1551. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1552. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1553. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1554. db.collection('scheduled_jobs')
  1555. .find(sjMatch)
  1556. .sort({ completedAt: -1, scheduledAt: -1 })
  1557. .skip(skip)
  1558. .limit(limit)
  1559. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1560. .toArray(),
  1561. db.collection('posts')
  1562. .find(ipMatch)
  1563. .sort({ publishedAt: -1 })
  1564. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1565. .toArray(),
  1566. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1567. db.collection('posts').countDocuments(ipMatch),
  1568. ]);
  1569. const normalised = [
  1570. ...scheduledJobs.map((j) => ({
  1571. _id: String(j._id),
  1572. type: 'scheduled',
  1573. content: j.content || null,
  1574. destinations: j.destinations || [],
  1575. platformResults: null,
  1576. status: j.status === 'completed' ? 'published' : 'failed',
  1577. publishedAt: j.completedAt || j.scheduledAt,
  1578. })),
  1579. ...immediatePosts.map((p) => ({
  1580. _id: String(p._id),
  1581. type: 'immediate',
  1582. content: p.content || null,
  1583. destinations: p.destinations || [],
  1584. platformResults: p.platformResults || null,
  1585. status: p.status,
  1586. publishedAt: p.publishedAt,
  1587. })),
  1588. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  1589. .slice(0, limit);
  1590. return { posts: normalised, total: schedTotal + immTotal };
  1591. });
  1592. module.exports = app;