server.js 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422
  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: rawSystem, model: reqModel, useCompetitorContext } = request.body || {};
  563. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  564. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  565. const system = rawSystem ? rawSystem + competitorSuffix : (competitorSuffix || undefined);
  566. const pconf = await getActiveProviderConfig();
  567. const model = reqModel || pconf.model;
  568. try {
  569. if (pconf.provider === 'ollama') {
  570. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  571. return { text: res.data.response, model, done: res.data.done };
  572. }
  573. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  574. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  575. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  576. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  577. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  578. return { text: res.data.choices[0]?.message?.content || '', model, done: true };
  579. }
  580. if (pconf.provider === 'gemini') {
  581. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  582. const res = await axios.post(
  583. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  584. { contents: buildGeminiContents(prompt, system) },
  585. { timeout: 90000 },
  586. );
  587. return { text: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model, done: true };
  588. }
  589. return reply.code(400).send({ error: `Unknown provider: ${pconf.provider}` });
  590. } catch (err) {
  591. const status = err.response?.status || 503;
  592. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  593. }
  594. });
  595. 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.';
  596. // Vision caption — supports ollama, openai, gemini (groq has no vision)
  597. app.post('/ai/caption', async (request, reply) => {
  598. const { imageUrl, model: reqModel } = request.body || {};
  599. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  600. const pconf = await getActiveProviderConfig();
  601. let imageBase64, imageMime;
  602. try {
  603. let imageBuffer;
  604. if (imageUrl.startsWith('/media/')) {
  605. const filename = path.basename(imageUrl);
  606. imageBuffer = fs.readFileSync(path.join(UPLOAD_DIR, filename));
  607. } else {
  608. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  609. imageBuffer = Buffer.from(imgRes.data);
  610. imageMime = imgRes.headers['content-type'] || 'image/jpeg';
  611. }
  612. imageBase64 = imageBuffer.toString('base64');
  613. if (!imageMime) imageMime = 'image/jpeg';
  614. } catch (err) {
  615. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  616. }
  617. try {
  618. const model = reqModel || pconf.visionModel || pconf.model;
  619. if (pconf.provider === 'ollama') {
  620. const res = await axios.post(`${pconf.endpoint}/api/generate`, {
  621. model, prompt: CAPTION_PROMPT, images: [imageBase64], stream: false,
  622. }, { timeout: 90000 });
  623. return { caption: res.data.response, model };
  624. }
  625. if (pconf.provider === 'openai') {
  626. if (!pconf.apiKey) return reply.code(503).send({ error: 'OpenAI API key not configured' });
  627. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  628. model: model || 'gpt-4o',
  629. messages: [{ role: 'user', content: [
  630. { type: 'text', text: CAPTION_PROMPT },
  631. { type: 'image_url', image_url: { url: `data:${imageMime};base64,${imageBase64}` } },
  632. ]}],
  633. stream: false,
  634. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  635. return { caption: res.data.choices[0]?.message?.content || '', model };
  636. }
  637. if (pconf.provider === 'gemini') {
  638. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  639. const geminiModel = model || 'gemini-1.5-flash';
  640. const res = await axios.post(
  641. `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${pconf.apiKey}`,
  642. { contents: [{ role: 'user', parts: [
  643. { text: CAPTION_PROMPT },
  644. { inlineData: { mimeType: imageMime, data: imageBase64 } },
  645. ]}]},
  646. { timeout: 90000 },
  647. );
  648. return { caption: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model: geminiModel };
  649. }
  650. return reply.code(400).send({ error: `Provider ${pconf.provider} does not support vision captions` });
  651. } catch (err) {
  652. const status = err.response?.status || 503;
  653. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  654. }
  655. });
  656. // SSE streaming endpoint — normalized data: { token, done } format for all providers
  657. app.post('/ai/stream', async (request, reply) => {
  658. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext } = request.body || {};
  659. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  660. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  661. const system = rawSystem ? rawSystem + competitorSuffix : (competitorSuffix || undefined);
  662. const pconf = await getActiveProviderConfig();
  663. const model = reqModel || pconf.model;
  664. reply.raw.setHeader('Content-Type', 'text/event-stream');
  665. reply.raw.setHeader('Cache-Control', 'no-cache');
  666. reply.raw.setHeader('X-Accel-Buffering', 'no');
  667. reply.raw.setHeader('Connection', 'keep-alive');
  668. reply.raw.flushHeaders();
  669. const writeToken = (token, done = false) => reply.raw.write(`data: ${JSON.stringify({ token, done })}\n\n`);
  670. const writeError = (msg) => { reply.raw.write(`data: ${JSON.stringify({ error: msg, done: true })}\n\n`); reply.raw.end(); };
  671. try {
  672. if (pconf.provider === 'ollama') {
  673. const ollamaRes = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  674. ollamaRes.data.on('data', (chunk) => {
  675. try {
  676. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  677. const data = JSON.parse(line);
  678. writeToken(data.response || '', !!data.done);
  679. }
  680. } catch (_) {}
  681. });
  682. ollamaRes.data.on('end', () => reply.raw.end());
  683. ollamaRes.data.on('error', (err) => writeError(err.message));
  684. return;
  685. }
  686. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  687. if (!pconf.apiKey) return writeError(`${pconf.provider} API key not configured`);
  688. const upstreamRes = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  689. model, messages: buildOpenAIMessages(prompt, system), stream: true,
  690. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, responseType: 'stream', timeout: 120000 });
  691. upstreamRes.data.on('data', (chunk) => {
  692. try {
  693. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  694. if (!line.startsWith('data: ')) continue;
  695. const payload = line.slice(6).trim();
  696. if (payload === '[DONE]') { writeToken('', true); return; }
  697. const data = JSON.parse(payload);
  698. const token = data.choices?.[0]?.delta?.content || '';
  699. if (token) writeToken(token);
  700. }
  701. } catch (_) {}
  702. });
  703. upstreamRes.data.on('end', () => reply.raw.end());
  704. upstreamRes.data.on('error', (err) => writeError(err.message));
  705. return;
  706. }
  707. if (pconf.provider === 'gemini') {
  708. if (!pconf.apiKey) return writeError('Gemini API key not configured');
  709. const geminiRes = await axios.post(
  710. `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${pconf.apiKey}`,
  711. { contents: buildGeminiContents(prompt, system) },
  712. { responseType: 'stream', timeout: 120000 },
  713. );
  714. geminiRes.data.on('data', (chunk) => {
  715. try {
  716. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  717. if (!line.startsWith('data: ')) continue;
  718. const data = JSON.parse(line.slice(6));
  719. const token = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  720. if (token) writeToken(token);
  721. }
  722. } catch (_) {}
  723. });
  724. geminiRes.data.on('end', () => { writeToken('', true); reply.raw.end(); });
  725. geminiRes.data.on('error', (err) => writeError(err.message));
  726. return;
  727. }
  728. writeError(`Unknown provider: ${pconf.provider}`);
  729. } catch (err) {
  730. writeError(err.message);
  731. }
  732. });
  733. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  734. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  735. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  736. app.post('/ai/bulk-draft', async (request, reply) => {
  737. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  738. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  739. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  740. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  741. const db = await getDb();
  742. const batchId = new ObjectId();
  743. const now = new Date();
  744. await db.collection('bulk_draft_batches').insertOne({
  745. _id: batchId,
  746. total: filteredTopics.length,
  747. completed: 0,
  748. failed: 0,
  749. status: 'processing',
  750. createdAt: now,
  751. updatedAt: now,
  752. });
  753. const selectedDests = destinations.filter((d) => d.selected);
  754. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  755. 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.`;
  756. // Fire-and-forget — process topics sequentially in the background
  757. (async () => {
  758. const pconf = await getActiveProviderConfig();
  759. const model = reqModel || pconf.model;
  760. for (const topic of filteredTopics) {
  761. try {
  762. const prompt = `Write a social media post about: ${topic}`;
  763. let content = '';
  764. if (pconf.provider === 'ollama') {
  765. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  766. content = res.data.response || '';
  767. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  768. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  769. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  770. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  771. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  772. content = res.data.choices[0]?.message?.content || '';
  773. } else if (pconf.provider === 'gemini') {
  774. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  775. const res = await axios.post(
  776. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  777. { contents: buildGeminiContents(prompt, system) },
  778. { timeout: 90000 },
  779. );
  780. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  781. }
  782. if (content.trim()) {
  783. const draftNow = new Date();
  784. await db.collection('drafts').insertOne({
  785. content: content.trim(),
  786. mediaUrl: '',
  787. scheduledAt: '',
  788. destinations: selectedDests,
  789. batchId: batchId.toString(),
  790. topic,
  791. createdAt: draftNow,
  792. updatedAt: draftNow,
  793. });
  794. }
  795. await db.collection('bulk_draft_batches').updateOne(
  796. { _id: batchId },
  797. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  798. );
  799. } catch (err) {
  800. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  801. await db.collection('bulk_draft_batches').updateOne(
  802. { _id: batchId },
  803. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  804. );
  805. }
  806. }
  807. await db.collection('bulk_draft_batches').updateOne(
  808. { _id: batchId },
  809. { $set: { status: 'done', updatedAt: new Date() } },
  810. );
  811. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  812. })().catch((err) => {
  813. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  814. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  815. { _id: batchId },
  816. { $set: { status: 'failed', updatedAt: new Date() } },
  817. )).catch(() => {});
  818. });
  819. return reply.code(202).send({ batchId: batchId.toString() });
  820. });
  821. // GET /ai/bulk-draft/:batchId — poll batch progress
  822. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  823. const { batchId } = request.params;
  824. let oid;
  825. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  826. const db = await getDb();
  827. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid });
  828. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  829. return {
  830. batchId: batch._id.toString(),
  831. total: batch.total,
  832. completed: batch.completed,
  833. failed: batch.failed,
  834. status: batch.status,
  835. processed: batch.completed + batch.failed,
  836. };
  837. });
  838. // ─── Platform service URLs ────────────────────────────────────────────────────
  839. const PLATFORM_SERVICES = {
  840. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  841. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  842. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  843. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  844. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  845. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  846. };
  847. // Direct multi-platform post endpoint.
  848. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  849. app.post('/post', async (request, reply) => {
  850. const { content, destinations = [], firstComment } = request.body || {};
  851. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  852. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  853. const results = await Promise.allSettled(
  854. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  855. const serviceUrl = PLATFORM_SERVICES[platform];
  856. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  857. const res = await axios.post(
  858. `${serviceUrl}/post`,
  859. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  860. { timeout: 30000 }
  861. );
  862. return { platform, accountId, ...res.data };
  863. })
  864. );
  865. const output = results.map((r, i) =>
  866. r.status === 'fulfilled'
  867. ? r.value
  868. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  869. );
  870. const anyFailed = output.some((r) => !r.success);
  871. const anySucceeded = output.some((r) => r.success);
  872. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  873. // Record the post for analytics
  874. try {
  875. const db = await getDb();
  876. await db.collection('posts').insertOne({
  877. _id: crypto.randomUUID(),
  878. type: 'immediate',
  879. content,
  880. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  881. destinations,
  882. platformResults: Object.fromEntries(
  883. output.map((r) => [
  884. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  885. { success: r.success, ...(r.error && { error: r.error }) },
  886. ])
  887. ),
  888. status: postStatus,
  889. publishedAt: new Date(),
  890. createdAt: new Date(),
  891. });
  892. } catch (err) {
  893. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  894. }
  895. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  896. });
  897. // ─── Legacy post route ────────────────────────────────────────────────────────
  898. let rabbitMQProducer = new RabbitMQProducer();
  899. app.post('/', async (request, reply) => {
  900. try {
  901. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  902. reply.send({ status: 'ok' });
  903. } catch (error) {
  904. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  905. reply.status(500).send({ error: 'Internal Server Error' });
  906. }
  907. });
  908. // ─── Meta App Credentials ────────────────────────────────────────────────────
  909. // Save Facebook App ID + Secret (entered by user in Settings UI)
  910. app.post('/credentials/meta-app', async (request, reply) => {
  911. const { appId, appSecret } = request.body || {};
  912. if (!appId || !appSecret) {
  913. return reply.code(400).send({ error: 'appId and appSecret are required' });
  914. }
  915. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  916. return { success: true };
  917. });
  918. // Get Meta App config (secret is masked for UI display)
  919. app.get('/credentials/meta-app', async () => {
  920. const cred = await getCredentials('meta_app');
  921. if (!cred) return { configured: false };
  922. const plainSecret = decryptToken(cred.appSecret) || '';
  923. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  924. });
  925. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  926. // Return the Facebook OAuth URL to redirect the user to
  927. app.get('/auth/meta/init', async (request, reply) => {
  928. const cred = await getCredentials('meta_app');
  929. if (!cred?.appId) {
  930. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  931. }
  932. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  933. const scopes = [
  934. 'pages_manage_posts',
  935. 'pages_read_engagement',
  936. 'instagram_basic',
  937. 'instagram_content_publish',
  938. 'instagram_manage_insights',
  939. ].join(',');
  940. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  941. return { url };
  942. });
  943. // OAuth callback — Facebook redirects here after user authorises
  944. app.get('/auth/meta/callback', async (request, reply) => {
  945. const { code, error: oauthError } = request.query;
  946. if (oauthError) {
  947. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  948. }
  949. if (!code) {
  950. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  951. }
  952. try {
  953. const appCred = await getCredentials('meta_app');
  954. if (!appCred?.appId) throw new Error('App credentials not configured');
  955. const appSecret = decryptToken(appCred.appSecret);
  956. if (!appSecret) throw new Error('Failed to decrypt app secret');
  957. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  958. // Exchange code for short-lived token
  959. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  960. params: {
  961. client_id: appCred.appId,
  962. client_secret: appSecret,
  963. redirect_uri: redirectUri,
  964. code,
  965. },
  966. });
  967. // Upgrade to long-lived user token (~60 days)
  968. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  969. params: {
  970. grant_type: 'fb_exchange_token',
  971. client_id: appCred.appId,
  972. client_secret: appSecret,
  973. fb_exchange_token: shortRes.data.access_token,
  974. },
  975. });
  976. const userToken = longRes.data.access_token;
  977. // Fetch all managed Facebook Pages
  978. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  979. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  980. });
  981. const pages = [];
  982. const igAccounts = [];
  983. for (const page of pagesRes.data.data || []) {
  984. pages.push({
  985. id: page.id,
  986. name: page.name,
  987. accessToken: encryptToken(page.access_token),
  988. picture: page.picture?.data?.url || null,
  989. selected: false,
  990. });
  991. // Check for linked Instagram Business Account
  992. try {
  993. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  994. params: {
  995. fields: 'instagram_business_account',
  996. access_token: page.access_token,
  997. },
  998. });
  999. if (igRes.data.instagram_business_account?.id) {
  1000. const igId = igRes.data.instagram_business_account.id;
  1001. // Fetch IG account details
  1002. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1003. params: {
  1004. fields: 'id,username,name,profile_picture_url',
  1005. access_token: userToken,
  1006. },
  1007. });
  1008. igAccounts.push({
  1009. id: igId,
  1010. username: igProfile.data.username || igProfile.data.name,
  1011. name: igProfile.data.name,
  1012. avatar: igProfile.data.profile_picture_url || null,
  1013. accessToken: encryptToken(userToken),
  1014. pageId: page.id,
  1015. selected: false,
  1016. });
  1017. }
  1018. } catch (_) {
  1019. // Page has no linked Instagram account — skip
  1020. }
  1021. }
  1022. // Store discovery results for the UI to pick from
  1023. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1024. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1025. } catch (err) {
  1026. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1027. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1028. }
  1029. });
  1030. // Return pending discovery results so the UI can render the page picker
  1031. app.get('/auth/meta/discovered', async () => {
  1032. const discovery = await getCredentials('meta_discovery');
  1033. if (!discovery) return { pages: [], igAccounts: [] };
  1034. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1035. });
  1036. // User has chosen which pages/accounts to connect
  1037. app.post('/auth/meta/save', async (request, reply) => {
  1038. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1039. const discovery = await getCredentials('meta_discovery');
  1040. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1041. const fbPages = (discovery.pages || []).map((p) => ({
  1042. ...p,
  1043. selected: selectedPageIds.includes(p.id),
  1044. }));
  1045. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1046. ...a,
  1047. selected: selectedIgAccountIds.includes(a.id),
  1048. }));
  1049. await setCredentials('facebook', { pages: fbPages });
  1050. await setCredentials('instagram', { accounts: igAccounts });
  1051. await deleteCredentials('meta_discovery');
  1052. _tokenExpiryCache = null; // invalidate cache after reconnect
  1053. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1054. });
  1055. // Disconnect all Meta platforms
  1056. app.delete('/credentials/meta', async () => {
  1057. await deleteCredentials('facebook');
  1058. await deleteCredentials('instagram');
  1059. await deleteCredentials('meta_discovery');
  1060. return { success: true };
  1061. });
  1062. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1063. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1064. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1065. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1066. app.post('/credentials/pinterest-app', async (request, reply) => {
  1067. const { clientId, clientSecret } = request.body || {};
  1068. if (!clientId || !clientSecret) {
  1069. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1070. }
  1071. await setCredentials('pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1072. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1073. return { success: true };
  1074. });
  1075. app.get('/credentials/pinterest-app', async () => {
  1076. const cred = await getCredentials('pinterest_app');
  1077. if (!cred) return { configured: false };
  1078. const plain = decryptToken(cred.clientSecret) || '';
  1079. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1080. });
  1081. app.get('/auth/pinterest/init', async (request, reply) => {
  1082. const cred = await getCredentials('pinterest_app');
  1083. if (!cred?.clientId) {
  1084. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1085. }
  1086. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1087. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1088. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1089. return { url };
  1090. });
  1091. app.get('/auth/pinterest/callback', async (request, reply) => {
  1092. const { code, error: oauthError } = request.query;
  1093. if (oauthError) {
  1094. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1095. }
  1096. if (!code) {
  1097. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1098. }
  1099. try {
  1100. const appCred = await getCredentials('pinterest_app');
  1101. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1102. const clientSecret = decryptToken(appCred.clientSecret);
  1103. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1104. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1105. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1106. const tokenRes = await axios.post(
  1107. PINTEREST_TOKEN_URL,
  1108. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1109. {
  1110. headers: {
  1111. Authorization: `Basic ${basicAuth}`,
  1112. 'Content-Type': 'application/x-www-form-urlencoded',
  1113. },
  1114. timeout: 15000,
  1115. }
  1116. );
  1117. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1118. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1119. const [userRes, boardsRes] = await Promise.all([
  1120. axios.get(`${PINTEREST_API}/user_account`, {
  1121. headers: { Authorization: `Bearer ${access_token}` },
  1122. timeout: 10000,
  1123. }),
  1124. axios.get(`${PINTEREST_API}/boards`, {
  1125. headers: { Authorization: `Bearer ${access_token}` },
  1126. params: { page_size: 100 },
  1127. timeout: 15000,
  1128. }),
  1129. ]);
  1130. const boards = (boardsRes.data.items || []).map((b) => ({
  1131. id: b.id,
  1132. name: b.name,
  1133. privacy: b.privacy,
  1134. selected: false,
  1135. }));
  1136. await setCredentials('pinterest', {
  1137. userId: userRes.data.username,
  1138. username: userRes.data.username,
  1139. displayName: userRes.data.business_name || userRes.data.username,
  1140. avatar: userRes.data.profile_image,
  1141. accessToken: encryptToken(access_token),
  1142. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1143. tokenExpiry,
  1144. boards,
  1145. });
  1146. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1147. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1148. } catch (err) {
  1149. const msg = err.response?.data?.message || err.message;
  1150. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1151. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1152. }
  1153. });
  1154. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1155. const { selectedBoardIds = [] } = request.body || {};
  1156. const cred = await getCredentials('pinterest');
  1157. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1158. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1159. await setCredentials('pinterest', { ...cred, boards });
  1160. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1161. return { success: true, selected: boards.filter((b) => b.selected).length };
  1162. });
  1163. app.delete('/credentials/pinterest', async () => {
  1164. await deleteCredentials('pinterest');
  1165. return { success: true };
  1166. });
  1167. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1168. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1169. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1170. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1171. app.post('/credentials/tiktok-app', async (request, reply) => {
  1172. const { clientKey, clientSecret } = request.body || {};
  1173. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1174. await setCredentials('tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1175. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1176. return { success: true };
  1177. });
  1178. app.get('/credentials/tiktok-app', async () => {
  1179. const cred = await getCredentials('tiktok_app');
  1180. if (!cred?.clientKey) return { configured: false };
  1181. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1182. });
  1183. app.get('/auth/tiktok/init', async (request, reply) => {
  1184. const cred = await getCredentials('tiktok_app');
  1185. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1186. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1187. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1188. const state = crypto.randomBytes(16).toString('hex');
  1189. // Persist PKCE verifier for the callback
  1190. const db = await getDb();
  1191. await db.collection('platform_credentials').updateOne(
  1192. { _id: 'tiktok_pkce' },
  1193. { $set: { codeVerifier, state, createdAt: new Date() } },
  1194. { upsert: true }
  1195. );
  1196. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1197. const scopes = 'user.info.basic,video.list,video.publish';
  1198. const params = new URLSearchParams({
  1199. client_key: cred.clientKey,
  1200. scope: scopes,
  1201. response_type: 'code',
  1202. redirect_uri: redirectUri,
  1203. state,
  1204. code_challenge: codeChallenge,
  1205. code_challenge_method: 'S256',
  1206. });
  1207. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1208. });
  1209. app.get('/auth/tiktok/callback', async (request, reply) => {
  1210. const { code, state, error: oauthError, error_description } = request.query;
  1211. if (oauthError) {
  1212. const msg = error_description || oauthError;
  1213. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1214. }
  1215. if (!code) {
  1216. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1217. }
  1218. try {
  1219. const db = await getDb();
  1220. const pkce = await db.collection('platform_credentials').findOne({ _id: 'tiktok_pkce' });
  1221. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1222. if (state && pkce.state && state !== pkce.state) throw new Error('OAuth state mismatch');
  1223. const appCred = await getCredentials('tiktok_app');
  1224. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1225. const clientSecret = decryptToken(appCred.clientSecret);
  1226. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1227. const tokenRes = await axios.post(
  1228. TIKTOK_TOKEN_URL,
  1229. new URLSearchParams({
  1230. client_key: appCred.clientKey,
  1231. client_secret: clientSecret,
  1232. code,
  1233. grant_type: 'authorization_code',
  1234. redirect_uri: redirectUri,
  1235. code_verifier: pkce.codeVerifier,
  1236. }).toString(),
  1237. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1238. );
  1239. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1240. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1241. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1242. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1243. headers: { Authorization: `Bearer ${access_token}` },
  1244. params: { fields: 'open_id,display_name,avatar_url,username' },
  1245. timeout: 10000,
  1246. });
  1247. const user = userRes.data?.data?.user || {};
  1248. await setCredentials('tiktok', {
  1249. openId: open_id || user.open_id,
  1250. username: user.username || user.display_name,
  1251. displayName: user.display_name,
  1252. avatar: user.avatar_url || null,
  1253. accessToken: encryptToken(access_token),
  1254. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1255. tokenExpiry,
  1256. refreshExpiry,
  1257. });
  1258. // Clean up PKCE temp state
  1259. await db.collection('platform_credentials').deleteOne({ _id: 'tiktok_pkce' });
  1260. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1261. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1262. } catch (err) {
  1263. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1264. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1265. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1266. }
  1267. });
  1268. app.delete('/credentials/tiktok', async () => {
  1269. await deleteCredentials('tiktok');
  1270. return { success: true };
  1271. });
  1272. // ─── Credential Status ────────────────────────────────────────────────────────
  1273. // Aggregate connection status for all DB-managed platforms
  1274. app.get('/credentials', async () => {
  1275. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1276. getCredentials('meta_app'),
  1277. getCredentials('facebook'),
  1278. getCredentials('instagram'),
  1279. getCredentials('pinterest'),
  1280. getCredentials('tiktok'),
  1281. ]);
  1282. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1283. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1284. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1285. return {
  1286. metaApp: { configured: !!(metaApp?.appId) },
  1287. facebook: {
  1288. connected: fbPages.length > 0,
  1289. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1290. },
  1291. instagram: {
  1292. connected: igAccounts.length > 0,
  1293. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1294. },
  1295. pinterest: {
  1296. connected: pinterestBoards.length > 0,
  1297. username: pinterest?.username || null,
  1298. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1299. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1300. },
  1301. tiktok: {
  1302. connected: !!(tiktok?.accessToken),
  1303. username: tiktok?.username || null,
  1304. displayName: tiktok?.displayName || null,
  1305. avatar: tiktok?.avatar || null,
  1306. },
  1307. };
  1308. });
  1309. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1310. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1311. const INDUSTRY_DEFAULTS = {
  1312. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1313. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1314. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1315. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1316. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1317. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1318. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1319. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1320. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1321. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  1322. };
  1323. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  1324. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  1325. // at least `afterMs` milliseconds in the future.
  1326. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  1327. const candidate = new Date(afterMs);
  1328. candidate.setUTCHours(hourUTC, 0, 0, 0);
  1329. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  1330. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  1331. candidate.setUTCDate(candidate.getUTCDate() + 7);
  1332. } else {
  1333. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  1334. }
  1335. return candidate;
  1336. }
  1337. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  1338. app.get('/schedule/suggestions', async (request, reply) => {
  1339. const { platform, accountId } = request.query;
  1340. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  1341. const db = await getDb();
  1342. const query = { platform, ...(accountId && { accountId }) };
  1343. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  1344. let slots;
  1345. let source;
  1346. if (dataPoints >= 10) {
  1347. const agg = await db.collection('post_metrics').aggregate([
  1348. { $match: query },
  1349. { $group: {
  1350. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1351. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1352. count: { $sum: 1 },
  1353. }},
  1354. { $sort: { avgEngagement: -1 } },
  1355. { $limit: 5 },
  1356. ]).toArray();
  1357. slots = agg.map((r) => [r._id.day, r._id.hour]);
  1358. source = 'history';
  1359. } else {
  1360. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  1361. source = 'default';
  1362. }
  1363. // 30-minute lead time so the user has time to finish writing
  1364. const afterMs = Date.now() + 30 * 60 * 1000;
  1365. const suggestions = slots
  1366. .map(([day, hour]) => {
  1367. const dt = nextOccurrence(day, hour, afterMs);
  1368. const h12 = hour % 12 || 12;
  1369. const ampm = hour < 12 ? 'am' : 'pm';
  1370. return {
  1371. utc: dt.toISOString(),
  1372. dayOfWeek: day,
  1373. hour,
  1374. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  1375. };
  1376. })
  1377. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  1378. .slice(0, 4);
  1379. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  1380. return { source, suggestions };
  1381. });
  1382. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  1383. async function crawlFacebookMetrics(db) {
  1384. const fb = await getCredentials('facebook');
  1385. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  1386. if (!pages.length) return { count: 0 };
  1387. let count = 0;
  1388. for (const page of pages) {
  1389. const token = decryptToken(page.accessToken);
  1390. if (!token) continue;
  1391. try {
  1392. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  1393. params: {
  1394. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  1395. limit: 100,
  1396. access_token: token,
  1397. },
  1398. timeout: 30000,
  1399. });
  1400. for (const post of res.data.data || []) {
  1401. const likes = post.reactions?.summary?.total_count || 0;
  1402. const comments = post.comments?.summary?.total_count || 0;
  1403. const shares = post.shares?.count || 0;
  1404. const publishedAt = new Date(post.created_time);
  1405. await db.collection('post_metrics').updateOne(
  1406. { platform: 'facebook', postId: post.id },
  1407. {
  1408. $set: {
  1409. platform: 'facebook',
  1410. accountId: page.id,
  1411. accountName: page.name,
  1412. postId: post.id,
  1413. content: post.message || null,
  1414. publishedAt,
  1415. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  1416. hourOfDay: publishedAt.getUTCHours(),
  1417. dayOfWeek: publishedAt.getUTCDay(),
  1418. fetchedAt: new Date(),
  1419. },
  1420. },
  1421. { upsert: true }
  1422. );
  1423. count++;
  1424. }
  1425. } catch (err) {
  1426. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  1427. }
  1428. }
  1429. return { count };
  1430. }
  1431. async function crawlInstagramMetrics(db) {
  1432. const ig = await getCredentials('instagram');
  1433. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  1434. if (!accounts.length) return { count: 0 };
  1435. let count = 0;
  1436. for (const account of accounts) {
  1437. const token = decryptToken(account.accessToken);
  1438. if (!token) continue;
  1439. try {
  1440. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  1441. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  1442. timeout: 30000,
  1443. });
  1444. for (const media of mediaRes.data.data || []) {
  1445. const likes = media.like_count || 0;
  1446. const comments = media.comments_count || 0;
  1447. const publishedAt = new Date(media.timestamp);
  1448. let views = 0;
  1449. let saves = 0;
  1450. try {
  1451. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  1452. params: { metric: 'reach,saved', access_token: token },
  1453. timeout: 10000,
  1454. });
  1455. for (const ins of insRes.data.data || []) {
  1456. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  1457. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  1458. }
  1459. } catch (_) {}
  1460. await db.collection('post_metrics').updateOne(
  1461. { platform: 'instagram', postId: media.id },
  1462. {
  1463. $set: {
  1464. platform: 'instagram',
  1465. accountId: account.id,
  1466. accountName: account.username,
  1467. postId: media.id,
  1468. content: media.caption || null,
  1469. publishedAt,
  1470. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  1471. hourOfDay: publishedAt.getUTCHours(),
  1472. dayOfWeek: publishedAt.getUTCDay(),
  1473. fetchedAt: new Date(),
  1474. },
  1475. },
  1476. { upsert: true }
  1477. );
  1478. count++;
  1479. }
  1480. } catch (err) {
  1481. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  1482. }
  1483. }
  1484. return { count };
  1485. }
  1486. app.post('/analytics/crawl', async () => {
  1487. const db = await getDb();
  1488. const results = {};
  1489. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  1490. try {
  1491. results[platform] = await crawler(db);
  1492. } catch (err) {
  1493. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  1494. results[platform] = { count: 0, error: err.message };
  1495. }
  1496. }
  1497. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  1498. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  1499. return { success: true, total, byPlatform: results };
  1500. });
  1501. app.get('/analytics/insights', async (request) => {
  1502. const filter = parseAccountFilter(request.query.account);
  1503. const metricsMatch = filter
  1504. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1505. : {};
  1506. const db = await getDb();
  1507. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  1508. if (total === 0) return { empty: true };
  1509. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  1510. db.collection('post_metrics').aggregate([
  1511. { $match: metricsMatch },
  1512. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1513. { $sort: { _id: 1 } },
  1514. ]).toArray(),
  1515. db.collection('post_metrics').aggregate([
  1516. { $match: metricsMatch },
  1517. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1518. { $sort: { _id: 1 } },
  1519. ]).toArray(),
  1520. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  1521. db.collection('post_metrics').aggregate([
  1522. { $match: metricsMatch },
  1523. { $group: {
  1524. _id: '$platform',
  1525. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1526. avgLikes: { $avg: '$metrics.likes' },
  1527. avgComments: { $avg: '$metrics.comments' },
  1528. avgShares: { $avg: '$metrics.shares' },
  1529. totalPosts: { $sum: 1 },
  1530. }},
  1531. { $sort: { avgEngagement: -1 } },
  1532. ]).toArray(),
  1533. db.collection('post_metrics').aggregate([
  1534. { $match: metricsMatch },
  1535. { $group: {
  1536. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1537. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1538. count: { $sum: 1 },
  1539. }},
  1540. ]).toArray(),
  1541. ]);
  1542. const byHour = Array.from({ length: 24 }, (_, h) => {
  1543. const e = byHourRaw.find((r) => r._id === h);
  1544. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1545. });
  1546. const byDay = Array.from({ length: 7 }, (_, d) => {
  1547. const e = byDayRaw.find((r) => r._id === d);
  1548. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1549. });
  1550. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  1551. const day = Math.floor(i / 24);
  1552. const hour = i % 24;
  1553. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  1554. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1555. });
  1556. return {
  1557. empty: false,
  1558. total,
  1559. byHour,
  1560. byDay,
  1561. heatmap,
  1562. topPosts: topPosts.map((p) => ({
  1563. platform: p.platform, accountName: p.accountName, postId: p.postId,
  1564. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  1565. })),
  1566. platformComparison: platformComparison.map((p) => ({
  1567. platform: p._id,
  1568. avgEngagement: Math.round(p.avgEngagement),
  1569. avgLikes: Math.round(p.avgLikes),
  1570. avgComments: Math.round(p.avgComments),
  1571. avgShares: Math.round(p.avgShares),
  1572. totalPosts: p.totalPosts,
  1573. })),
  1574. };
  1575. });
  1576. // ─── Analytics ────────────────────────────────────────────────────────────────
  1577. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  1578. function parseAccountFilter(account) {
  1579. if (!account) return null;
  1580. const idx = account.indexOf(':');
  1581. if (idx === -1) return { platform: account };
  1582. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  1583. }
  1584. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  1585. function sjFilter(filter) {
  1586. if (!filter) return {};
  1587. return {
  1588. 'destinations.platform': filter.platform,
  1589. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1590. };
  1591. }
  1592. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  1593. function ipFilter(filter) {
  1594. if (!filter) return {};
  1595. return {
  1596. 'destinations.platform': filter.platform,
  1597. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1598. };
  1599. }
  1600. app.get('/analytics/summary', async (request) => {
  1601. const filter = parseAccountFilter(request.query.account);
  1602. const db = await getDb();
  1603. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1604. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1605. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  1606. // account filter after $unwind so a job targeting multiple platforms only
  1607. // counts the platform(s) that match the filter.
  1608. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  1609. const [
  1610. schedCompleted, schedFailed,
  1611. immPublished, immFailed,
  1612. recentSched, recentImm,
  1613. schedPlatformRaw, immPlatformRaw,
  1614. schedDayRaw, immDayRaw,
  1615. ] = await Promise.all([
  1616. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  1617. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  1618. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  1619. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  1620. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  1621. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  1622. // Platform breakdown from scheduled_jobs destinations
  1623. db.collection('scheduled_jobs').aggregate([
  1624. { $match: { status: 'completed', ...sjFilter(filter) } },
  1625. { $unwind: '$destinations' },
  1626. ...unwindFilter,
  1627. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  1628. { $sort: { count: -1 } },
  1629. ]).toArray(),
  1630. // Platform breakdown from immediate posts platformResults
  1631. db.collection('posts').aggregate([
  1632. { $match: { type: 'immediate', ...ipFilter(filter) } },
  1633. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  1634. { $unwind: '$results' },
  1635. { $match: { 'results.v.success': true } },
  1636. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  1637. { $group: { _id: '$platform', count: { $sum: 1 } } },
  1638. ]).toArray(),
  1639. // Activity by day from scheduled_jobs (using completedAt)
  1640. db.collection('scheduled_jobs').aggregate([
  1641. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  1642. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  1643. { $sort: { _id: 1 } },
  1644. ]).toArray(),
  1645. // Activity by day from immediate posts
  1646. db.collection('posts').aggregate([
  1647. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  1648. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  1649. { $sort: { _id: 1 } },
  1650. ]).toArray(),
  1651. ]);
  1652. const dayMap = {};
  1653. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1654. dayMap[_id] = (dayMap[_id] || 0) + count;
  1655. }
  1656. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1657. const platformMap = {};
  1658. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1659. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1660. }
  1661. const published = schedCompleted + immPublished;
  1662. const failed = schedFailed + immFailed;
  1663. const total = published + failed;
  1664. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1665. const recentCount = recentSched + recentImm;
  1666. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1667. });
  1668. app.get('/analytics/posts', async (request) => {
  1669. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1670. const skip = parseInt(request.query.skip || '0', 10);
  1671. const filter = parseAccountFilter(request.query.account);
  1672. const db = await getDb();
  1673. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1674. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1675. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1676. db.collection('scheduled_jobs')
  1677. .find(sjMatch)
  1678. .sort({ completedAt: -1, scheduledAt: -1 })
  1679. .skip(skip)
  1680. .limit(limit)
  1681. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1682. .toArray(),
  1683. db.collection('posts')
  1684. .find(ipMatch)
  1685. .sort({ publishedAt: -1 })
  1686. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1687. .toArray(),
  1688. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1689. db.collection('posts').countDocuments(ipMatch),
  1690. ]);
  1691. const normalised = [
  1692. ...scheduledJobs.map((j) => ({
  1693. _id: String(j._id),
  1694. type: 'scheduled',
  1695. content: j.content || null,
  1696. destinations: j.destinations || [],
  1697. platformResults: null,
  1698. status: j.status === 'completed' ? 'published' : 'failed',
  1699. publishedAt: j.completedAt || j.scheduledAt,
  1700. })),
  1701. ...immediatePosts.map((p) => ({
  1702. _id: String(p._id),
  1703. type: 'immediate',
  1704. content: p.content || null,
  1705. destinations: p.destinations || [],
  1706. platformResults: p.platformResults || null,
  1707. status: p.status,
  1708. publishedAt: p.publishedAt,
  1709. })),
  1710. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  1711. .slice(0, limit);
  1712. return { posts: normalised, total: schedTotal + immTotal };
  1713. });
  1714. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  1715. app.get('/hashtag-groups', async () => {
  1716. const db = await getDb();
  1717. const groups = await db.collection('hashtag_groups').find({}).sort({ name: 1 }).toArray();
  1718. return { groups };
  1719. });
  1720. app.post('/hashtag-groups', async (request, reply) => {
  1721. const { name, hashtags } = request.body || {};
  1722. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  1723. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  1724. const db = await getDb();
  1725. const result = await db.collection('hashtag_groups').insertOne({
  1726. name: name.trim(),
  1727. hashtags: [...new Set(tags)],
  1728. createdAt: new Date(),
  1729. updatedAt: new Date(),
  1730. });
  1731. return { success: true, _id: result.insertedId };
  1732. });
  1733. app.put('/hashtag-groups/:id', async (request, reply) => {
  1734. const { id } = request.params;
  1735. const { name, hashtags } = request.body || {};
  1736. const update = { updatedAt: new Date() };
  1737. if (name?.trim()) update.name = name.trim();
  1738. if (hashtags) {
  1739. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  1740. update.hashtags = [...new Set(tags)];
  1741. }
  1742. const db = await getDb();
  1743. let oid;
  1744. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1745. await db.collection('hashtag_groups').updateOne({ _id: oid }, { $set: update });
  1746. return { success: true };
  1747. });
  1748. app.delete('/hashtag-groups/:id', async (request, reply) => {
  1749. const { id } = request.params;
  1750. const db = await getDb();
  1751. let oid;
  1752. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1753. await db.collection('hashtag_groups').deleteOne({ _id: oid });
  1754. return { success: true };
  1755. });
  1756. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  1757. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  1758. function extractHashtags(text) {
  1759. if (!text) return [];
  1760. const tags = [];
  1761. let m;
  1762. HASHTAG_RE.lastIndex = 0;
  1763. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  1764. return tags;
  1765. }
  1766. function gradeHashtag(count, avgEngagement) {
  1767. if (count >= 5 && avgEngagement >= 10) return 'A';
  1768. if (count >= 3 && avgEngagement >= 3) return 'B';
  1769. if (count >= 2) return 'C';
  1770. return 'D';
  1771. }
  1772. app.post('/hashtags/scrape', async () => {
  1773. const db = await getDb();
  1774. // Collect hashtag → { count, totalEngagement, platforms }
  1775. const tagMap = {};
  1776. function touch(tag, platform, engagement) {
  1777. if (!tagMap[tag]) tagMap[tag] = { count: 0, totalEngagement: 0, platforms: new Set() };
  1778. tagMap[tag].count++;
  1779. tagMap[tag].totalEngagement += engagement;
  1780. tagMap[tag].platforms.add(platform);
  1781. }
  1782. // Scan published posts
  1783. const posts = await db.collection('posts').find({}, { projection: { content: 1, destinations: 1, platformResults: 1 } }).toArray();
  1784. const postMetrics = await db.collection('post_metrics').find({}).toArray();
  1785. // Build engagement lookup keyed by content fingerprint (first 100 chars)
  1786. const metricsByContent = {};
  1787. for (const m of postMetrics) {
  1788. if (m.content) {
  1789. const key = m.content.slice(0, 100).toLowerCase().trim();
  1790. metricsByContent[key] = (metricsByContent[key] || 0) + m.metrics.engagementTotal;
  1791. }
  1792. }
  1793. for (const post of posts) {
  1794. const tags = extractHashtags(post.content || '');
  1795. const engagement = post.content
  1796. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  1797. : 0;
  1798. const platforms = (post.destinations || []).map((d) => d.platform);
  1799. for (const tag of tags) {
  1800. for (const platform of platforms.length ? platforms : ['unknown']) {
  1801. touch(tag, platform, engagement / Math.max(tags.length, 1));
  1802. }
  1803. }
  1804. }
  1805. // Also scan feed items
  1806. const feeds = await db.collection('feeds').find({}, { projection: { content: 1, platform: 1, metrics: 1 } }).toArray();
  1807. for (const item of feeds) {
  1808. const tags = extractHashtags(item.content || '');
  1809. const engagement = (item.metrics?.likes || 0) + (item.metrics?.comments || 0) + (item.metrics?.shares || 0);
  1810. for (const tag of tags) {
  1811. touch(tag, item.platform || 'unknown', engagement / Math.max(tags.length, 1));
  1812. }
  1813. }
  1814. // Upsert hashtag_stats
  1815. let scraped = 0;
  1816. for (const [tag, data] of Object.entries(tagMap)) {
  1817. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  1818. await db.collection('hashtag_stats').updateOne(
  1819. { _id: tag },
  1820. {
  1821. $set: {
  1822. count: data.count,
  1823. avgEngagement: Math.round(avgEngagement * 10) / 10,
  1824. grade: gradeHashtag(data.count, avgEngagement),
  1825. platforms: [...data.platforms],
  1826. lastScraped: new Date(),
  1827. },
  1828. },
  1829. { upsert: true }
  1830. );
  1831. scraped++;
  1832. }
  1833. app.log.info({ action: 'hashtag_scrape', outcome: 'success', scraped });
  1834. return { success: true, scraped };
  1835. });
  1836. app.get('/hashtags/stats', async (request) => {
  1837. const sortBy = request.query.sort || 'count';
  1838. const db = await getDb();
  1839. const sortField = sortBy === 'engagement' ? 'avgEngagement' : 'count';
  1840. const stats = await db.collection('hashtag_stats')
  1841. .find({})
  1842. .sort({ [sortField]: -1 })
  1843. .limit(200)
  1844. .toArray();
  1845. return { stats };
  1846. });
  1847. app.post('/hashtags/ai-suggest', async (request, reply) => {
  1848. const { accountKey, topTags = [], count = 20 } = request.body || {};
  1849. let profileCtx = '';
  1850. if (accountKey) {
  1851. try {
  1852. const db = await getDb();
  1853. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  1854. if (profile) {
  1855. const parts = [];
  1856. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  1857. if (profile.description) parts.push(`Description: ${profile.description}`);
  1858. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  1859. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  1860. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  1861. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  1862. profileCtx = parts.join('\n');
  1863. }
  1864. } catch (_) {}
  1865. }
  1866. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  1867. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  1868. const prompt = [
  1869. `Suggest ${count} high-performing hashtags for a social media account.`,
  1870. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  1871. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  1872. `\nReturn exactly ${count} unique hashtags as a space-separated list. Mix popular and niche tags. Include a variety of sizes (broad, medium, niche). Example: #photography #naturephotography #landscapephoto`,
  1873. ].filter(Boolean).join('');
  1874. try {
  1875. const pconf = await getActiveProviderConfig();
  1876. const model = pconf.model;
  1877. let text = '';
  1878. if (pconf.provider === 'ollama') {
  1879. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  1880. text = res.data.response;
  1881. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1882. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  1883. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1884. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1885. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  1886. text = res.data.choices[0]?.message?.content || '';
  1887. } else if (pconf.provider === 'gemini') {
  1888. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  1889. const res = await axios.post(
  1890. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1891. { contents: buildGeminiContents(prompt, system) },
  1892. { timeout: 60000 },
  1893. );
  1894. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1895. } else {
  1896. return reply.code(400).send({ error: 'AI not configured' });
  1897. }
  1898. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  1899. return { success: true, hashtags: tags };
  1900. } catch (err) {
  1901. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  1902. }
  1903. });
  1904. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  1905. async function extractTextFromUrl(url) {
  1906. try {
  1907. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  1908. const html = res.data || '';
  1909. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  1910. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  1911. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  1912. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  1913. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  1914. } catch {
  1915. return '';
  1916. }
  1917. }
  1918. async function scrapeBluesky(profileUrl) {
  1919. try {
  1920. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  1921. if (!handle) return '';
  1922. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  1923. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  1924. return posts.join('\n').slice(0, 3000);
  1925. } catch {
  1926. return '';
  1927. }
  1928. }
  1929. async function scrapeMastodon(profileUrl) {
  1930. try {
  1931. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  1932. if (!m) return '';
  1933. const [, instance, username] = m;
  1934. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  1935. const accountId = lookupRes.data?.id;
  1936. if (!accountId) return '';
  1937. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  1938. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  1939. return posts.join('\n').slice(0, 3000);
  1940. } catch {
  1941. return '';
  1942. }
  1943. }
  1944. async function runCompetitorScrape(competitorId) {
  1945. const db = await getDb();
  1946. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  1947. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  1948. const newItems = [];
  1949. if (competitor.websiteUrl) {
  1950. const text = await extractTextFromUrl(competitor.websiteUrl);
  1951. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  1952. }
  1953. const socialEntries = Object.entries(competitor.socialUrls || {});
  1954. for (const [platform, url] of socialEntries) {
  1955. if (!url) continue;
  1956. let text = '';
  1957. if (platform === 'bluesky') text = await scrapeBluesky(url);
  1958. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  1959. else text = await extractTextFromUrl(url);
  1960. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  1961. }
  1962. const existing = competitor.scrapedContent || [];
  1963. const combined = [...newItems, ...existing].slice(0, 20);
  1964. await db.collection('competitors').updateOne(
  1965. { _id: new ObjectId(competitorId) },
  1966. { $set: { scrapedContent: combined, lastScraped: new Date(), updatedAt: new Date() } },
  1967. );
  1968. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  1969. }
  1970. async function buildCompetitorSystemSuffix() {
  1971. try {
  1972. const db = await getDb();
  1973. const competitors = await db.collection('competitors').find({ aiSummary: { $nin: ['', null] } }).toArray();
  1974. if (!competitors.length) return '';
  1975. const lines = competitors.map((c) => `- ${c.name}: ${c.aiSummary}`).join('\n');
  1976. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  1977. } catch {
  1978. return '';
  1979. }
  1980. }
  1981. // List competitors
  1982. app.get('/competitors', async (request, reply) => {
  1983. const db = await getDb();
  1984. const list = await db.collection('competitors').find({}).sort({ createdAt: 1 }).toArray();
  1985. return list;
  1986. });
  1987. // Add competitor (max 2)
  1988. app.post('/competitors', async (request, reply) => {
  1989. const db = await getDb();
  1990. const count = await db.collection('competitors').countDocuments();
  1991. if (count >= 2) return reply.code(400).send({ error: 'Maximum 2 competitors allowed' });
  1992. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  1993. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  1994. const now = new Date();
  1995. const result = await db.collection('competitors').insertOne({
  1996. name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  1997. });
  1998. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  1999. return doc;
  2000. });
  2001. // Update competitor
  2002. app.put('/competitors/:id', async (request, reply) => {
  2003. const db = await getDb();
  2004. const { name, websiteUrl, socialUrls } = request.body || {};
  2005. const updates = { updatedAt: new Date() };
  2006. if (name !== undefined) updates.name = name;
  2007. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  2008. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  2009. await db.collection('competitors').updateOne({ _id: new ObjectId(request.params.id) }, { $set: updates });
  2010. const doc = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2011. return doc;
  2012. });
  2013. // Delete competitor
  2014. app.delete('/competitors/:id', async (request, reply) => {
  2015. const db = await getDb();
  2016. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id) });
  2017. return { success: true };
  2018. });
  2019. // Scrape one competitor
  2020. app.post('/competitors/:id/scrape', async (request, reply) => {
  2021. try {
  2022. const result = await runCompetitorScrape(request.params.id);
  2023. return { success: result.ok, sources: result.sources, message: result.message };
  2024. } catch (err) {
  2025. return reply.code(500).send({ error: 'Scrape failed', detail: err.message });
  2026. }
  2027. });
  2028. // Scrape all competitors (called by scheduler)
  2029. app.post('/competitors/scrape-all', async (request, reply) => {
  2030. const db = await getDb();
  2031. const all = await db.collection('competitors').find({}).toArray();
  2032. const results = [];
  2033. for (const c of all) {
  2034. const r = await runCompetitorScrape(c._id.toString());
  2035. results.push({ id: c._id.toString(), name: c.name, ...r });
  2036. }
  2037. return { success: true, results };
  2038. });
  2039. // Summarize competitor content with AI
  2040. app.post('/competitors/:id/summarize', async (request, reply) => {
  2041. const db = await getDb();
  2042. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2043. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2044. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  2045. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  2046. const system = 'You are a competitive intelligence analyst. Be concise.';
  2047. const prompt = `Analyse the following content from "${competitor.name}" and summarise their key themes, messaging style, and content strategy in 2-3 sentences. Focus on topics, tone, and positioning.\n\n${content}`;
  2048. try {
  2049. const pconf = await getActiveProviderConfig();
  2050. const model = pconf.model;
  2051. let summary = '';
  2052. if (pconf.provider === 'ollama') {
  2053. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2054. summary = res.data.response;
  2055. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2056. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2057. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2058. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2059. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2060. summary = res.data.choices[0]?.message?.content || '';
  2061. } else if (pconf.provider === 'gemini') {
  2062. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2063. const res = await axios.post(
  2064. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2065. { contents: buildGeminiContents(prompt, system) },
  2066. { timeout: 180000 },
  2067. );
  2068. summary = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2069. } else {
  2070. return reply.code(400).send({ error: 'AI not configured' });
  2071. }
  2072. summary = summary.trim();
  2073. await db.collection('competitors').updateOne(
  2074. { _id: new ObjectId(request.params.id) },
  2075. { $set: { aiSummary: summary, updatedAt: new Date() } },
  2076. );
  2077. return { success: true, aiSummary: summary };
  2078. } catch (err) {
  2079. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  2080. }
  2081. });
  2082. // Extract keywords from scraped content using AI (item 34)
  2083. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  2084. const db = await getDb();
  2085. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2086. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2087. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  2088. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  2089. const system = 'You are an SEO and content strategist. Return only valid JSON.';
  2090. const prompt = `Analyse the following content from "${competitor.name}" and extract the top 20 keywords and key phrases they appear to be targeting or ranking for. Include both short-tail and long-tail keywords.\n\nContent:\n${content}\n\nReturn ONLY a JSON array of strings, e.g. ["keyword one", "keyword two"]. No explanation, no markdown.`;
  2091. try {
  2092. const pconf = await getActiveProviderConfig();
  2093. const model = pconf.model;
  2094. let text = '';
  2095. if (pconf.provider === 'ollama') {
  2096. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2097. text = res.data.response;
  2098. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2099. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2100. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2101. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2102. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2103. text = res.data.choices[0]?.message?.content || '';
  2104. } else if (pconf.provider === 'gemini') {
  2105. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2106. const res = await axios.post(
  2107. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2108. { contents: buildGeminiContents(prompt, system) },
  2109. { timeout: 120000 },
  2110. );
  2111. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2112. } else {
  2113. return reply.code(400).send({ error: 'AI not configured' });
  2114. }
  2115. let keywords = [];
  2116. try {
  2117. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2118. keywords = JSON.parse(jsonStr);
  2119. if (!Array.isArray(keywords)) keywords = [];
  2120. keywords = keywords.filter((k) => typeof k === 'string').slice(0, 20);
  2121. } catch {
  2122. keywords = [];
  2123. }
  2124. await db.collection('competitors').updateOne(
  2125. { _id: new ObjectId(request.params.id) },
  2126. { $set: { keywords, updatedAt: new Date() } },
  2127. );
  2128. return { success: true, keywords };
  2129. } catch (err) {
  2130. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  2131. }
  2132. });
  2133. module.exports = app;