server.js 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591
  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. app.post('/hashtags/scrape', async () => {
  1776. const db = await getDb();
  1777. // Collect hashtag → { count, totalEngagement, platforms }
  1778. const tagMap = {};
  1779. function touch(tag, platform, engagement) {
  1780. if (!tagMap[tag]) tagMap[tag] = { count: 0, totalEngagement: 0, platforms: new Set() };
  1781. tagMap[tag].count++;
  1782. tagMap[tag].totalEngagement += engagement;
  1783. tagMap[tag].platforms.add(platform);
  1784. }
  1785. // Scan published posts
  1786. const posts = await db.collection('posts').find({}, { projection: { content: 1, destinations: 1, platformResults: 1 } }).toArray();
  1787. const postMetrics = await db.collection('post_metrics').find({}).toArray();
  1788. // Build engagement lookup keyed by content fingerprint (first 100 chars)
  1789. const metricsByContent = {};
  1790. for (const m of postMetrics) {
  1791. if (m.content) {
  1792. const key = m.content.slice(0, 100).toLowerCase().trim();
  1793. metricsByContent[key] = (metricsByContent[key] || 0) + m.metrics.engagementTotal;
  1794. }
  1795. }
  1796. for (const post of posts) {
  1797. const tags = extractHashtags(post.content || '');
  1798. const engagement = post.content
  1799. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  1800. : 0;
  1801. const platforms = (post.destinations || []).map((d) => d.platform);
  1802. for (const tag of tags) {
  1803. for (const platform of platforms.length ? platforms : ['unknown']) {
  1804. touch(tag, platform, engagement / Math.max(tags.length, 1));
  1805. }
  1806. }
  1807. }
  1808. // Also scan feed items
  1809. const feeds = await db.collection('feeds').find({}, { projection: { content: 1, platform: 1, metrics: 1 } }).toArray();
  1810. for (const item of feeds) {
  1811. const tags = extractHashtags(item.content || '');
  1812. const engagement = (item.metrics?.likes || 0) + (item.metrics?.comments || 0) + (item.metrics?.shares || 0);
  1813. for (const tag of tags) {
  1814. touch(tag, item.platform || 'unknown', engagement / Math.max(tags.length, 1));
  1815. }
  1816. }
  1817. // Upsert hashtag_stats
  1818. let scraped = 0;
  1819. for (const [tag, data] of Object.entries(tagMap)) {
  1820. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  1821. await db.collection('hashtag_stats').updateOne(
  1822. { _id: tag },
  1823. {
  1824. $set: {
  1825. count: data.count,
  1826. avgEngagement: Math.round(avgEngagement * 10) / 10,
  1827. grade: gradeHashtag(data.count, avgEngagement),
  1828. platforms: [...data.platforms],
  1829. lastScraped: new Date(),
  1830. },
  1831. },
  1832. { upsert: true }
  1833. );
  1834. scraped++;
  1835. }
  1836. app.log.info({ action: 'hashtag_scrape', outcome: 'success', scraped });
  1837. return { success: true, scraped };
  1838. });
  1839. app.get('/hashtags/stats', async (request) => {
  1840. const sortBy = request.query.sort || 'count';
  1841. const db = await getDb();
  1842. const sortField = sortBy === 'engagement' ? 'avgEngagement' : 'count';
  1843. const stats = await db.collection('hashtag_stats')
  1844. .find({})
  1845. .sort({ [sortField]: -1 })
  1846. .limit(200)
  1847. .toArray();
  1848. return { stats };
  1849. });
  1850. app.post('/hashtags/ai-suggest', async (request, reply) => {
  1851. const { accountKey, topTags = [], count = 20 } = request.body || {};
  1852. let profileCtx = '';
  1853. if (accountKey) {
  1854. try {
  1855. const db = await getDb();
  1856. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  1857. if (profile) {
  1858. const parts = [];
  1859. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  1860. if (profile.description) parts.push(`Description: ${profile.description}`);
  1861. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  1862. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  1863. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  1864. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  1865. profileCtx = parts.join('\n');
  1866. }
  1867. } catch (_) {}
  1868. }
  1869. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  1870. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  1871. const prompt = [
  1872. `Suggest ${count} high-performing hashtags for a social media account.`,
  1873. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  1874. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  1875. `\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`,
  1876. ].filter(Boolean).join('');
  1877. try {
  1878. const pconf = await getActiveProviderConfig();
  1879. const model = pconf.model;
  1880. let text = '';
  1881. if (pconf.provider === 'ollama') {
  1882. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  1883. text = res.data.response;
  1884. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1885. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  1886. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1887. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1888. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  1889. text = res.data.choices[0]?.message?.content || '';
  1890. } else if (pconf.provider === 'gemini') {
  1891. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  1892. const res = await axios.post(
  1893. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1894. { contents: buildGeminiContents(prompt, system) },
  1895. { timeout: 60000 },
  1896. );
  1897. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1898. } else {
  1899. return reply.code(400).send({ error: 'AI not configured' });
  1900. }
  1901. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  1902. return { success: true, hashtags: tags };
  1903. } catch (err) {
  1904. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  1905. }
  1906. });
  1907. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  1908. async function extractTextFromUrl(url) {
  1909. try {
  1910. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  1911. const html = res.data || '';
  1912. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  1913. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  1914. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  1915. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  1916. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  1917. } catch {
  1918. return '';
  1919. }
  1920. }
  1921. async function scrapeBluesky(profileUrl) {
  1922. try {
  1923. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  1924. if (!handle) return '';
  1925. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  1926. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  1927. return posts.join('\n').slice(0, 3000);
  1928. } catch {
  1929. return '';
  1930. }
  1931. }
  1932. async function scrapeMastodon(profileUrl) {
  1933. try {
  1934. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  1935. if (!m) return '';
  1936. const [, instance, username] = m;
  1937. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  1938. const accountId = lookupRes.data?.id;
  1939. if (!accountId) return '';
  1940. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  1941. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  1942. return posts.join('\n').slice(0, 3000);
  1943. } catch {
  1944. return '';
  1945. }
  1946. }
  1947. async function runCompetitorScrape(competitorId) {
  1948. const db = await getDb();
  1949. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  1950. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  1951. const newItems = [];
  1952. if (competitor.websiteUrl) {
  1953. const text = await extractTextFromUrl(competitor.websiteUrl);
  1954. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  1955. }
  1956. const socialEntries = Object.entries(competitor.socialUrls || {});
  1957. for (const [platform, url] of socialEntries) {
  1958. if (!url) continue;
  1959. let text = '';
  1960. if (platform === 'bluesky') text = await scrapeBluesky(url);
  1961. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  1962. else text = await extractTextFromUrl(url);
  1963. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  1964. }
  1965. const existing = competitor.scrapedContent || [];
  1966. const combined = [...newItems, ...existing].slice(0, 20);
  1967. await db.collection('competitors').updateOne(
  1968. { _id: new ObjectId(competitorId) },
  1969. { $set: { scrapedContent: combined, lastScraped: new Date(), updatedAt: new Date() } },
  1970. );
  1971. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  1972. }
  1973. async function buildCompetitorSystemSuffix() {
  1974. try {
  1975. const db = await getDb();
  1976. const competitors = await db.collection('competitors').find({
  1977. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  1978. }).toArray();
  1979. if (!competitors.length) return '';
  1980. const lines = competitors.map((c) => {
  1981. if (c.aiAnalysis?.positioning) {
  1982. const a = c.aiAnalysis;
  1983. const parts = [`- ${c.name}:`];
  1984. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  1985. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  1986. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  1987. return parts.join('\n');
  1988. }
  1989. return `- ${c.name}: ${c.aiSummary}`;
  1990. }).join('\n');
  1991. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  1992. } catch {
  1993. return '';
  1994. }
  1995. }
  1996. // List competitors
  1997. app.get('/competitors', async (request, reply) => {
  1998. const db = await getDb();
  1999. const list = await db.collection('competitors').find({}).sort({ createdAt: 1 }).toArray();
  2000. return list;
  2001. });
  2002. // Add competitor (max 2)
  2003. app.post('/competitors', async (request, reply) => {
  2004. const db = await getDb();
  2005. const count = await db.collection('competitors').countDocuments();
  2006. if (count >= 2) return reply.code(400).send({ error: 'Maximum 2 competitors allowed' });
  2007. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  2008. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  2009. const now = new Date();
  2010. const result = await db.collection('competitors').insertOne({
  2011. name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  2012. });
  2013. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  2014. return doc;
  2015. });
  2016. // Update competitor
  2017. app.put('/competitors/:id', async (request, reply) => {
  2018. const db = await getDb();
  2019. const { name, websiteUrl, socialUrls } = request.body || {};
  2020. const updates = { updatedAt: new Date() };
  2021. if (name !== undefined) updates.name = name;
  2022. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  2023. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  2024. await db.collection('competitors').updateOne({ _id: new ObjectId(request.params.id) }, { $set: updates });
  2025. const doc = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2026. return doc;
  2027. });
  2028. // Delete competitor
  2029. app.delete('/competitors/:id', async (request, reply) => {
  2030. const db = await getDb();
  2031. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id) });
  2032. return { success: true };
  2033. });
  2034. // Scrape one competitor — returns jobId immediately, runs in background
  2035. app.post('/competitors/:id/scrape', async (request, reply) => {
  2036. const jobId = new ObjectId().toString();
  2037. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  2038. (async () => {
  2039. try {
  2040. const result = await runCompetitorScrape(request.params.id);
  2041. activeScrapeJobs.set(jobId, {
  2042. status: result.ok ? 'done' : 'failed',
  2043. sources: result.sources,
  2044. message: result.message,
  2045. });
  2046. } catch (err) {
  2047. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  2048. }
  2049. })();
  2050. return reply.code(202).send({ jobId });
  2051. });
  2052. // Poll scrape job status
  2053. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  2054. const job = activeScrapeJobs.get(request.params.jobId);
  2055. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  2056. return job;
  2057. });
  2058. // Scrape all competitors (called by scheduler)
  2059. app.post('/competitors/scrape-all', async (request, reply) => {
  2060. const db = await getDb();
  2061. const all = await db.collection('competitors').find({}).toArray();
  2062. const results = [];
  2063. for (const c of all) {
  2064. const r = await runCompetitorScrape(c._id.toString());
  2065. results.push({ id: c._id.toString(), name: c.name, ...r });
  2066. }
  2067. return { success: true, results };
  2068. });
  2069. // Summarize competitor content with AI — returns structured analysis
  2070. app.post('/competitors/:id/summarize', async (request, reply) => {
  2071. const db = await getDb();
  2072. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2073. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2074. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  2075. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  2076. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2077. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  2078. {
  2079. "themes": ["3-5 main content topics or pillars they focus on"],
  2080. "tone": "one sentence describing their voice and communication style",
  2081. "positioning": "one sentence on how they position themselves in the market",
  2082. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  2083. "moves": ["3 specific content angles you could use to stand out against them"]
  2084. }
  2085. Content:
  2086. ${content}
  2087. Return ONLY the JSON object. No explanation, no markdown.`;
  2088. try {
  2089. const pconf = await getActiveProviderConfig();
  2090. const model = pconf.model;
  2091. let text = '';
  2092. if (pconf.provider === 'ollama') {
  2093. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2094. text = res.data.response;
  2095. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2096. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2097. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2098. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2099. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2100. text = res.data.choices[0]?.message?.content || '';
  2101. } else if (pconf.provider === 'gemini') {
  2102. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2103. const res = await axios.post(
  2104. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2105. { contents: buildGeminiContents(prompt, system) },
  2106. { timeout: 180000 },
  2107. );
  2108. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2109. } else {
  2110. return reply.code(400).send({ error: 'AI not configured' });
  2111. }
  2112. let aiAnalysis = null;
  2113. try {
  2114. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2115. aiAnalysis = JSON.parse(jsonStr);
  2116. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  2117. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  2118. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  2119. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  2120. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  2121. } catch {
  2122. aiAnalysis = null;
  2123. }
  2124. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  2125. await db.collection('competitors').updateOne(
  2126. { _id: new ObjectId(request.params.id) },
  2127. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  2128. );
  2129. return { success: true, aiAnalysis };
  2130. } catch (err) {
  2131. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  2132. }
  2133. });
  2134. // Extract keywords from scraped content using AI (item 34)
  2135. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  2136. const db = await getDb();
  2137. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2138. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2139. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  2140. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  2141. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2142. 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:
  2143. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  2144. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  2145. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  2146. - navigational: user is searching for a specific brand or tool by name
  2147. Content:
  2148. ${content}
  2149. Return ONLY a JSON array, e.g.:
  2150. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  2151. No explanation, no markdown.`;
  2152. try {
  2153. const pconf = await getActiveProviderConfig();
  2154. const model = pconf.model;
  2155. let text = '';
  2156. if (pconf.provider === 'ollama') {
  2157. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2158. text = res.data.response;
  2159. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2160. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2161. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2162. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2163. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2164. text = res.data.choices[0]?.message?.content || '';
  2165. } else if (pconf.provider === 'gemini') {
  2166. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2167. const res = await axios.post(
  2168. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2169. { contents: buildGeminiContents(prompt, system) },
  2170. { timeout: 120000 },
  2171. );
  2172. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2173. } else {
  2174. return reply.code(400).send({ error: 'AI not configured' });
  2175. }
  2176. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  2177. let keywords = [];
  2178. try {
  2179. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2180. const parsed = JSON.parse(jsonStr);
  2181. if (!Array.isArray(parsed)) throw new Error();
  2182. const now = new Date();
  2183. keywords = parsed
  2184. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  2185. .slice(0, 20)
  2186. .map((k) => ({
  2187. term: k.term.trim(),
  2188. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  2189. extractedAt: now,
  2190. }));
  2191. } catch {
  2192. keywords = [];
  2193. }
  2194. await db.collection('competitors').updateOne(
  2195. { _id: new ObjectId(request.params.id) },
  2196. { $set: { keywords, updatedAt: new Date() } },
  2197. );
  2198. return { success: true, keywords };
  2199. } catch (err) {
  2200. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  2201. }
  2202. });
  2203. // Generate a 5-post content roadmap from competitor keywords and gaps
  2204. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  2205. const db = await getDb();
  2206. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2207. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2208. const keywords = (competitor.keywords || []);
  2209. const hasKeywords = keywords.length > 0;
  2210. const hasContent = (competitor.scrapedContent || []).length > 0;
  2211. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  2212. const kwList = hasKeywords
  2213. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  2214. : '';
  2215. const gaps = competitor.aiAnalysis?.gaps || [];
  2216. const moves = competitor.aiAnalysis?.moves || [];
  2217. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  2218. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  2219. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  2220. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2221. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  2222. ${kwSection}${gapsSection}${movesSection}
  2223. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  2224. - topic: short topic name, max 8 words
  2225. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  2226. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  2227. - rationale: one sentence on why this post wins against ${competitor.name}
  2228. Return ONLY a JSON array:
  2229. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  2230. No explanation, no markdown.`;
  2231. try {
  2232. const pconf = await getActiveProviderConfig();
  2233. const model = pconf.model;
  2234. let text = '';
  2235. if (pconf.provider === 'ollama') {
  2236. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2237. text = res.data.response;
  2238. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2239. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2240. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2241. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2242. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2243. text = res.data.choices[0]?.message?.content || '';
  2244. } else if (pconf.provider === 'gemini') {
  2245. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2246. const res = await axios.post(
  2247. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2248. { contents: buildGeminiContents(prompt, system) },
  2249. { timeout: 180000 },
  2250. );
  2251. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2252. } else {
  2253. return reply.code(400).send({ error: 'AI not configured' });
  2254. }
  2255. let roadmap = [];
  2256. try {
  2257. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2258. const parsed = JSON.parse(jsonStr);
  2259. if (!Array.isArray(parsed)) throw new Error();
  2260. roadmap = parsed
  2261. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  2262. .slice(0, 5)
  2263. .map((p) => ({
  2264. topic: p.topic.trim(),
  2265. headline: p.headline.trim(),
  2266. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  2267. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  2268. }));
  2269. } catch {
  2270. roadmap = [];
  2271. }
  2272. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  2273. await db.collection('competitors').updateOne(
  2274. { _id: new ObjectId(request.params.id) },
  2275. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  2276. );
  2277. return { success: true, contentRoadmap: roadmap };
  2278. } catch (err) {
  2279. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  2280. }
  2281. });
  2282. module.exports = app;