server.js 100 KB

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