server.js 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686
  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. // In-memory job state for async competitor scrapes.
  19. // Max 2 competitors, scrapes complete in seconds — no persistence needed.
  20. const activeScrapeJobs = new Map();
  21. fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  22. app.register(multipart, { limits: { fileSize: MAX_FILE_SIZE } });
  23. const GRAPH_API = 'https://graph.facebook.com/v22.0';
  24. // The public base URL of this app (used for OAuth redirect_uri)
  25. const APP_BASE_URL = process.env.APP_BASE_URL || 'http://localhost:8081';
  26. // ─── CORS ────────────────────────────────────────────────────────────────────
  27. app.addHook('onSend', async (request, reply) => {
  28. reply.header('Access-Control-Allow-Origin', '*');
  29. reply.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  30. reply.header('Access-Control-Allow-Headers', 'Content-Type');
  31. });
  32. app.options('*', async (request, reply) => {
  33. reply.code(204).send();
  34. });
  35. // ─── Helpers ─────────────────────────────────────────────────────────────────
  36. async function getCredentials(id) {
  37. const db = await getDb();
  38. return db.collection('platform_credentials').findOne({ _id: id });
  39. }
  40. async function setCredentials(id, data) {
  41. const db = await getDb();
  42. await db.collection('platform_credentials').updateOne(
  43. { _id: id },
  44. { $set: { _id: id, ...data, updatedAt: new Date() } },
  45. { upsert: true }
  46. );
  47. }
  48. async function deleteCredentials(id) {
  49. const db = await getDb();
  50. await db.collection('platform_credentials').deleteOne({ _id: id });
  51. }
  52. // ─── Media Upload & Library ───────────────────────────────────────────────────
  53. app.post('/upload', async (request, reply) => {
  54. const folder = request.query.folder || null;
  55. const data = await request.file();
  56. if (!data) return reply.code(400).send({ error: 'No file provided' });
  57. const ext = path.extname(data.filename).toLowerCase();
  58. if (!ALLOWED_EXTENSIONS.has(ext)) {
  59. data.file.resume();
  60. return reply.code(400).send({ error: `File type "${ext}" is not allowed. Allowed: jpg, jpeg, png, gif, webp, mp4, mov, avi` });
  61. }
  62. const filename = `${crypto.randomUUID()}${ext}`;
  63. const filepath = path.join(UPLOAD_DIR, filename);
  64. try {
  65. await pipeline(data.file, fs.createWriteStream(filepath));
  66. } catch (err) {
  67. app.log.error({ action: 'media_upload', outcome: 'failure', err: err.message });
  68. return reply.code(500).send({ error: 'Failed to save file' });
  69. }
  70. const stat = fs.statSync(filepath);
  71. const record = {
  72. filename,
  73. originalName: data.filename,
  74. url: `/media/${filename}`,
  75. mimetype: data.mimetype,
  76. size: stat.size,
  77. folder: folder || null,
  78. uploadedAt: new Date(),
  79. };
  80. try {
  81. const db = await getDb();
  82. await db.collection('media_files').insertOne(record);
  83. } catch (err) {
  84. app.log.error({ action: 'media_metadata_save', outcome: 'failure', err: err.message });
  85. }
  86. return { url: record.url, filename, originalName: data.filename, mimetype: data.mimetype, size: stat.size, folder: record.folder };
  87. });
  88. // List uploaded media files, newest first; optionally filter by folder
  89. // folder=__none__ → unorganized (null/missing); folder=<name> → that folder; omit → all
  90. app.get('/media-library', async (request) => {
  91. const db = await getDb();
  92. const { folder } = request.query;
  93. const query = {};
  94. if (folder === '__none__') {
  95. query.$or = [{ folder: { $exists: false } }, { folder: null }, { folder: '' }];
  96. } else if (folder) {
  97. query.folder = folder;
  98. }
  99. const files = await db.collection('media_files').find(query).sort({ uploadedAt: -1 }).toArray();
  100. return { files };
  101. });
  102. // List custom folders with per-folder file counts
  103. app.get('/media-folders', async () => {
  104. const db = await getDb();
  105. const [folders, counts] = await Promise.all([
  106. db.collection('media_folders').find({}).sort({ createdAt: 1 }).toArray(),
  107. db.collection('media_files').aggregate([
  108. { $group: { _id: { $ifNull: ['$folder', '__none__'] }, count: { $sum: 1 } } },
  109. ]).toArray(),
  110. ]);
  111. const countMap = Object.fromEntries(counts.map((c) => [c._id, c.count]));
  112. const total = counts.reduce((s, c) => s + c.count, 0);
  113. return {
  114. folders: folders.map((f) => ({ name: f.name, count: countMap[f.name] || 0 })),
  115. totalCount: total,
  116. unorganizedCount: countMap['__none__'] || 0,
  117. folderCounts: countMap,
  118. };
  119. });
  120. // Create a custom folder
  121. app.post('/media-folders', async (request, reply) => {
  122. const { name } = request.body || {};
  123. if (!name?.trim()) return reply.code(400).send({ error: 'Folder name is required' });
  124. const trimmed = name.trim();
  125. const db = await getDb();
  126. if (await db.collection('media_folders').findOne({ name: trimmed })) {
  127. return reply.code(409).send({ error: 'Folder already exists' });
  128. }
  129. await db.collection('media_folders').insertOne({ name: trimmed, createdAt: new Date() });
  130. return { name: trimmed };
  131. });
  132. // Delete a custom folder; files in it become unorganized
  133. app.delete('/media-folders/:name', async (request, reply) => {
  134. const name = decodeURIComponent(request.params.name);
  135. const db = await getDb();
  136. await db.collection('media_folders').deleteOne({ name });
  137. await db.collection('media_files').updateMany({ folder: name }, { $set: { folder: null } });
  138. return { success: true };
  139. });
  140. // Update a file's folder assignment
  141. app.patch('/media/:filename', async (request, reply) => {
  142. const { filename } = request.params;
  143. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  144. return reply.code(400).send({ error: 'Invalid filename' });
  145. }
  146. const { folder } = request.body || {};
  147. const db = await getDb();
  148. const result = await db.collection('media_files').updateOne(
  149. { filename },
  150. { $set: { folder: folder || null } },
  151. );
  152. if (!result.matchedCount) return reply.code(404).send({ error: 'File not found' });
  153. return { success: true };
  154. });
  155. // Delete a media file from disk and database
  156. app.delete('/media/:filename', async (request, reply) => {
  157. const { filename } = request.params;
  158. // Prevent path traversal
  159. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  160. return reply.code(400).send({ error: 'Invalid filename' });
  161. }
  162. const filepath = path.join(UPLOAD_DIR, filename);
  163. try {
  164. fs.unlinkSync(filepath);
  165. } catch (err) {
  166. if (err.code !== 'ENOENT') {
  167. app.log.error({ action: 'media_delete', outcome: 'failure', err: err.message });
  168. return reply.code(500).send({ error: 'Failed to delete file' });
  169. }
  170. // Already gone from disk — still clean up DB record
  171. }
  172. const db = await getDb();
  173. await db.collection('media_files').deleteOne({ filename });
  174. return { success: true };
  175. });
  176. // ─── Drafts ──────────────────────────────────────────────────────────────────
  177. app.post('/drafts', async (request, reply) => {
  178. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  179. const db = await getDb();
  180. const now = new Date();
  181. const result = await db.collection('drafts').insertOne({
  182. content, mediaUrl, scheduledAt, destinations, createdAt: now, updatedAt: now,
  183. });
  184. const draft = await db.collection('drafts').findOne({ _id: result.insertedId });
  185. return reply.code(201).send(draft);
  186. });
  187. app.get('/drafts', async () => {
  188. const db = await getDb();
  189. const drafts = await db.collection('drafts').find({}).sort({ updatedAt: -1 }).toArray();
  190. return { drafts };
  191. });
  192. app.get('/drafts/:id', async (request, reply) => {
  193. const { id } = request.params;
  194. let oid;
  195. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  196. const db = await getDb();
  197. const draft = await db.collection('drafts').findOne({ _id: oid });
  198. if (!draft) return reply.code(404).send({ error: 'Draft not found' });
  199. return draft;
  200. });
  201. app.put('/drafts/:id', async (request, reply) => {
  202. const { id } = request.params;
  203. let oid;
  204. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  205. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  206. const db = await getDb();
  207. const result = await db.collection('drafts').updateOne(
  208. { _id: oid },
  209. { $set: { content, mediaUrl, scheduledAt, destinations, updatedAt: new Date() } }
  210. );
  211. if (!result.matchedCount) return reply.code(404).send({ error: 'Draft not found' });
  212. return { success: true };
  213. });
  214. app.delete('/drafts/:id', async (request, reply) => {
  215. const { id } = request.params;
  216. let oid;
  217. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  218. const db = await getDb();
  219. await db.collection('drafts').deleteOne({ _id: oid });
  220. return { success: true };
  221. });
  222. // ─── Meta Token Expiry & Auto-Refresh ────────────────────────────────────────
  223. let _tokenExpiryCache = null;
  224. let _tokenExpiryCacheAt = 0;
  225. const TOKEN_EXPIRY_TTL = 60 * 60 * 1000; // 1 hour
  226. const TOKEN_REFRESH_THRESHOLD_DAYS = 7; // refresh when ≤ this many days remain
  227. app.get('/meta/token-expiry', async (request, reply) => {
  228. if (_tokenExpiryCache && Date.now() - _tokenExpiryCacheAt < TOKEN_EXPIRY_TTL) {
  229. return _tokenExpiryCache;
  230. }
  231. const appCred = await getCredentials('meta_app');
  232. if (!appCred?.appId || !appCred?.appSecret) return { accounts: [] };
  233. const plainAppSecret = decryptToken(appCred.appSecret);
  234. if (!plainAppSecret) return { accounts: [] };
  235. const ig = await getCredentials('instagram');
  236. const selectedAccounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  237. if (!selectedAccounts.length) return { accounts: [] };
  238. const appToken = `${appCred.appId}|${plainAppSecret}`;
  239. const accounts = [];
  240. for (const account of selectedAccounts) {
  241. const plainToken = decryptToken(account.accessToken);
  242. if (!plainToken) continue;
  243. try {
  244. const res = await axios.get(`${GRAPH_API}/debug_token`, {
  245. params: { input_token: plainToken, access_token: appToken },
  246. timeout: 10000,
  247. });
  248. const data = res.data.data;
  249. const expiresAt = data.expires_at ? new Date(data.expires_at * 1000).toISOString() : null;
  250. const daysLeft = expiresAt
  251. ? Math.ceil((new Date(expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
  252. : null;
  253. accounts.push({ id: account.id, username: account.username, expiresAt, daysLeft, isValid: !!data.is_valid });
  254. } catch (err) {
  255. app.log.warn({ action: 'token_expiry_check', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  256. }
  257. }
  258. _tokenExpiryCache = { accounts, checkedAt: new Date().toISOString() };
  259. _tokenExpiryCacheAt = Date.now();
  260. return _tokenExpiryCache;
  261. });
  262. // Refresh Instagram long-lived tokens that are within TOKEN_REFRESH_THRESHOLD_DAYS of expiry.
  263. // Called by the scheduler's daily BullMQ job; can also be triggered manually from Settings.
  264. app.post('/meta/token-refresh', async (request, reply) => {
  265. const appCred = await getCredentials('meta_app');
  266. if (!appCred?.appId || !appCred?.appSecret) {
  267. return reply.code(400).send({ success: false, error: 'Meta app credentials not configured' });
  268. }
  269. const plainAppSecret = decryptToken(appCred.appSecret);
  270. if (!plainAppSecret) {
  271. return reply.code(500).send({ success: false, error: 'Failed to decrypt app secret' });
  272. }
  273. const ig = await getCredentials('instagram');
  274. const allAccounts = ig?.accounts || [];
  275. const selectedAccounts = allAccounts.filter((a) => a.selected && a.accessToken);
  276. if (!selectedAccounts.length) {
  277. return { success: true, refreshed: 0, skipped: 0, errors: 0 };
  278. }
  279. const appToken = `${appCred.appId}|${plainAppSecret}`;
  280. const refreshed = [];
  281. const skipped = [];
  282. const errors = [];
  283. for (const account of selectedAccounts) {
  284. const plainToken = decryptToken(account.accessToken);
  285. if (!plainToken) {
  286. errors.push({ username: account.username, error: 'decrypt_failed' });
  287. continue;
  288. }
  289. // Check current token expiry via debug_token
  290. let daysLeft = null;
  291. try {
  292. const debugRes = await axios.get(`${GRAPH_API}/debug_token`, {
  293. params: { input_token: plainToken, access_token: appToken },
  294. timeout: 10000,
  295. });
  296. const data = debugRes.data.data;
  297. if (!data.is_valid) {
  298. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'skip', reason: 'invalid_token' });
  299. errors.push({ username: account.username, error: 'token_invalid' });
  300. continue;
  301. }
  302. // expires_at is a Unix timestamp; null means never-expiring (page token etc.)
  303. daysLeft = data.expires_at
  304. ? Math.ceil((data.expires_at * 1000 - Date.now()) / (1000 * 60 * 60 * 24))
  305. : null;
  306. } catch (err) {
  307. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, step: 'debug_token', outcome: 'failure', err: err.message });
  308. errors.push({ username: account.username, error: err.message });
  309. continue;
  310. }
  311. // Token never expires or has plenty of time — skip
  312. if (daysLeft !== null && daysLeft > TOKEN_REFRESH_THRESHOLD_DAYS) {
  313. skipped.push({ username: account.username, daysLeft });
  314. continue;
  315. }
  316. // Refresh: exchange current long-lived token for a new one
  317. try {
  318. const refreshRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  319. params: {
  320. grant_type: 'fb_exchange_token',
  321. client_id: appCred.appId,
  322. client_secret: plainAppSecret,
  323. fb_exchange_token: plainToken,
  324. },
  325. timeout: 15000,
  326. });
  327. // Mutates the element inside allAccounts (same object reference)
  328. account.accessToken = encryptToken(refreshRes.data.access_token);
  329. refreshed.push({ username: account.username, previousDaysLeft: daysLeft });
  330. app.log.info({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'success', previousDaysLeft: daysLeft });
  331. } catch (err) {
  332. app.log.error({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  333. errors.push({ username: account.username, error: err.message });
  334. }
  335. }
  336. if (refreshed.length > 0) {
  337. await setCredentials('instagram', { accounts: allAccounts });
  338. _tokenExpiryCache = null; // force fresh expiry check on next poll
  339. }
  340. app.log.info({ action: 'token_refresh', platform: 'meta', outcome: 'complete', refreshed: refreshed.length, skipped: skipped.length, errors: errors.length });
  341. return { success: true, refreshed: refreshed.length, skipped: skipped.length, errors: errors.length };
  342. });
  343. // ─── Account Profiles ────────────────────────────────────────────────────────
  344. app.get('/profiles', async () => {
  345. const db = await getDb();
  346. const profiles = await db.collection('account_profiles').find({}).toArray();
  347. return { profiles };
  348. });
  349. app.get('/profiles/:accountKey', async (request, reply) => {
  350. const { accountKey } = request.params;
  351. const db = await getDb();
  352. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  353. return profile ?? { _id: accountKey };
  354. });
  355. app.put('/profiles/:accountKey', async (request, reply) => {
  356. const { accountKey } = request.params;
  357. const {
  358. businessName = '', description = '', websiteUrl = '', industry = '',
  359. targetAudience = '', toneOfVoice = '', keywords = '', hashtags = '',
  360. postingGuidelines = '',
  361. } = request.body || {};
  362. const db = await getDb();
  363. await db.collection('account_profiles').updateOne(
  364. { _id: accountKey },
  365. { $set: { businessName, description, websiteUrl, industry, targetAudience, toneOfVoice, keywords, hashtags, postingGuidelines, updatedAt: new Date() } },
  366. { upsert: true }
  367. );
  368. return { success: true };
  369. });
  370. // ─── AI / Multi-provider ─────────────────────────────────────────────────────
  371. const DEFAULT_OLLAMA_ENDPOINT = process.env.OLLAMA_ENDPOINT || 'http://ollama:11434';
  372. const DEFAULT_OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2';
  373. const PROVIDER_MODELS = {
  374. openai: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-3.5-turbo'],
  375. groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768', 'gemma2-9b-it'],
  376. gemini: ['gemini-2.0-flash', 'gemini-1.5-flash', 'gemini-1.5-pro'],
  377. };
  378. const PROVIDER_BASE_URLS = {
  379. openai: 'https://api.openai.com/v1',
  380. groq: 'https://api.groq.com/openai/v1',
  381. };
  382. // Returns decrypted runtime config for the currently active provider
  383. async function getActiveProviderConfig() {
  384. const aiConfig = await getCredentials('ai_config');
  385. const provider = aiConfig?.provider || 'ollama';
  386. if (provider === 'openai' || provider === 'groq') {
  387. const doc = await getCredentials(`${provider}_config`);
  388. return {
  389. provider,
  390. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  391. model: doc?.model || PROVIDER_MODELS[provider][0],
  392. baseUrl: PROVIDER_BASE_URLS[provider],
  393. };
  394. }
  395. if (provider === 'gemini') {
  396. const doc = await getCredentials('gemini_config');
  397. return {
  398. provider,
  399. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  400. model: doc?.model || PROVIDER_MODELS.gemini[0],
  401. };
  402. }
  403. return {
  404. provider: 'ollama',
  405. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  406. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  407. visionModel: aiConfig?.visionModel || 'llava',
  408. };
  409. }
  410. function buildOpenAIMessages(prompt, system) {
  411. const messages = [];
  412. if (system) messages.push({ role: 'system', content: system });
  413. messages.push({ role: 'user', content: prompt });
  414. return messages;
  415. }
  416. // Gemini encodes system as a leading user/model conversation pair
  417. function buildGeminiContents(prompt, system) {
  418. const contents = [];
  419. if (system) {
  420. contents.push({ role: 'user', parts: [{ text: system }] });
  421. contents.push({ role: 'model', parts: [{ text: 'Understood.' }] });
  422. }
  423. contents.push({ role: 'user', parts: [{ text: prompt }] });
  424. return contents;
  425. }
  426. app.get('/ai/config', async () => {
  427. const config = await getCredentials('ai_config');
  428. return {
  429. provider: config?.provider || 'ollama',
  430. endpoint: config?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  431. model: config?.model || DEFAULT_OLLAMA_MODEL,
  432. visionModel: config?.visionModel || 'llava',
  433. enabled: config?.enabled ?? true,
  434. };
  435. });
  436. app.put('/ai/config', async (request, reply) => {
  437. const { provider = 'ollama', endpoint, model, visionModel = 'llava', enabled = true } = request.body || {};
  438. if (provider === 'ollama' && !endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  439. await setCredentials('ai_config', { provider, endpoint, model, visionModel, enabled });
  440. return { success: true };
  441. });
  442. // ─── Provider management routes ───────────────────────────────────────────────
  443. app.get('/ai/providers', async () => {
  444. const aiConfig = await getCredentials('ai_config');
  445. const active = aiConfig?.provider || 'ollama';
  446. const [openaiDoc, groqDoc, geminiDoc] = await Promise.all([
  447. getCredentials('openai_config'),
  448. getCredentials('groq_config'),
  449. getCredentials('gemini_config'),
  450. ]);
  451. return {
  452. active,
  453. providers: [
  454. {
  455. name: 'ollama',
  456. configured: true,
  457. active: active === 'ollama',
  458. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  459. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  460. visionModel: aiConfig?.visionModel || 'llava',
  461. },
  462. {
  463. name: 'openai',
  464. configured: !!openaiDoc?.apiKey,
  465. active: active === 'openai',
  466. model: openaiDoc?.model || PROVIDER_MODELS.openai[0],
  467. apiKeyHint: openaiDoc?.apiKey ? `sk-...${decryptToken(openaiDoc.apiKey).slice(-4)}` : null,
  468. },
  469. {
  470. name: 'groq',
  471. configured: !!groqDoc?.apiKey,
  472. active: active === 'groq',
  473. model: groqDoc?.model || PROVIDER_MODELS.groq[0],
  474. apiKeyHint: groqDoc?.apiKey ? `gsk_...${decryptToken(groqDoc.apiKey).slice(-4)}` : null,
  475. },
  476. {
  477. name: 'gemini',
  478. configured: !!geminiDoc?.apiKey,
  479. active: active === 'gemini',
  480. model: geminiDoc?.model || PROVIDER_MODELS.gemini[0],
  481. apiKeyHint: geminiDoc?.apiKey ? `AIza...${decryptToken(geminiDoc.apiKey).slice(-4)}` : null,
  482. },
  483. ],
  484. };
  485. });
  486. // PUT /ai/provider/:name — save credentials and optionally set as active
  487. // ollama body: { endpoint, model, visionModel, setActive? }
  488. // others body: { apiKey, model, setActive? }
  489. app.put('/ai/provider/:name', async (request, reply) => {
  490. const { name } = request.params;
  491. const { apiKey, model, endpoint, visionModel, setActive = false } = request.body || {};
  492. if (name === 'ollama') {
  493. if (!endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  494. const existing = await getCredentials('ai_config') || {};
  495. await setCredentials('ai_config', {
  496. ...existing,
  497. provider: setActive ? 'ollama' : (existing.provider || 'ollama'),
  498. endpoint,
  499. model: model || DEFAULT_OLLAMA_MODEL,
  500. visionModel: visionModel || 'llava',
  501. });
  502. } else if (['openai', 'groq', 'gemini'].includes(name)) {
  503. if (!apiKey) return reply.code(400).send({ error: 'apiKey is required' });
  504. await setCredentials(`${name}_config`, {
  505. apiKey: encryptToken(apiKey),
  506. model: model || PROVIDER_MODELS[name][0],
  507. });
  508. if (setActive) {
  509. const existing = await getCredentials('ai_config') || {};
  510. await setCredentials('ai_config', { ...existing, provider: name });
  511. }
  512. } else {
  513. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  514. }
  515. return { success: true };
  516. });
  517. // DELETE /ai/provider/:name — remove provider credentials; falls back to ollama if it was active
  518. app.delete('/ai/provider/:name', async (request, reply) => {
  519. const { name } = request.params;
  520. if (name === 'ollama') return reply.code(400).send({ error: 'Cannot remove Ollama provider' });
  521. if (!['openai', 'groq', 'gemini'].includes(name)) return reply.code(404).send({ error: `Unknown provider: ${name}` });
  522. const db = await getDb();
  523. await db.collection('platform_credentials').deleteOne({ _id: `${name}_config` });
  524. const aiConfig = await getCredentials('ai_config') || {};
  525. if (aiConfig.provider === name) {
  526. await setCredentials('ai_config', { ...aiConfig, provider: 'ollama' });
  527. }
  528. return { success: true };
  529. });
  530. // POST /ai/provider/:name/models — list models for a provider (test without saving key)
  531. app.post('/ai/provider/:name/models', async (request, reply) => {
  532. const { name } = request.params;
  533. const { apiKey: bodyApiKey, endpoint: bodyEndpoint } = request.body || {};
  534. if (name === 'ollama') {
  535. const aiConfig = await getCredentials('ai_config');
  536. const ep = bodyEndpoint || aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  537. try {
  538. const res = await axios.get(`${ep}/api/tags`, { timeout: 5000 });
  539. return { models: (res.data.models || []).map((m) => m.name) };
  540. } catch (err) {
  541. return reply.code(503).send({ error: 'Could not reach Ollama', detail: err.message });
  542. }
  543. }
  544. if (['openai', 'groq', 'gemini'].includes(name)) {
  545. return { models: PROVIDER_MODELS[name] };
  546. }
  547. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  548. });
  549. app.get('/ai/models', async (request, reply) => {
  550. const config = await getCredentials('ai_config');
  551. const provider = config?.provider || 'ollama';
  552. if (provider !== 'ollama') {
  553. return { models: PROVIDER_MODELS[provider] || [], provider };
  554. }
  555. const endpoint = request.query.endpoint || config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  556. try {
  557. const res = await axios.get(`${endpoint}/api/tags`, { timeout: 5000 });
  558. const models = (res.data.models || []).map((m) => m.name);
  559. return { models, endpoint };
  560. } catch (err) {
  561. return reply.code(503).send({ error: 'Could not reach Ollama — check the endpoint', detail: err.message });
  562. }
  563. });
  564. app.post('/ai/generate', async (request, reply) => {
  565. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext } = request.body || {};
  566. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  567. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  568. const system = rawSystem ? rawSystem + competitorSuffix : (competitorSuffix || undefined);
  569. const pconf = await getActiveProviderConfig();
  570. const model = reqModel || pconf.model;
  571. try {
  572. if (pconf.provider === 'ollama') {
  573. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  574. return { text: res.data.response, model, done: res.data.done };
  575. }
  576. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  577. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  578. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  579. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  580. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  581. return { text: res.data.choices[0]?.message?.content || '', model, done: true };
  582. }
  583. if (pconf.provider === 'gemini') {
  584. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  585. const res = await axios.post(
  586. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  587. { contents: buildGeminiContents(prompt, system) },
  588. { timeout: 90000 },
  589. );
  590. return { text: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model, done: true };
  591. }
  592. return reply.code(400).send({ error: `Unknown provider: ${pconf.provider}` });
  593. } catch (err) {
  594. const status = err.response?.status || 503;
  595. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  596. }
  597. });
  598. 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.';
  599. // Vision caption — supports ollama, openai, gemini (groq has no vision)
  600. app.post('/ai/caption', async (request, reply) => {
  601. const { imageUrl, model: reqModel } = request.body || {};
  602. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  603. const pconf = await getActiveProviderConfig();
  604. let imageBase64, imageMime;
  605. try {
  606. let imageBuffer;
  607. if (imageUrl.startsWith('/media/')) {
  608. const filename = path.basename(imageUrl);
  609. imageBuffer = fs.readFileSync(path.join(UPLOAD_DIR, filename));
  610. } else {
  611. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  612. imageBuffer = Buffer.from(imgRes.data);
  613. imageMime = imgRes.headers['content-type'] || 'image/jpeg';
  614. }
  615. imageBase64 = imageBuffer.toString('base64');
  616. if (!imageMime) imageMime = 'image/jpeg';
  617. } catch (err) {
  618. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  619. }
  620. try {
  621. const model = reqModel || pconf.visionModel || pconf.model;
  622. if (pconf.provider === 'ollama') {
  623. const res = await axios.post(`${pconf.endpoint}/api/generate`, {
  624. model, prompt: CAPTION_PROMPT, images: [imageBase64], stream: false,
  625. }, { timeout: 90000 });
  626. return { caption: res.data.response, model };
  627. }
  628. if (pconf.provider === 'openai') {
  629. if (!pconf.apiKey) return reply.code(503).send({ error: 'OpenAI API key not configured' });
  630. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  631. model: model || 'gpt-4o',
  632. messages: [{ role: 'user', content: [
  633. { type: 'text', text: CAPTION_PROMPT },
  634. { type: 'image_url', image_url: { url: `data:${imageMime};base64,${imageBase64}` } },
  635. ]}],
  636. stream: false,
  637. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  638. return { caption: res.data.choices[0]?.message?.content || '', model };
  639. }
  640. if (pconf.provider === 'gemini') {
  641. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  642. const geminiModel = model || 'gemini-1.5-flash';
  643. const res = await axios.post(
  644. `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${pconf.apiKey}`,
  645. { contents: [{ role: 'user', parts: [
  646. { text: CAPTION_PROMPT },
  647. { inlineData: { mimeType: imageMime, data: imageBase64 } },
  648. ]}]},
  649. { timeout: 90000 },
  650. );
  651. return { caption: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model: geminiModel };
  652. }
  653. return reply.code(400).send({ error: `Provider ${pconf.provider} does not support vision captions` });
  654. } catch (err) {
  655. const status = err.response?.status || 503;
  656. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  657. }
  658. });
  659. // SSE streaming endpoint — normalized data: { token, done } format for all providers
  660. app.post('/ai/stream', async (request, reply) => {
  661. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext } = request.body || {};
  662. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  663. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  664. const system = rawSystem ? rawSystem + competitorSuffix : (competitorSuffix || undefined);
  665. const pconf = await getActiveProviderConfig();
  666. const model = reqModel || pconf.model;
  667. reply.raw.setHeader('Content-Type', 'text/event-stream');
  668. reply.raw.setHeader('Cache-Control', 'no-cache');
  669. reply.raw.setHeader('X-Accel-Buffering', 'no');
  670. reply.raw.setHeader('Connection', 'keep-alive');
  671. reply.raw.flushHeaders();
  672. const writeToken = (token, done = false) => reply.raw.write(`data: ${JSON.stringify({ token, done })}\n\n`);
  673. const writeError = (msg) => { reply.raw.write(`data: ${JSON.stringify({ error: msg, done: true })}\n\n`); reply.raw.end(); };
  674. try {
  675. if (pconf.provider === 'ollama') {
  676. const ollamaRes = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  677. ollamaRes.data.on('data', (chunk) => {
  678. try {
  679. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  680. const data = JSON.parse(line);
  681. writeToken(data.response || '', !!data.done);
  682. }
  683. } catch (_) {}
  684. });
  685. ollamaRes.data.on('end', () => reply.raw.end());
  686. ollamaRes.data.on('error', (err) => writeError(err.message));
  687. return;
  688. }
  689. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  690. if (!pconf.apiKey) return writeError(`${pconf.provider} API key not configured`);
  691. const upstreamRes = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  692. model, messages: buildOpenAIMessages(prompt, system), stream: true,
  693. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, responseType: 'stream', timeout: 120000 });
  694. upstreamRes.data.on('data', (chunk) => {
  695. try {
  696. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  697. if (!line.startsWith('data: ')) continue;
  698. const payload = line.slice(6).trim();
  699. if (payload === '[DONE]') { writeToken('', true); return; }
  700. const data = JSON.parse(payload);
  701. const token = data.choices?.[0]?.delta?.content || '';
  702. if (token) writeToken(token);
  703. }
  704. } catch (_) {}
  705. });
  706. upstreamRes.data.on('end', () => reply.raw.end());
  707. upstreamRes.data.on('error', (err) => writeError(err.message));
  708. return;
  709. }
  710. if (pconf.provider === 'gemini') {
  711. if (!pconf.apiKey) return writeError('Gemini API key not configured');
  712. const geminiRes = await axios.post(
  713. `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${pconf.apiKey}`,
  714. { contents: buildGeminiContents(prompt, system) },
  715. { responseType: 'stream', timeout: 120000 },
  716. );
  717. geminiRes.data.on('data', (chunk) => {
  718. try {
  719. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  720. if (!line.startsWith('data: ')) continue;
  721. const data = JSON.parse(line.slice(6));
  722. const token = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  723. if (token) writeToken(token);
  724. }
  725. } catch (_) {}
  726. });
  727. geminiRes.data.on('end', () => { writeToken('', true); reply.raw.end(); });
  728. geminiRes.data.on('error', (err) => writeError(err.message));
  729. return;
  730. }
  731. writeError(`Unknown provider: ${pconf.provider}`);
  732. } catch (err) {
  733. writeError(err.message);
  734. }
  735. });
  736. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  737. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  738. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  739. app.post('/ai/bulk-draft', async (request, reply) => {
  740. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  741. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  742. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  743. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  744. const db = await getDb();
  745. const batchId = new ObjectId();
  746. const now = new Date();
  747. await db.collection('bulk_draft_batches').insertOne({
  748. _id: batchId,
  749. total: filteredTopics.length,
  750. completed: 0,
  751. failed: 0,
  752. status: 'processing',
  753. createdAt: now,
  754. updatedAt: now,
  755. });
  756. const selectedDests = destinations.filter((d) => d.selected);
  757. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  758. 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.`;
  759. // Fire-and-forget — process topics sequentially in the background
  760. (async () => {
  761. const pconf = await getActiveProviderConfig();
  762. const model = reqModel || pconf.model;
  763. for (const topic of filteredTopics) {
  764. try {
  765. const prompt = `Write a social media post about: ${topic}`;
  766. let content = '';
  767. if (pconf.provider === 'ollama') {
  768. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  769. content = res.data.response || '';
  770. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  771. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  772. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  773. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  774. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  775. content = res.data.choices[0]?.message?.content || '';
  776. } else if (pconf.provider === 'gemini') {
  777. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  778. const res = await axios.post(
  779. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  780. { contents: buildGeminiContents(prompt, system) },
  781. { timeout: 90000 },
  782. );
  783. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  784. }
  785. if (content.trim()) {
  786. const draftNow = new Date();
  787. await db.collection('drafts').insertOne({
  788. content: content.trim(),
  789. mediaUrl: '',
  790. scheduledAt: '',
  791. destinations: selectedDests,
  792. batchId: batchId.toString(),
  793. topic,
  794. createdAt: draftNow,
  795. updatedAt: draftNow,
  796. });
  797. }
  798. await db.collection('bulk_draft_batches').updateOne(
  799. { _id: batchId },
  800. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  801. );
  802. } catch (err) {
  803. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  804. await db.collection('bulk_draft_batches').updateOne(
  805. { _id: batchId },
  806. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  807. );
  808. }
  809. }
  810. await db.collection('bulk_draft_batches').updateOne(
  811. { _id: batchId },
  812. { $set: { status: 'done', updatedAt: new Date() } },
  813. );
  814. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  815. })().catch((err) => {
  816. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  817. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  818. { _id: batchId },
  819. { $set: { status: 'failed', updatedAt: new Date() } },
  820. )).catch(() => {});
  821. });
  822. return reply.code(202).send({ batchId: batchId.toString() });
  823. });
  824. // GET /ai/bulk-draft/:batchId — poll batch progress
  825. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  826. const { batchId } = request.params;
  827. let oid;
  828. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  829. const db = await getDb();
  830. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid });
  831. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  832. return {
  833. batchId: batch._id.toString(),
  834. total: batch.total,
  835. completed: batch.completed,
  836. failed: batch.failed,
  837. status: batch.status,
  838. processed: batch.completed + batch.failed,
  839. };
  840. });
  841. // ─── Platform service URLs ────────────────────────────────────────────────────
  842. const PLATFORM_SERVICES = {
  843. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  844. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  845. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  846. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  847. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  848. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  849. };
  850. // Direct multi-platform post endpoint.
  851. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  852. app.post('/post', async (request, reply) => {
  853. const { content, destinations = [], firstComment } = request.body || {};
  854. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  855. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  856. const results = await Promise.allSettled(
  857. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  858. const serviceUrl = PLATFORM_SERVICES[platform];
  859. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  860. const res = await axios.post(
  861. `${serviceUrl}/post`,
  862. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  863. { timeout: 30000 }
  864. );
  865. return { platform, accountId, ...res.data };
  866. })
  867. );
  868. const output = results.map((r, i) =>
  869. r.status === 'fulfilled'
  870. ? r.value
  871. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  872. );
  873. const anyFailed = output.some((r) => !r.success);
  874. const anySucceeded = output.some((r) => r.success);
  875. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  876. // Record the post for analytics
  877. try {
  878. const db = await getDb();
  879. await db.collection('posts').insertOne({
  880. _id: crypto.randomUUID(),
  881. type: 'immediate',
  882. content,
  883. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  884. destinations,
  885. platformResults: Object.fromEntries(
  886. output.map((r) => [
  887. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  888. { success: r.success, ...(r.error && { error: r.error }) },
  889. ])
  890. ),
  891. status: postStatus,
  892. publishedAt: new Date(),
  893. createdAt: new Date(),
  894. });
  895. } catch (err) {
  896. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  897. }
  898. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  899. });
  900. // ─── Legacy post route ────────────────────────────────────────────────────────
  901. let rabbitMQProducer = new RabbitMQProducer();
  902. app.post('/', async (request, reply) => {
  903. try {
  904. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  905. reply.send({ status: 'ok' });
  906. } catch (error) {
  907. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  908. reply.status(500).send({ error: 'Internal Server Error' });
  909. }
  910. });
  911. // ─── Meta App Credentials ────────────────────────────────────────────────────
  912. // Save Facebook App ID + Secret (entered by user in Settings UI)
  913. app.post('/credentials/meta-app', async (request, reply) => {
  914. const { appId, appSecret } = request.body || {};
  915. if (!appId || !appSecret) {
  916. return reply.code(400).send({ error: 'appId and appSecret are required' });
  917. }
  918. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  919. return { success: true };
  920. });
  921. // Get Meta App config (secret is masked for UI display)
  922. app.get('/credentials/meta-app', async () => {
  923. const cred = await getCredentials('meta_app');
  924. if (!cred) return { configured: false };
  925. const plainSecret = decryptToken(cred.appSecret) || '';
  926. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  927. });
  928. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  929. // Return the Facebook OAuth URL to redirect the user to
  930. app.get('/auth/meta/init', async (request, reply) => {
  931. const cred = await getCredentials('meta_app');
  932. if (!cred?.appId) {
  933. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  934. }
  935. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  936. const scopes = [
  937. 'pages_manage_posts',
  938. 'pages_read_engagement',
  939. 'instagram_basic',
  940. 'instagram_content_publish',
  941. 'instagram_manage_insights',
  942. ].join(',');
  943. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  944. return { url };
  945. });
  946. // OAuth callback — Facebook redirects here after user authorises
  947. app.get('/auth/meta/callback', async (request, reply) => {
  948. const { code, error: oauthError } = request.query;
  949. if (oauthError) {
  950. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  951. }
  952. if (!code) {
  953. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  954. }
  955. try {
  956. const appCred = await getCredentials('meta_app');
  957. if (!appCred?.appId) throw new Error('App credentials not configured');
  958. const appSecret = decryptToken(appCred.appSecret);
  959. if (!appSecret) throw new Error('Failed to decrypt app secret');
  960. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  961. // Exchange code for short-lived token
  962. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  963. params: {
  964. client_id: appCred.appId,
  965. client_secret: appSecret,
  966. redirect_uri: redirectUri,
  967. code,
  968. },
  969. });
  970. // Upgrade to long-lived user token (~60 days)
  971. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  972. params: {
  973. grant_type: 'fb_exchange_token',
  974. client_id: appCred.appId,
  975. client_secret: appSecret,
  976. fb_exchange_token: shortRes.data.access_token,
  977. },
  978. });
  979. const userToken = longRes.data.access_token;
  980. // Fetch all managed Facebook Pages
  981. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  982. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  983. });
  984. const pages = [];
  985. const igAccounts = [];
  986. for (const page of pagesRes.data.data || []) {
  987. pages.push({
  988. id: page.id,
  989. name: page.name,
  990. accessToken: encryptToken(page.access_token),
  991. picture: page.picture?.data?.url || null,
  992. selected: false,
  993. });
  994. // Check for linked Instagram Business Account
  995. try {
  996. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  997. params: {
  998. fields: 'instagram_business_account',
  999. access_token: page.access_token,
  1000. },
  1001. });
  1002. if (igRes.data.instagram_business_account?.id) {
  1003. const igId = igRes.data.instagram_business_account.id;
  1004. // Fetch IG account details
  1005. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1006. params: {
  1007. fields: 'id,username,name,profile_picture_url',
  1008. access_token: userToken,
  1009. },
  1010. });
  1011. igAccounts.push({
  1012. id: igId,
  1013. username: igProfile.data.username || igProfile.data.name,
  1014. name: igProfile.data.name,
  1015. avatar: igProfile.data.profile_picture_url || null,
  1016. accessToken: encryptToken(userToken),
  1017. pageId: page.id,
  1018. selected: false,
  1019. });
  1020. }
  1021. } catch (_) {
  1022. // Page has no linked Instagram account — skip
  1023. }
  1024. }
  1025. // Store discovery results for the UI to pick from
  1026. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1027. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1028. } catch (err) {
  1029. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1030. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1031. }
  1032. });
  1033. // Return pending discovery results so the UI can render the page picker
  1034. app.get('/auth/meta/discovered', async () => {
  1035. const discovery = await getCredentials('meta_discovery');
  1036. if (!discovery) return { pages: [], igAccounts: [] };
  1037. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1038. });
  1039. // User has chosen which pages/accounts to connect
  1040. app.post('/auth/meta/save', async (request, reply) => {
  1041. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1042. const discovery = await getCredentials('meta_discovery');
  1043. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1044. const fbPages = (discovery.pages || []).map((p) => ({
  1045. ...p,
  1046. selected: selectedPageIds.includes(p.id),
  1047. }));
  1048. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1049. ...a,
  1050. selected: selectedIgAccountIds.includes(a.id),
  1051. }));
  1052. await setCredentials('facebook', { pages: fbPages });
  1053. await setCredentials('instagram', { accounts: igAccounts });
  1054. await deleteCredentials('meta_discovery');
  1055. _tokenExpiryCache = null; // invalidate cache after reconnect
  1056. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1057. });
  1058. // Disconnect all Meta platforms
  1059. app.delete('/credentials/meta', async () => {
  1060. await deleteCredentials('facebook');
  1061. await deleteCredentials('instagram');
  1062. await deleteCredentials('meta_discovery');
  1063. return { success: true };
  1064. });
  1065. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1066. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1067. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1068. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1069. app.post('/credentials/pinterest-app', async (request, reply) => {
  1070. const { clientId, clientSecret } = request.body || {};
  1071. if (!clientId || !clientSecret) {
  1072. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1073. }
  1074. await setCredentials('pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1075. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1076. return { success: true };
  1077. });
  1078. app.get('/credentials/pinterest-app', async () => {
  1079. const cred = await getCredentials('pinterest_app');
  1080. if (!cred) return { configured: false };
  1081. const plain = decryptToken(cred.clientSecret) || '';
  1082. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1083. });
  1084. app.get('/auth/pinterest/init', async (request, reply) => {
  1085. const cred = await getCredentials('pinterest_app');
  1086. if (!cred?.clientId) {
  1087. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1088. }
  1089. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1090. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1091. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1092. return { url };
  1093. });
  1094. app.get('/auth/pinterest/callback', async (request, reply) => {
  1095. const { code, error: oauthError } = request.query;
  1096. if (oauthError) {
  1097. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1098. }
  1099. if (!code) {
  1100. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1101. }
  1102. try {
  1103. const appCred = await getCredentials('pinterest_app');
  1104. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1105. const clientSecret = decryptToken(appCred.clientSecret);
  1106. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1107. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1108. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1109. const tokenRes = await axios.post(
  1110. PINTEREST_TOKEN_URL,
  1111. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1112. {
  1113. headers: {
  1114. Authorization: `Basic ${basicAuth}`,
  1115. 'Content-Type': 'application/x-www-form-urlencoded',
  1116. },
  1117. timeout: 15000,
  1118. }
  1119. );
  1120. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1121. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1122. const [userRes, boardsRes] = await Promise.all([
  1123. axios.get(`${PINTEREST_API}/user_account`, {
  1124. headers: { Authorization: `Bearer ${access_token}` },
  1125. timeout: 10000,
  1126. }),
  1127. axios.get(`${PINTEREST_API}/boards`, {
  1128. headers: { Authorization: `Bearer ${access_token}` },
  1129. params: { page_size: 100 },
  1130. timeout: 15000,
  1131. }),
  1132. ]);
  1133. const boards = (boardsRes.data.items || []).map((b) => ({
  1134. id: b.id,
  1135. name: b.name,
  1136. privacy: b.privacy,
  1137. selected: false,
  1138. }));
  1139. await setCredentials('pinterest', {
  1140. userId: userRes.data.username,
  1141. username: userRes.data.username,
  1142. displayName: userRes.data.business_name || userRes.data.username,
  1143. avatar: userRes.data.profile_image,
  1144. accessToken: encryptToken(access_token),
  1145. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1146. tokenExpiry,
  1147. boards,
  1148. });
  1149. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1150. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1151. } catch (err) {
  1152. const msg = err.response?.data?.message || err.message;
  1153. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1154. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1155. }
  1156. });
  1157. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1158. const { selectedBoardIds = [] } = request.body || {};
  1159. const cred = await getCredentials('pinterest');
  1160. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1161. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1162. await setCredentials('pinterest', { ...cred, boards });
  1163. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1164. return { success: true, selected: boards.filter((b) => b.selected).length };
  1165. });
  1166. app.delete('/credentials/pinterest', async () => {
  1167. await deleteCredentials('pinterest');
  1168. return { success: true };
  1169. });
  1170. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1171. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1172. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1173. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1174. app.post('/credentials/tiktok-app', async (request, reply) => {
  1175. const { clientKey, clientSecret } = request.body || {};
  1176. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1177. await setCredentials('tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1178. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1179. return { success: true };
  1180. });
  1181. app.get('/credentials/tiktok-app', async () => {
  1182. const cred = await getCredentials('tiktok_app');
  1183. if (!cred?.clientKey) return { configured: false };
  1184. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1185. });
  1186. app.get('/auth/tiktok/init', async (request, reply) => {
  1187. const cred = await getCredentials('tiktok_app');
  1188. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1189. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1190. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1191. const state = crypto.randomBytes(16).toString('hex');
  1192. // Persist PKCE verifier for the callback
  1193. const db = await getDb();
  1194. await db.collection('platform_credentials').updateOne(
  1195. { _id: 'tiktok_pkce' },
  1196. { $set: { codeVerifier, state, createdAt: new Date() } },
  1197. { upsert: true }
  1198. );
  1199. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1200. const scopes = 'user.info.basic,video.list,video.publish';
  1201. const params = new URLSearchParams({
  1202. client_key: cred.clientKey,
  1203. scope: scopes,
  1204. response_type: 'code',
  1205. redirect_uri: redirectUri,
  1206. state,
  1207. code_challenge: codeChallenge,
  1208. code_challenge_method: 'S256',
  1209. });
  1210. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1211. });
  1212. app.get('/auth/tiktok/callback', async (request, reply) => {
  1213. const { code, state, error: oauthError, error_description } = request.query;
  1214. if (oauthError) {
  1215. const msg = error_description || oauthError;
  1216. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1217. }
  1218. if (!code) {
  1219. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1220. }
  1221. try {
  1222. const db = await getDb();
  1223. const pkce = await db.collection('platform_credentials').findOne({ _id: 'tiktok_pkce' });
  1224. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1225. if (state && pkce.state && state !== pkce.state) throw new Error('OAuth state mismatch');
  1226. const appCred = await getCredentials('tiktok_app');
  1227. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1228. const clientSecret = decryptToken(appCred.clientSecret);
  1229. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1230. const tokenRes = await axios.post(
  1231. TIKTOK_TOKEN_URL,
  1232. new URLSearchParams({
  1233. client_key: appCred.clientKey,
  1234. client_secret: clientSecret,
  1235. code,
  1236. grant_type: 'authorization_code',
  1237. redirect_uri: redirectUri,
  1238. code_verifier: pkce.codeVerifier,
  1239. }).toString(),
  1240. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1241. );
  1242. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1243. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1244. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1245. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1246. headers: { Authorization: `Bearer ${access_token}` },
  1247. params: { fields: 'open_id,display_name,avatar_url,username' },
  1248. timeout: 10000,
  1249. });
  1250. const user = userRes.data?.data?.user || {};
  1251. await setCredentials('tiktok', {
  1252. openId: open_id || user.open_id,
  1253. username: user.username || user.display_name,
  1254. displayName: user.display_name,
  1255. avatar: user.avatar_url || null,
  1256. accessToken: encryptToken(access_token),
  1257. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1258. tokenExpiry,
  1259. refreshExpiry,
  1260. });
  1261. // Clean up PKCE temp state
  1262. await db.collection('platform_credentials').deleteOne({ _id: 'tiktok_pkce' });
  1263. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1264. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1265. } catch (err) {
  1266. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1267. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1268. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1269. }
  1270. });
  1271. app.delete('/credentials/tiktok', async () => {
  1272. await deleteCredentials('tiktok');
  1273. return { success: true };
  1274. });
  1275. // ─── Credential Status ────────────────────────────────────────────────────────
  1276. // Aggregate connection status for all DB-managed platforms
  1277. app.get('/credentials', async () => {
  1278. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1279. getCredentials('meta_app'),
  1280. getCredentials('facebook'),
  1281. getCredentials('instagram'),
  1282. getCredentials('pinterest'),
  1283. getCredentials('tiktok'),
  1284. ]);
  1285. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1286. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1287. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1288. return {
  1289. metaApp: { configured: !!(metaApp?.appId) },
  1290. facebook: {
  1291. connected: fbPages.length > 0,
  1292. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1293. },
  1294. instagram: {
  1295. connected: igAccounts.length > 0,
  1296. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1297. },
  1298. pinterest: {
  1299. connected: pinterestBoards.length > 0,
  1300. username: pinterest?.username || null,
  1301. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1302. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1303. },
  1304. tiktok: {
  1305. connected: !!(tiktok?.accessToken),
  1306. username: tiktok?.username || null,
  1307. displayName: tiktok?.displayName || null,
  1308. avatar: tiktok?.avatar || null,
  1309. },
  1310. };
  1311. });
  1312. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1313. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1314. const INDUSTRY_DEFAULTS = {
  1315. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1316. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1317. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1318. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1319. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1320. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1321. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1322. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1323. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1324. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  1325. };
  1326. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  1327. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  1328. // at least `afterMs` milliseconds in the future.
  1329. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  1330. const candidate = new Date(afterMs);
  1331. candidate.setUTCHours(hourUTC, 0, 0, 0);
  1332. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  1333. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  1334. candidate.setUTCDate(candidate.getUTCDate() + 7);
  1335. } else {
  1336. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  1337. }
  1338. return candidate;
  1339. }
  1340. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  1341. app.get('/schedule/suggestions', async (request, reply) => {
  1342. const { platform, accountId } = request.query;
  1343. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  1344. const db = await getDb();
  1345. const query = { platform, ...(accountId && { accountId }) };
  1346. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  1347. let slots;
  1348. let source;
  1349. if (dataPoints >= 10) {
  1350. const agg = await db.collection('post_metrics').aggregate([
  1351. { $match: query },
  1352. { $group: {
  1353. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1354. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1355. count: { $sum: 1 },
  1356. }},
  1357. { $sort: { avgEngagement: -1 } },
  1358. { $limit: 5 },
  1359. ]).toArray();
  1360. slots = agg.map((r) => [r._id.day, r._id.hour]);
  1361. source = 'history';
  1362. } else {
  1363. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  1364. source = 'default';
  1365. }
  1366. // 30-minute lead time so the user has time to finish writing
  1367. const afterMs = Date.now() + 30 * 60 * 1000;
  1368. const suggestions = slots
  1369. .map(([day, hour]) => {
  1370. const dt = nextOccurrence(day, hour, afterMs);
  1371. const h12 = hour % 12 || 12;
  1372. const ampm = hour < 12 ? 'am' : 'pm';
  1373. return {
  1374. utc: dt.toISOString(),
  1375. dayOfWeek: day,
  1376. hour,
  1377. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  1378. };
  1379. })
  1380. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  1381. .slice(0, 4);
  1382. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  1383. return { source, suggestions };
  1384. });
  1385. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  1386. async function crawlFacebookMetrics(db) {
  1387. const fb = await getCredentials('facebook');
  1388. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  1389. if (!pages.length) return { count: 0 };
  1390. let count = 0;
  1391. for (const page of pages) {
  1392. const token = decryptToken(page.accessToken);
  1393. if (!token) continue;
  1394. try {
  1395. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  1396. params: {
  1397. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  1398. limit: 100,
  1399. access_token: token,
  1400. },
  1401. timeout: 30000,
  1402. });
  1403. for (const post of res.data.data || []) {
  1404. const likes = post.reactions?.summary?.total_count || 0;
  1405. const comments = post.comments?.summary?.total_count || 0;
  1406. const shares = post.shares?.count || 0;
  1407. const publishedAt = new Date(post.created_time);
  1408. await db.collection('post_metrics').updateOne(
  1409. { platform: 'facebook', postId: post.id },
  1410. {
  1411. $set: {
  1412. platform: 'facebook',
  1413. accountId: page.id,
  1414. accountName: page.name,
  1415. postId: post.id,
  1416. content: post.message || null,
  1417. publishedAt,
  1418. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  1419. hourOfDay: publishedAt.getUTCHours(),
  1420. dayOfWeek: publishedAt.getUTCDay(),
  1421. fetchedAt: new Date(),
  1422. },
  1423. },
  1424. { upsert: true }
  1425. );
  1426. count++;
  1427. }
  1428. } catch (err) {
  1429. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  1430. }
  1431. }
  1432. return { count };
  1433. }
  1434. async function crawlInstagramMetrics(db) {
  1435. const ig = await getCredentials('instagram');
  1436. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  1437. if (!accounts.length) return { count: 0 };
  1438. let count = 0;
  1439. for (const account of accounts) {
  1440. const token = decryptToken(account.accessToken);
  1441. if (!token) continue;
  1442. try {
  1443. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  1444. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  1445. timeout: 30000,
  1446. });
  1447. for (const media of mediaRes.data.data || []) {
  1448. const likes = media.like_count || 0;
  1449. const comments = media.comments_count || 0;
  1450. const publishedAt = new Date(media.timestamp);
  1451. let views = 0;
  1452. let saves = 0;
  1453. try {
  1454. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  1455. params: { metric: 'reach,saved', access_token: token },
  1456. timeout: 10000,
  1457. });
  1458. for (const ins of insRes.data.data || []) {
  1459. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  1460. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  1461. }
  1462. } catch (_) {}
  1463. await db.collection('post_metrics').updateOne(
  1464. { platform: 'instagram', postId: media.id },
  1465. {
  1466. $set: {
  1467. platform: 'instagram',
  1468. accountId: account.id,
  1469. accountName: account.username,
  1470. postId: media.id,
  1471. content: media.caption || null,
  1472. publishedAt,
  1473. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  1474. hourOfDay: publishedAt.getUTCHours(),
  1475. dayOfWeek: publishedAt.getUTCDay(),
  1476. fetchedAt: new Date(),
  1477. },
  1478. },
  1479. { upsert: true }
  1480. );
  1481. count++;
  1482. }
  1483. } catch (err) {
  1484. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  1485. }
  1486. }
  1487. return { count };
  1488. }
  1489. app.post('/analytics/crawl', async () => {
  1490. const db = await getDb();
  1491. const results = {};
  1492. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  1493. try {
  1494. results[platform] = await crawler(db);
  1495. } catch (err) {
  1496. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  1497. results[platform] = { count: 0, error: err.message };
  1498. }
  1499. }
  1500. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  1501. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  1502. return { success: true, total, byPlatform: results };
  1503. });
  1504. app.get('/analytics/insights', async (request) => {
  1505. const filter = parseAccountFilter(request.query.account);
  1506. const metricsMatch = filter
  1507. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1508. : {};
  1509. const db = await getDb();
  1510. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  1511. if (total === 0) return { empty: true };
  1512. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  1513. db.collection('post_metrics').aggregate([
  1514. { $match: metricsMatch },
  1515. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1516. { $sort: { _id: 1 } },
  1517. ]).toArray(),
  1518. db.collection('post_metrics').aggregate([
  1519. { $match: metricsMatch },
  1520. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1521. { $sort: { _id: 1 } },
  1522. ]).toArray(),
  1523. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  1524. db.collection('post_metrics').aggregate([
  1525. { $match: metricsMatch },
  1526. { $group: {
  1527. _id: '$platform',
  1528. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1529. avgLikes: { $avg: '$metrics.likes' },
  1530. avgComments: { $avg: '$metrics.comments' },
  1531. avgShares: { $avg: '$metrics.shares' },
  1532. totalPosts: { $sum: 1 },
  1533. }},
  1534. { $sort: { avgEngagement: -1 } },
  1535. ]).toArray(),
  1536. db.collection('post_metrics').aggregate([
  1537. { $match: metricsMatch },
  1538. { $group: {
  1539. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1540. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1541. count: { $sum: 1 },
  1542. }},
  1543. ]).toArray(),
  1544. ]);
  1545. const byHour = Array.from({ length: 24 }, (_, h) => {
  1546. const e = byHourRaw.find((r) => r._id === h);
  1547. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1548. });
  1549. const byDay = Array.from({ length: 7 }, (_, d) => {
  1550. const e = byDayRaw.find((r) => r._id === d);
  1551. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1552. });
  1553. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  1554. const day = Math.floor(i / 24);
  1555. const hour = i % 24;
  1556. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  1557. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1558. });
  1559. return {
  1560. empty: false,
  1561. total,
  1562. byHour,
  1563. byDay,
  1564. heatmap,
  1565. topPosts: topPosts.map((p) => ({
  1566. platform: p.platform, accountName: p.accountName, postId: p.postId,
  1567. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  1568. })),
  1569. platformComparison: platformComparison.map((p) => ({
  1570. platform: p._id,
  1571. avgEngagement: Math.round(p.avgEngagement),
  1572. avgLikes: Math.round(p.avgLikes),
  1573. avgComments: Math.round(p.avgComments),
  1574. avgShares: Math.round(p.avgShares),
  1575. totalPosts: p.totalPosts,
  1576. })),
  1577. };
  1578. });
  1579. // ─── Analytics ────────────────────────────────────────────────────────────────
  1580. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  1581. function parseAccountFilter(account) {
  1582. if (!account) return null;
  1583. const idx = account.indexOf(':');
  1584. if (idx === -1) return { platform: account };
  1585. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  1586. }
  1587. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  1588. function sjFilter(filter) {
  1589. if (!filter) return {};
  1590. return {
  1591. 'destinations.platform': filter.platform,
  1592. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1593. };
  1594. }
  1595. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  1596. function ipFilter(filter) {
  1597. if (!filter) return {};
  1598. return {
  1599. 'destinations.platform': filter.platform,
  1600. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1601. };
  1602. }
  1603. app.get('/analytics/summary', async (request) => {
  1604. const filter = parseAccountFilter(request.query.account);
  1605. const db = await getDb();
  1606. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1607. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1608. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  1609. // account filter after $unwind so a job targeting multiple platforms only
  1610. // counts the platform(s) that match the filter.
  1611. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  1612. const [
  1613. schedCompleted, schedFailed,
  1614. immPublished, immFailed,
  1615. recentSched, recentImm,
  1616. schedPlatformRaw, immPlatformRaw,
  1617. schedDayRaw, immDayRaw,
  1618. ] = await Promise.all([
  1619. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  1620. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  1621. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  1622. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  1623. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  1624. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  1625. // Platform breakdown from scheduled_jobs destinations
  1626. db.collection('scheduled_jobs').aggregate([
  1627. { $match: { status: 'completed', ...sjFilter(filter) } },
  1628. { $unwind: '$destinations' },
  1629. ...unwindFilter,
  1630. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  1631. { $sort: { count: -1 } },
  1632. ]).toArray(),
  1633. // Platform breakdown from immediate posts platformResults
  1634. db.collection('posts').aggregate([
  1635. { $match: { type: 'immediate', ...ipFilter(filter) } },
  1636. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  1637. { $unwind: '$results' },
  1638. { $match: { 'results.v.success': true } },
  1639. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  1640. { $group: { _id: '$platform', count: { $sum: 1 } } },
  1641. ]).toArray(),
  1642. // Activity by day from scheduled_jobs (using completedAt)
  1643. db.collection('scheduled_jobs').aggregate([
  1644. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  1645. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  1646. { $sort: { _id: 1 } },
  1647. ]).toArray(),
  1648. // Activity by day from immediate posts
  1649. db.collection('posts').aggregate([
  1650. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  1651. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  1652. { $sort: { _id: 1 } },
  1653. ]).toArray(),
  1654. ]);
  1655. const dayMap = {};
  1656. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1657. dayMap[_id] = (dayMap[_id] || 0) + count;
  1658. }
  1659. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1660. const platformMap = {};
  1661. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1662. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1663. }
  1664. const published = schedCompleted + immPublished;
  1665. const failed = schedFailed + immFailed;
  1666. const total = published + failed;
  1667. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1668. const recentCount = recentSched + recentImm;
  1669. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1670. });
  1671. app.get('/analytics/posts', async (request) => {
  1672. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1673. const skip = parseInt(request.query.skip || '0', 10);
  1674. const filter = parseAccountFilter(request.query.account);
  1675. const db = await getDb();
  1676. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1677. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1678. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1679. db.collection('scheduled_jobs')
  1680. .find(sjMatch)
  1681. .sort({ completedAt: -1, scheduledAt: -1 })
  1682. .skip(skip)
  1683. .limit(limit)
  1684. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1685. .toArray(),
  1686. db.collection('posts')
  1687. .find(ipMatch)
  1688. .sort({ publishedAt: -1 })
  1689. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1690. .toArray(),
  1691. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1692. db.collection('posts').countDocuments(ipMatch),
  1693. ]);
  1694. const normalised = [
  1695. ...scheduledJobs.map((j) => ({
  1696. _id: String(j._id),
  1697. type: 'scheduled',
  1698. content: j.content || null,
  1699. destinations: j.destinations || [],
  1700. platformResults: null,
  1701. status: j.status === 'completed' ? 'published' : 'failed',
  1702. publishedAt: j.completedAt || j.scheduledAt,
  1703. })),
  1704. ...immediatePosts.map((p) => ({
  1705. _id: String(p._id),
  1706. type: 'immediate',
  1707. content: p.content || null,
  1708. destinations: p.destinations || [],
  1709. platformResults: p.platformResults || null,
  1710. status: p.status,
  1711. publishedAt: p.publishedAt,
  1712. })),
  1713. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  1714. .slice(0, limit);
  1715. return { posts: normalised, total: schedTotal + immTotal };
  1716. });
  1717. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  1718. app.get('/hashtag-groups', async () => {
  1719. const db = await getDb();
  1720. const groups = await db.collection('hashtag_groups').find({}).sort({ name: 1 }).toArray();
  1721. return { groups };
  1722. });
  1723. app.post('/hashtag-groups', async (request, reply) => {
  1724. const { name, hashtags } = request.body || {};
  1725. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  1726. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  1727. const db = await getDb();
  1728. const result = await db.collection('hashtag_groups').insertOne({
  1729. name: name.trim(),
  1730. hashtags: [...new Set(tags)],
  1731. createdAt: new Date(),
  1732. updatedAt: new Date(),
  1733. });
  1734. return { success: true, _id: result.insertedId };
  1735. });
  1736. app.put('/hashtag-groups/:id', async (request, reply) => {
  1737. const { id } = request.params;
  1738. const { name, hashtags } = request.body || {};
  1739. const update = { updatedAt: new Date() };
  1740. if (name?.trim()) update.name = name.trim();
  1741. if (hashtags) {
  1742. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  1743. update.hashtags = [...new Set(tags)];
  1744. }
  1745. const db = await getDb();
  1746. let oid;
  1747. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1748. await db.collection('hashtag_groups').updateOne({ _id: oid }, { $set: update });
  1749. return { success: true };
  1750. });
  1751. app.delete('/hashtag-groups/:id', async (request, reply) => {
  1752. const { id } = request.params;
  1753. const db = await getDb();
  1754. let oid;
  1755. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1756. await db.collection('hashtag_groups').deleteOne({ _id: oid });
  1757. return { success: true };
  1758. });
  1759. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  1760. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  1761. function extractHashtags(text) {
  1762. if (!text) return [];
  1763. const tags = [];
  1764. let m;
  1765. HASHTAG_RE.lastIndex = 0;
  1766. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  1767. return tags;
  1768. }
  1769. function gradeHashtag(count, avgEngagement) {
  1770. if (count >= 5 && avgEngagement >= 10) return 'A';
  1771. if (count >= 3 && avgEngagement >= 3) return 'B';
  1772. if (count >= 2) return 'C';
  1773. return 'D';
  1774. }
  1775. // POST /hashtags/scrape — scan YOUR published posts per-account.
  1776. // Body: { accountKey?: string } — omit to scan all accounts at once.
  1777. app.post('/hashtags/scrape', async (request) => {
  1778. const { accountKey: filterAccount } = request.body || {};
  1779. const db = await getDb();
  1780. // tagMap key: `${accountKey}||${hashtag}`
  1781. const tagMap = {};
  1782. function touch(tag, accountKey, platform, engagement) {
  1783. const key = `${accountKey}||${tag}`;
  1784. if (!tagMap[key]) tagMap[key] = { tag, accountKey, count: 0, totalEngagement: 0, platforms: new Set() };
  1785. tagMap[key].count++;
  1786. tagMap[key].totalEngagement += engagement;
  1787. tagMap[key].platforms.add(platform);
  1788. }
  1789. // Engagement lookup keyed by content fingerprint
  1790. const postMetrics = await db.collection('post_metrics').find({}).toArray();
  1791. const metricsByContent = {};
  1792. for (const m of postMetrics) {
  1793. if (m.content) {
  1794. const key = m.content.slice(0, 100).toLowerCase().trim();
  1795. metricsByContent[key] = (metricsByContent[key] || 0) + (m.metrics?.engagementTotal || 0);
  1796. }
  1797. }
  1798. // Scan YOUR published posts only — feeds are others' content, not your performance
  1799. const posts = await db.collection('posts').find({}, { projection: { content: 1, destinations: 1 } }).toArray();
  1800. for (const post of posts) {
  1801. const tags = extractHashtags(post.content || '');
  1802. if (!tags.length) continue;
  1803. const engagement = post.content
  1804. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  1805. : 0;
  1806. const destinations = post.destinations?.length ? post.destinations : [{ platform: 'unknown' }];
  1807. for (const dest of destinations) {
  1808. const acctKey = dest.accountId ? `${dest.platform}:${dest.accountId}` : dest.platform;
  1809. if (filterAccount && acctKey !== filterAccount) continue;
  1810. for (const tag of tags) {
  1811. touch(tag, acctKey, dest.platform, engagement / Math.max(tags.length, 1));
  1812. }
  1813. }
  1814. }
  1815. let scraped = 0;
  1816. for (const [compoundKey, 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: compoundKey },
  1820. {
  1821. $set: {
  1822. hashtag: data.tag,
  1823. accountKey: data.accountKey,
  1824. count: data.count,
  1825. avgEngagement: Math.round(avgEngagement * 10) / 10,
  1826. grade: gradeHashtag(data.count, avgEngagement),
  1827. platforms: [...data.platforms],
  1828. lastScraped: new Date(),
  1829. },
  1830. },
  1831. { upsert: true }
  1832. );
  1833. scraped++;
  1834. }
  1835. log.info({ action: 'hashtag_scrape', accountKey: filterAccount || 'all', outcome: 'success', scraped });
  1836. return { success: true, scraped };
  1837. });
  1838. app.get('/hashtags/stats', async (request) => {
  1839. const { sort, accountKey } = request.query;
  1840. const db = await getDb();
  1841. const sortField = sort === 'engagement' ? 'avgEngagement' : 'count';
  1842. if (accountKey) {
  1843. // Per-account view
  1844. const stats = await db.collection('hashtag_stats')
  1845. .find({ accountKey })
  1846. .sort({ [sortField]: -1 })
  1847. .limit(200)
  1848. .toArray();
  1849. return { stats };
  1850. }
  1851. // Aggregate view: group by hashtag across all accounts
  1852. const allStats = await db.collection('hashtag_stats').find({ accountKey: { $exists: true } }).toArray();
  1853. const grouped = new Map();
  1854. for (const s of allStats) {
  1855. if (!s.hashtag) continue;
  1856. if (!grouped.has(s.hashtag)) {
  1857. grouped.set(s.hashtag, { count: 0, totalEngagement: 0, totalCount: 0, platforms: new Set(), lastScraped: null });
  1858. }
  1859. const g = grouped.get(s.hashtag);
  1860. g.count += s.count;
  1861. g.totalEngagement += s.avgEngagement * s.count;
  1862. g.totalCount += s.count;
  1863. for (const p of (s.platforms || [])) g.platforms.add(p);
  1864. if (!g.lastScraped || (s.lastScraped && new Date(s.lastScraped) > new Date(g.lastScraped))) g.lastScraped = s.lastScraped;
  1865. }
  1866. const stats = [...grouped.entries()]
  1867. .map(([tag, g]) => {
  1868. const avgEngagement = g.totalCount > 0 ? Math.round((g.totalEngagement / g.totalCount) * 10) / 10 : 0;
  1869. return {
  1870. _id: tag,
  1871. hashtag: tag,
  1872. accountKey: null,
  1873. count: g.count,
  1874. avgEngagement,
  1875. grade: gradeHashtag(g.count, avgEngagement),
  1876. platforms: [...g.platforms],
  1877. lastScraped: g.lastScraped,
  1878. };
  1879. })
  1880. .sort((a, b) => b[sortField] - a[sortField])
  1881. .slice(0, 200);
  1882. return { stats };
  1883. });
  1884. app.post('/hashtags/ai-suggest', async (request, reply) => {
  1885. const { accountKey, topTags = [], count = 20 } = request.body || {};
  1886. let profileCtx = '';
  1887. if (accountKey) {
  1888. try {
  1889. const db = await getDb();
  1890. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  1891. if (profile) {
  1892. const parts = [];
  1893. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  1894. if (profile.description) parts.push(`Description: ${profile.description}`);
  1895. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  1896. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  1897. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  1898. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  1899. profileCtx = parts.join('\n');
  1900. }
  1901. } catch (_) {}
  1902. }
  1903. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  1904. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  1905. const prompt = [
  1906. `Suggest ${count} high-performing hashtags for a social media account.`,
  1907. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  1908. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  1909. `\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`,
  1910. ].filter(Boolean).join('');
  1911. try {
  1912. const pconf = await getActiveProviderConfig();
  1913. const model = pconf.model;
  1914. let text = '';
  1915. if (pconf.provider === 'ollama') {
  1916. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  1917. text = res.data.response;
  1918. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1919. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  1920. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1921. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1922. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  1923. text = res.data.choices[0]?.message?.content || '';
  1924. } else if (pconf.provider === 'gemini') {
  1925. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  1926. const res = await axios.post(
  1927. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1928. { contents: buildGeminiContents(prompt, system) },
  1929. { timeout: 60000 },
  1930. );
  1931. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1932. } else {
  1933. return reply.code(400).send({ error: 'AI not configured' });
  1934. }
  1935. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  1936. return { success: true, hashtags: tags };
  1937. } catch (err) {
  1938. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  1939. }
  1940. });
  1941. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  1942. async function extractTextFromUrl(url) {
  1943. try {
  1944. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  1945. const html = res.data || '';
  1946. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  1947. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  1948. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  1949. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  1950. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  1951. } catch {
  1952. return '';
  1953. }
  1954. }
  1955. async function scrapeBluesky(profileUrl) {
  1956. try {
  1957. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  1958. if (!handle) return '';
  1959. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  1960. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  1961. return posts.join('\n').slice(0, 3000);
  1962. } catch {
  1963. return '';
  1964. }
  1965. }
  1966. async function scrapeMastodon(profileUrl) {
  1967. try {
  1968. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  1969. if (!m) return '';
  1970. const [, instance, username] = m;
  1971. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  1972. const accountId = lookupRes.data?.id;
  1973. if (!accountId) return '';
  1974. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  1975. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  1976. return posts.join('\n').slice(0, 3000);
  1977. } catch {
  1978. return '';
  1979. }
  1980. }
  1981. async function runCompetitorScrape(competitorId) {
  1982. const db = await getDb();
  1983. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  1984. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  1985. const newItems = [];
  1986. if (competitor.websiteUrl) {
  1987. const text = await extractTextFromUrl(competitor.websiteUrl);
  1988. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  1989. }
  1990. const socialEntries = Object.entries(competitor.socialUrls || {});
  1991. for (const [platform, url] of socialEntries) {
  1992. if (!url) continue;
  1993. let text = '';
  1994. if (platform === 'bluesky') text = await scrapeBluesky(url);
  1995. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  1996. else text = await extractTextFromUrl(url);
  1997. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  1998. }
  1999. const existing = competitor.scrapedContent || [];
  2000. // Detect whether any newly scraped content differs from what was previously stored
  2001. const existingFingerprints = new Set(existing.map((s) => s.url + '||' + s.text.slice(0, 200)));
  2002. const contentChanged = newItems.some((item) => !existingFingerprints.has(item.url + '||' + item.text.slice(0, 200)));
  2003. const combined = [...newItems, ...existing].slice(0, 20);
  2004. await db.collection('competitors').updateOne(
  2005. { _id: new ObjectId(competitorId) },
  2006. { $set: { scrapedContent: combined, contentChanged, lastScraped: new Date(), updatedAt: new Date() } },
  2007. );
  2008. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  2009. }
  2010. async function buildCompetitorSystemSuffix() {
  2011. try {
  2012. const db = await getDb();
  2013. const competitors = await db.collection('competitors').find({
  2014. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  2015. }).toArray();
  2016. if (!competitors.length) return '';
  2017. const lines = competitors.map((c) => {
  2018. if (c.aiAnalysis?.positioning) {
  2019. const a = c.aiAnalysis;
  2020. const parts = [`- ${c.name}:`];
  2021. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  2022. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  2023. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  2024. return parts.join('\n');
  2025. }
  2026. return `- ${c.name}: ${c.aiSummary}`;
  2027. }).join('\n');
  2028. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  2029. } catch {
  2030. return '';
  2031. }
  2032. }
  2033. // List competitors
  2034. app.get('/competitors', async (request, reply) => {
  2035. const db = await getDb();
  2036. const list = await db.collection('competitors').find({}).sort({ createdAt: 1 }).toArray();
  2037. return list;
  2038. });
  2039. // Add competitor (max 2)
  2040. app.post('/competitors', async (request, reply) => {
  2041. const db = await getDb();
  2042. const count = await db.collection('competitors').countDocuments();
  2043. if (count >= 5) return reply.code(400).send({ error: 'Maximum 5 competitors allowed' });
  2044. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  2045. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  2046. const now = new Date();
  2047. const result = await db.collection('competitors').insertOne({
  2048. name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  2049. });
  2050. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  2051. return doc;
  2052. });
  2053. // Update competitor
  2054. app.put('/competitors/:id', async (request, reply) => {
  2055. const db = await getDb();
  2056. const { name, websiteUrl, socialUrls } = request.body || {};
  2057. const updates = { updatedAt: new Date() };
  2058. if (name !== undefined) updates.name = name;
  2059. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  2060. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  2061. await db.collection('competitors').updateOne({ _id: new ObjectId(request.params.id) }, { $set: updates });
  2062. const doc = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2063. return doc;
  2064. });
  2065. // Delete competitor
  2066. app.delete('/competitors/:id', async (request, reply) => {
  2067. const db = await getDb();
  2068. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id) });
  2069. return { success: true };
  2070. });
  2071. // Scrape one competitor — returns jobId immediately, runs in background
  2072. app.post('/competitors/:id/scrape', async (request, reply) => {
  2073. const jobId = new ObjectId().toString();
  2074. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  2075. (async () => {
  2076. try {
  2077. const result = await runCompetitorScrape(request.params.id);
  2078. activeScrapeJobs.set(jobId, {
  2079. status: result.ok ? 'done' : 'failed',
  2080. sources: result.sources,
  2081. message: result.message,
  2082. });
  2083. } catch (err) {
  2084. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  2085. }
  2086. })();
  2087. return reply.code(202).send({ jobId });
  2088. });
  2089. // Poll scrape job status
  2090. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  2091. const job = activeScrapeJobs.get(request.params.jobId);
  2092. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  2093. return job;
  2094. });
  2095. // Scrape all competitors (called by scheduler)
  2096. app.post('/competitors/scrape-all', async (request, reply) => {
  2097. const db = await getDb();
  2098. const all = await db.collection('competitors').find({}).toArray();
  2099. const results = [];
  2100. for (const c of all) {
  2101. const r = await runCompetitorScrape(c._id.toString());
  2102. results.push({ id: c._id.toString(), name: c.name, ...r });
  2103. }
  2104. return { success: true, results };
  2105. });
  2106. // Summarize competitor content with AI — returns structured analysis
  2107. app.post('/competitors/:id/summarize', async (request, reply) => {
  2108. const db = await getDb();
  2109. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2110. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2111. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  2112. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  2113. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2114. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  2115. {
  2116. "themes": ["3-5 main content topics or pillars they focus on"],
  2117. "tone": "one sentence describing their voice and communication style",
  2118. "positioning": "one sentence on how they position themselves in the market",
  2119. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  2120. "moves": ["3 specific content angles you could use to stand out against them"]
  2121. }
  2122. Content:
  2123. ${content}
  2124. Return ONLY the JSON object. No explanation, no markdown.`;
  2125. try {
  2126. const pconf = await getActiveProviderConfig();
  2127. const model = pconf.model;
  2128. let text = '';
  2129. if (pconf.provider === 'ollama') {
  2130. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2131. text = res.data.response;
  2132. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2133. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2134. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2135. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2136. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2137. text = res.data.choices[0]?.message?.content || '';
  2138. } else if (pconf.provider === 'gemini') {
  2139. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2140. const res = await axios.post(
  2141. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2142. { contents: buildGeminiContents(prompt, system) },
  2143. { timeout: 180000 },
  2144. );
  2145. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2146. } else {
  2147. return reply.code(400).send({ error: 'AI not configured' });
  2148. }
  2149. let aiAnalysis = null;
  2150. try {
  2151. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2152. aiAnalysis = JSON.parse(jsonStr);
  2153. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  2154. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  2155. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  2156. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  2157. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  2158. } catch {
  2159. aiAnalysis = null;
  2160. }
  2161. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  2162. await db.collection('competitors').updateOne(
  2163. { _id: new ObjectId(request.params.id) },
  2164. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  2165. );
  2166. return { success: true, aiAnalysis };
  2167. } catch (err) {
  2168. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  2169. }
  2170. });
  2171. // Extract keywords from scraped content using AI (item 34)
  2172. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  2173. const db = await getDb();
  2174. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2175. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2176. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  2177. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  2178. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2179. const prompt = `Analyse the following content from "${competitor.name}" and extract the top 20 keywords and key phrases they appear to be targeting. For each keyword, classify its search intent using one of these four types:
  2180. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  2181. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  2182. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  2183. - navigational: user is searching for a specific brand or tool by name
  2184. Content:
  2185. ${content}
  2186. Return ONLY a JSON array, e.g.:
  2187. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  2188. No explanation, no markdown.`;
  2189. try {
  2190. const pconf = await getActiveProviderConfig();
  2191. const model = pconf.model;
  2192. let text = '';
  2193. if (pconf.provider === 'ollama') {
  2194. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2195. text = res.data.response;
  2196. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2197. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2198. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2199. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2200. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2201. text = res.data.choices[0]?.message?.content || '';
  2202. } else if (pconf.provider === 'gemini') {
  2203. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2204. const res = await axios.post(
  2205. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2206. { contents: buildGeminiContents(prompt, system) },
  2207. { timeout: 120000 },
  2208. );
  2209. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2210. } else {
  2211. return reply.code(400).send({ error: 'AI not configured' });
  2212. }
  2213. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  2214. let keywords = [];
  2215. try {
  2216. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2217. const parsed = JSON.parse(jsonStr);
  2218. if (!Array.isArray(parsed)) throw new Error();
  2219. const now = new Date();
  2220. keywords = parsed
  2221. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  2222. .slice(0, 20)
  2223. .map((k) => ({
  2224. term: k.term.trim(),
  2225. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  2226. extractedAt: now,
  2227. }));
  2228. } catch {
  2229. keywords = [];
  2230. }
  2231. await db.collection('competitors').updateOne(
  2232. { _id: new ObjectId(request.params.id) },
  2233. { $set: { keywords, updatedAt: new Date() } },
  2234. );
  2235. return { success: true, keywords };
  2236. } catch (err) {
  2237. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  2238. }
  2239. });
  2240. // Analyse content gaps — compare competitor keywords against user's hashtag_stats
  2241. app.post('/competitors/:id/analyze-gaps', async (request, reply) => {
  2242. const db = await getDb();
  2243. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2244. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2245. const keywords = (competitor.keywords || []);
  2246. if (!keywords.length) return reply.code(400).send({ error: 'Extract keywords first before analysing gaps' });
  2247. const hashtagDocs = await db.collection('hashtag_stats')
  2248. .find({ accountKey: { $exists: true } }, { projection: { _id: 0, hashtag: 1 } })
  2249. .toArray();
  2250. const hashtagStatsEmpty = hashtagDocs.length === 0;
  2251. // Deduplicate across accounts — same hashtag used by any account counts as covered
  2252. const uniqueTags = [...new Set(hashtagDocs.map((h) => h.hashtag).filter(Boolean))];
  2253. const hashtagTexts = uniqueTags.map((tag) => ({ id: tag, text: tag.replace(/^#/, '').toLowerCase() }));
  2254. const INTENT_ORDER = { transactional: 0, commercial: 1, informational: 2, navigational: 3 };
  2255. function findMatchingHashtags(term) {
  2256. const words = term.toLowerCase().split(/\s+/).filter((w) => w.length >= 4);
  2257. return hashtagTexts
  2258. .filter(({ text }) => words.some((w) => text.includes(w)))
  2259. .map(({ id }) => id);
  2260. }
  2261. const gaps = [];
  2262. const covered = [];
  2263. for (const kw of keywords) {
  2264. const term = typeof kw === 'string' ? kw : kw.term;
  2265. const intent = typeof kw === 'string' ? 'informational' : (kw.intent || 'informational');
  2266. const matched = findMatchingHashtags(term);
  2267. if (matched.length) {
  2268. covered.push({ term, intent, matchedHashtags: matched.slice(0, 4) });
  2269. } else {
  2270. gaps.push({ term, intent });
  2271. }
  2272. }
  2273. gaps.sort((a, b) => (INTENT_ORDER[a.intent] ?? 99) - (INTENT_ORDER[b.intent] ?? 99));
  2274. const gapAnalysis = { gaps, covered, totalKeywords: keywords.length, hashtagStatsEmpty, lastAnalyzed: new Date() };
  2275. await db.collection('competitors').updateOne(
  2276. { _id: new ObjectId(request.params.id) },
  2277. { $set: { gapAnalysis, updatedAt: new Date() } },
  2278. );
  2279. return { success: true, ...gapAnalysis };
  2280. });
  2281. // Generate a 5-post content roadmap from competitor keywords and gaps
  2282. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  2283. const db = await getDb();
  2284. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2285. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2286. const keywords = (competitor.keywords || []);
  2287. const hasKeywords = keywords.length > 0;
  2288. const hasContent = (competitor.scrapedContent || []).length > 0;
  2289. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  2290. const kwList = hasKeywords
  2291. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  2292. : '';
  2293. const gaps = competitor.aiAnalysis?.gaps || [];
  2294. const moves = competitor.aiAnalysis?.moves || [];
  2295. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  2296. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  2297. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  2298. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2299. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  2300. ${kwSection}${gapsSection}${movesSection}
  2301. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  2302. - topic: short topic name, max 8 words
  2303. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  2304. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  2305. - rationale: one sentence on why this post wins against ${competitor.name}
  2306. Return ONLY a JSON array:
  2307. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  2308. No explanation, no markdown.`;
  2309. try {
  2310. const pconf = await getActiveProviderConfig();
  2311. const model = pconf.model;
  2312. let text = '';
  2313. if (pconf.provider === 'ollama') {
  2314. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2315. text = res.data.response;
  2316. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2317. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2318. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2319. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2320. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2321. text = res.data.choices[0]?.message?.content || '';
  2322. } else if (pconf.provider === 'gemini') {
  2323. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2324. const res = await axios.post(
  2325. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2326. { contents: buildGeminiContents(prompt, system) },
  2327. { timeout: 180000 },
  2328. );
  2329. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2330. } else {
  2331. return reply.code(400).send({ error: 'AI not configured' });
  2332. }
  2333. let roadmap = [];
  2334. try {
  2335. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2336. const parsed = JSON.parse(jsonStr);
  2337. if (!Array.isArray(parsed)) throw new Error();
  2338. roadmap = parsed
  2339. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  2340. .slice(0, 5)
  2341. .map((p) => ({
  2342. topic: p.topic.trim(),
  2343. headline: p.headline.trim(),
  2344. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  2345. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  2346. }));
  2347. } catch {
  2348. roadmap = [];
  2349. }
  2350. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  2351. await db.collection('competitors').updateOne(
  2352. { _id: new ObjectId(request.params.id) },
  2353. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  2354. );
  2355. return { success: true, contentRoadmap: roadmap };
  2356. } catch (err) {
  2357. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  2358. }
  2359. });
  2360. module.exports = app;