server.js 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265
  1. require('dotenv').config();
  2. const { createLogger } = require('./utils/logger');
  3. const log = createLogger('gateway');
  4. const app = require('fastify')({ logger: log });
  5. const multipart = require('@fastify/multipart');
  6. const axios = require('axios');
  7. const fs = require('fs');
  8. const path = require('path');
  9. const crypto = require('crypto');
  10. const { pipeline } = require('stream/promises');
  11. const { ObjectId } = require('mongodb');
  12. const { getDb } = require('./utils/MongoDBConnector');
  13. const { encryptToken, decryptToken, warnIfNoKey } = require('./utils/crypto');
  14. const RabbitMQProducer = require('./utils/RabbitMQProducer');
  15. const UPLOAD_DIR = process.env.UPLOAD_DIR || '/uploads';
  16. const ALLOWED_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.mp4', '.mov', '.avi']);
  17. const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
  18. // In-memory job state for async competitor scrapes.
  19. // Max 2 competitors, scrapes complete in seconds — no persistence needed.
  20. const activeScrapeJobs = new Map();
  21. // ─── Platform-native writing rules ────────────────────────────────────────────
  22. // Injected into the AI system prompt when destinations are known.
  23. const PLATFORM_WRITING_RULES = {
  24. twitter: [
  25. 'Keep the post under 200 characters for maximum retweetability.',
  26. 'Use zero to one hashtag — more than one significantly hurts reach.',
  27. 'End with a question or provocation to drive replies.',
  28. 'No slow intros — the hook must land in the opening clause.',
  29. ],
  30. linkedin: [
  31. 'Only the first 2–3 lines are visible before "see more" — the hook must grab immediately.',
  32. 'Put external links in the first comment, not the post body — links in copy reduce reach.',
  33. 'Use 2–3 hashtags maximum, placed at the very end of the post.',
  34. 'Write for practitioners and decision-makers using clear, direct language.',
  35. ],
  36. instagram: [
  37. 'Only the first ~125 characters show before "more" — front-load the hook.',
  38. 'For Reels: hook text must appear on-screen within the first 1 second; assume silent viewing, so text overlays are essential.',
  39. 'Carousels get the highest saves — use them for educational or step-by-step content.',
  40. 'End with a clear call-to-action.',
  41. ],
  42. facebook: [
  43. 'First 3 lines visible before "See more" — lead with the most engaging line.',
  44. 'Conversational tone outperforms corporate language.',
  45. 'Questions and polls significantly boost comments and reach.',
  46. 'External links reduce reach — consider placing the link in the first comment.',
  47. ],
  48. tiktok: [
  49. 'The very first spoken word or on-screen text must hook the viewer at second 0 — no slow intros.',
  50. 'Creator-native feel performs far better than polished corporate openers.',
  51. 'End every script with a comment-bait line (a question or debate prompt).',
  52. 'Optimal caption length: short and punchy; the hook lives in the video, not the caption.',
  53. ],
  54. youtube: [
  55. 'Title must be written for search — include the primary keyword near the front.',
  56. 'Open the script with a 15-second hook that states the value proposition immediately.',
  57. 'First 2 lines of the description appear in search results — write them for click-through.',
  58. 'Always include timestamps/chapters in longer-form descriptions.',
  59. ],
  60. pinterest: [
  61. 'Pinterest is a search engine — descriptions must be keyword-rich prose, not hashtag fragments.',
  62. 'Every pin should link somewhere relevant; linkless pins underperform.',
  63. 'Vertical 2:3 format is optimal for feed visibility.',
  64. 'Use natural-language keyword phrases (e.g. "easy weeknight dinner ideas") not isolated keywords.',
  65. ],
  66. reddit: [
  67. 'Reddit is a community channel, not a publishing channel — never pitch directly.',
  68. 'Write like a practitioner who works at the brand, not a marketer who works for it.',
  69. 'Lead with value: useful data, a genuine question, or an interesting observation.',
  70. 'Match the subreddit tone exactly — formal communities reject casual posts and vice versa.',
  71. ],
  72. mastodon: [
  73. 'Mastodon users value authenticity — corporate marketing tone is poorly received.',
  74. 'Use 3–5 relevant hashtags; they are the primary discovery mechanism on Mastodon.',
  75. 'Longer posts should use a CW (content warning) as a brief summary — this is a community norm.',
  76. 'Engagement comes from genuine conversation, not broadcast-style posting.',
  77. ],
  78. bluesky: [
  79. 'Bluesky rewards original perspectives — repurposed content from other platforms underperforms.',
  80. 'Threads work well for longer ideas; each post in the thread should stand alone.',
  81. 'Use 1–2 hashtags if any — hashtag culture is still developing on Bluesky.',
  82. 'Substance drives sharing here more than engagement-bait does.',
  83. ],
  84. };
  85. function buildPlatformRulesBlock(destinations) {
  86. if (!destinations?.length) return '';
  87. const platforms = [...new Set(destinations.map((d) => d.platform).filter(Boolean))];
  88. const blocks = platforms
  89. .map((p) => {
  90. const rules = PLATFORM_WRITING_RULES[p];
  91. if (!rules?.length) return null;
  92. const name = p.charAt(0).toUpperCase() + p.slice(1);
  93. return `${name} rules:\n${rules.map((r) => `- ${r}`).join('\n')}`;
  94. })
  95. .filter(Boolean);
  96. if (!blocks.length) return '';
  97. return '\n\nPLATFORM-SPECIFIC WRITING RULES (follow these for every post on this platform):\n' + blocks.join('\n\n');
  98. }
  99. fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  100. app.register(multipart, { limits: { fileSize: MAX_FILE_SIZE } });
  101. const GRAPH_API = 'https://graph.facebook.com/v22.0';
  102. // The public base URL of this app (used for OAuth redirect_uri)
  103. const APP_BASE_URL = process.env.APP_BASE_URL || 'http://localhost:8081';
  104. // ─── CORS ────────────────────────────────────────────────────────────────────
  105. app.addHook('onSend', async (request, reply) => {
  106. reply.header('Access-Control-Allow-Origin', '*');
  107. reply.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  108. reply.header('Access-Control-Allow-Headers', 'Content-Type');
  109. });
  110. app.options('*', async (request, reply) => {
  111. reply.code(204).send();
  112. });
  113. // ─── Helpers ─────────────────────────────────────────────────────────────────
  114. async function getCredentials(id) {
  115. const db = await getDb();
  116. return db.collection('platform_credentials').findOne({ _id: id });
  117. }
  118. async function setCredentials(id, data) {
  119. const db = await getDb();
  120. await db.collection('platform_credentials').updateOne(
  121. { _id: id },
  122. { $set: { _id: id, ...data, updatedAt: new Date() } },
  123. { upsert: true }
  124. );
  125. }
  126. async function deleteCredentials(id) {
  127. const db = await getDb();
  128. await db.collection('platform_credentials').deleteOne({ _id: id });
  129. }
  130. // ─── Media Upload & Library ───────────────────────────────────────────────────
  131. app.post('/upload', async (request, reply) => {
  132. const folder = request.query.folder || null;
  133. const data = await request.file();
  134. if (!data) return reply.code(400).send({ error: 'No file provided' });
  135. const ext = path.extname(data.filename).toLowerCase();
  136. if (!ALLOWED_EXTENSIONS.has(ext)) {
  137. data.file.resume();
  138. return reply.code(400).send({ error: `File type "${ext}" is not allowed. Allowed: jpg, jpeg, png, gif, webp, mp4, mov, avi` });
  139. }
  140. const filename = `${crypto.randomUUID()}${ext}`;
  141. const filepath = path.join(UPLOAD_DIR, filename);
  142. try {
  143. await pipeline(data.file, fs.createWriteStream(filepath));
  144. } catch (err) {
  145. app.log.error({ action: 'media_upload', outcome: 'failure', err: err.message });
  146. return reply.code(500).send({ error: 'Failed to save file' });
  147. }
  148. const stat = fs.statSync(filepath);
  149. const record = {
  150. filename,
  151. originalName: data.filename,
  152. url: `/media/${filename}`,
  153. mimetype: data.mimetype,
  154. size: stat.size,
  155. folder: folder || null,
  156. uploadedAt: new Date(),
  157. };
  158. try {
  159. const db = await getDb();
  160. await db.collection('media_files').insertOne(record);
  161. } catch (err) {
  162. app.log.error({ action: 'media_metadata_save', outcome: 'failure', err: err.message });
  163. }
  164. return { url: record.url, filename, originalName: data.filename, mimetype: data.mimetype, size: stat.size, folder: record.folder };
  165. });
  166. // List uploaded media files, newest first; optionally filter by folder
  167. // folder=__none__ → unorganized (null/missing); folder=<name> → that folder; omit → all
  168. app.get('/media-library', async (request) => {
  169. const db = await getDb();
  170. const { folder } = request.query;
  171. const query = {};
  172. if (folder === '__none__') {
  173. query.$or = [{ folder: { $exists: false } }, { folder: null }, { folder: '' }];
  174. } else if (folder) {
  175. query.folder = folder;
  176. }
  177. const files = await db.collection('media_files').find(query).sort({ uploadedAt: -1 }).toArray();
  178. return { files };
  179. });
  180. // List custom folders with per-folder file counts
  181. app.get('/media-folders', async () => {
  182. const db = await getDb();
  183. const [folders, counts] = await Promise.all([
  184. db.collection('media_folders').find({}).sort({ createdAt: 1 }).toArray(),
  185. db.collection('media_files').aggregate([
  186. { $group: { _id: { $ifNull: ['$folder', '__none__'] }, count: { $sum: 1 } } },
  187. ]).toArray(),
  188. ]);
  189. const countMap = Object.fromEntries(counts.map((c) => [c._id, c.count]));
  190. const total = counts.reduce((s, c) => s + c.count, 0);
  191. return {
  192. folders: folders.map((f) => ({ name: f.name, count: countMap[f.name] || 0 })),
  193. totalCount: total,
  194. unorganizedCount: countMap['__none__'] || 0,
  195. folderCounts: countMap,
  196. };
  197. });
  198. // Create a custom folder
  199. app.post('/media-folders', async (request, reply) => {
  200. const { name } = request.body || {};
  201. if (!name?.trim()) return reply.code(400).send({ error: 'Folder name is required' });
  202. const trimmed = name.trim();
  203. const db = await getDb();
  204. if (await db.collection('media_folders').findOne({ name: trimmed })) {
  205. return reply.code(409).send({ error: 'Folder already exists' });
  206. }
  207. await db.collection('media_folders').insertOne({ name: trimmed, createdAt: new Date() });
  208. return { name: trimmed };
  209. });
  210. // Delete a custom folder; files in it become unorganized
  211. app.delete('/media-folders/:name', async (request, reply) => {
  212. const name = decodeURIComponent(request.params.name);
  213. const db = await getDb();
  214. await db.collection('media_folders').deleteOne({ name });
  215. await db.collection('media_files').updateMany({ folder: name }, { $set: { folder: null } });
  216. return { success: true };
  217. });
  218. // Update a file's folder assignment
  219. app.patch('/media/:filename', async (request, reply) => {
  220. const { filename } = request.params;
  221. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  222. return reply.code(400).send({ error: 'Invalid filename' });
  223. }
  224. const { folder } = request.body || {};
  225. const db = await getDb();
  226. const result = await db.collection('media_files').updateOne(
  227. { filename },
  228. { $set: { folder: folder || null } },
  229. );
  230. if (!result.matchedCount) return reply.code(404).send({ error: 'File not found' });
  231. return { success: true };
  232. });
  233. // Delete a media file from disk and database
  234. app.delete('/media/:filename', async (request, reply) => {
  235. const { filename } = request.params;
  236. // Prevent path traversal
  237. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  238. return reply.code(400).send({ error: 'Invalid filename' });
  239. }
  240. const filepath = path.join(UPLOAD_DIR, filename);
  241. try {
  242. fs.unlinkSync(filepath);
  243. } catch (err) {
  244. if (err.code !== 'ENOENT') {
  245. app.log.error({ action: 'media_delete', outcome: 'failure', err: err.message });
  246. return reply.code(500).send({ error: 'Failed to delete file' });
  247. }
  248. // Already gone from disk — still clean up DB record
  249. }
  250. const db = await getDb();
  251. await db.collection('media_files').deleteOne({ filename });
  252. return { success: true };
  253. });
  254. // ─── Drafts ──────────────────────────────────────────────────────────────────
  255. app.post('/drafts', async (request, reply) => {
  256. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  257. const db = await getDb();
  258. const now = new Date();
  259. const result = await db.collection('drafts').insertOne({
  260. content, mediaUrl, scheduledAt, destinations, createdAt: now, updatedAt: now,
  261. });
  262. const draft = await db.collection('drafts').findOne({ _id: result.insertedId });
  263. return reply.code(201).send(draft);
  264. });
  265. app.get('/drafts', async () => {
  266. const db = await getDb();
  267. const drafts = await db.collection('drafts').find({}).sort({ updatedAt: -1 }).toArray();
  268. return { drafts };
  269. });
  270. app.get('/drafts/:id', async (request, reply) => {
  271. const { id } = request.params;
  272. let oid;
  273. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  274. const db = await getDb();
  275. const draft = await db.collection('drafts').findOne({ _id: oid });
  276. if (!draft) return reply.code(404).send({ error: 'Draft not found' });
  277. return draft;
  278. });
  279. app.put('/drafts/:id', async (request, reply) => {
  280. const { id } = request.params;
  281. let oid;
  282. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  283. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  284. const db = await getDb();
  285. const result = await db.collection('drafts').updateOne(
  286. { _id: oid },
  287. { $set: { content, mediaUrl, scheduledAt, destinations, updatedAt: new Date() } }
  288. );
  289. if (!result.matchedCount) return reply.code(404).send({ error: 'Draft not found' });
  290. return { success: true };
  291. });
  292. app.delete('/drafts/:id', async (request, reply) => {
  293. const { id } = request.params;
  294. let oid;
  295. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  296. const db = await getDb();
  297. await db.collection('drafts').deleteOne({ _id: oid });
  298. return { success: true };
  299. });
  300. // ─── Meta Token Expiry & Auto-Refresh ────────────────────────────────────────
  301. let _tokenExpiryCache = null;
  302. let _tokenExpiryCacheAt = 0;
  303. const TOKEN_EXPIRY_TTL = 60 * 60 * 1000; // 1 hour
  304. const TOKEN_REFRESH_THRESHOLD_DAYS = 7; // refresh when ≤ this many days remain
  305. app.get('/meta/token-expiry', async (request, reply) => {
  306. if (_tokenExpiryCache && Date.now() - _tokenExpiryCacheAt < TOKEN_EXPIRY_TTL) {
  307. return _tokenExpiryCache;
  308. }
  309. const appCred = await getCredentials('meta_app');
  310. if (!appCred?.appId || !appCred?.appSecret) return { accounts: [] };
  311. const plainAppSecret = decryptToken(appCred.appSecret);
  312. if (!plainAppSecret) return { accounts: [] };
  313. const ig = await getCredentials('instagram');
  314. const selectedAccounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  315. if (!selectedAccounts.length) return { accounts: [] };
  316. const appToken = `${appCred.appId}|${plainAppSecret}`;
  317. const accounts = [];
  318. for (const account of selectedAccounts) {
  319. const plainToken = decryptToken(account.accessToken);
  320. if (!plainToken) continue;
  321. try {
  322. const res = await axios.get(`${GRAPH_API}/debug_token`, {
  323. params: { input_token: plainToken, access_token: appToken },
  324. timeout: 10000,
  325. });
  326. const data = res.data.data;
  327. const expiresAt = data.expires_at ? new Date(data.expires_at * 1000).toISOString() : null;
  328. const daysLeft = expiresAt
  329. ? Math.ceil((new Date(expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
  330. : null;
  331. accounts.push({ id: account.id, username: account.username, expiresAt, daysLeft, isValid: !!data.is_valid });
  332. } catch (err) {
  333. app.log.warn({ action: 'token_expiry_check', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  334. }
  335. }
  336. _tokenExpiryCache = { accounts, checkedAt: new Date().toISOString() };
  337. _tokenExpiryCacheAt = Date.now();
  338. return _tokenExpiryCache;
  339. });
  340. // Refresh Instagram long-lived tokens that are within TOKEN_REFRESH_THRESHOLD_DAYS of expiry.
  341. // Called by the scheduler's daily BullMQ job; can also be triggered manually from Settings.
  342. app.post('/meta/token-refresh', async (request, reply) => {
  343. const appCred = await getCredentials('meta_app');
  344. if (!appCred?.appId || !appCred?.appSecret) {
  345. return reply.code(400).send({ success: false, error: 'Meta app credentials not configured' });
  346. }
  347. const plainAppSecret = decryptToken(appCred.appSecret);
  348. if (!plainAppSecret) {
  349. return reply.code(500).send({ success: false, error: 'Failed to decrypt app secret' });
  350. }
  351. const ig = await getCredentials('instagram');
  352. const allAccounts = ig?.accounts || [];
  353. const selectedAccounts = allAccounts.filter((a) => a.selected && a.accessToken);
  354. if (!selectedAccounts.length) {
  355. return { success: true, refreshed: 0, skipped: 0, errors: 0 };
  356. }
  357. const appToken = `${appCred.appId}|${plainAppSecret}`;
  358. const refreshed = [];
  359. const skipped = [];
  360. const errors = [];
  361. for (const account of selectedAccounts) {
  362. const plainToken = decryptToken(account.accessToken);
  363. if (!plainToken) {
  364. errors.push({ username: account.username, error: 'decrypt_failed' });
  365. continue;
  366. }
  367. // Check current token expiry via debug_token
  368. let daysLeft = null;
  369. try {
  370. const debugRes = await axios.get(`${GRAPH_API}/debug_token`, {
  371. params: { input_token: plainToken, access_token: appToken },
  372. timeout: 10000,
  373. });
  374. const data = debugRes.data.data;
  375. if (!data.is_valid) {
  376. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'skip', reason: 'invalid_token' });
  377. errors.push({ username: account.username, error: 'token_invalid' });
  378. continue;
  379. }
  380. // expires_at is a Unix timestamp; null means never-expiring (page token etc.)
  381. daysLeft = data.expires_at
  382. ? Math.ceil((data.expires_at * 1000 - Date.now()) / (1000 * 60 * 60 * 24))
  383. : null;
  384. } catch (err) {
  385. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, step: 'debug_token', outcome: 'failure', err: err.message });
  386. errors.push({ username: account.username, error: err.message });
  387. continue;
  388. }
  389. // Token never expires or has plenty of time — skip
  390. if (daysLeft !== null && daysLeft > TOKEN_REFRESH_THRESHOLD_DAYS) {
  391. skipped.push({ username: account.username, daysLeft });
  392. continue;
  393. }
  394. // Refresh: exchange current long-lived token for a new one
  395. try {
  396. const refreshRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  397. params: {
  398. grant_type: 'fb_exchange_token',
  399. client_id: appCred.appId,
  400. client_secret: plainAppSecret,
  401. fb_exchange_token: plainToken,
  402. },
  403. timeout: 15000,
  404. });
  405. // Mutates the element inside allAccounts (same object reference)
  406. account.accessToken = encryptToken(refreshRes.data.access_token);
  407. refreshed.push({ username: account.username, previousDaysLeft: daysLeft });
  408. app.log.info({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'success', previousDaysLeft: daysLeft });
  409. } catch (err) {
  410. app.log.error({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  411. errors.push({ username: account.username, error: err.message });
  412. }
  413. }
  414. if (refreshed.length > 0) {
  415. await setCredentials('instagram', { accounts: allAccounts });
  416. _tokenExpiryCache = null; // force fresh expiry check on next poll
  417. }
  418. app.log.info({ action: 'token_refresh', platform: 'meta', outcome: 'complete', refreshed: refreshed.length, skipped: skipped.length, errors: errors.length });
  419. return { success: true, refreshed: refreshed.length, skipped: skipped.length, errors: errors.length };
  420. });
  421. // ─── Account Profiles ────────────────────────────────────────────────────────
  422. app.get('/profiles', async () => {
  423. const db = await getDb();
  424. const profiles = await db.collection('account_profiles').find({}).toArray();
  425. return { profiles };
  426. });
  427. app.get('/profiles/:accountKey', async (request, reply) => {
  428. const { accountKey } = request.params;
  429. const db = await getDb();
  430. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  431. return profile ?? { _id: accountKey };
  432. });
  433. app.put('/profiles/:accountKey', async (request, reply) => {
  434. const { accountKey } = request.params;
  435. const {
  436. businessName = '', description = '', websiteUrl = '', industry = '',
  437. targetAudience = '', toneOfVoice = '', keywords = '', hashtags = '',
  438. postingGuidelines = '',
  439. } = request.body || {};
  440. const db = await getDb();
  441. await db.collection('account_profiles').updateOne(
  442. { _id: accountKey },
  443. { $set: { businessName, description, websiteUrl, industry, targetAudience, toneOfVoice, keywords, hashtags, postingGuidelines, updatedAt: new Date() } },
  444. { upsert: true }
  445. );
  446. return { success: true };
  447. });
  448. // ─── AI / Multi-provider ─────────────────────────────────────────────────────
  449. const DEFAULT_OLLAMA_ENDPOINT = process.env.OLLAMA_ENDPOINT || 'http://ollama:11434';
  450. const DEFAULT_OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2';
  451. const PROVIDER_MODELS = {
  452. openai: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-3.5-turbo'],
  453. groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768', 'gemma2-9b-it'],
  454. gemini: ['gemini-2.0-flash', 'gemini-1.5-flash', 'gemini-1.5-pro'],
  455. };
  456. const PROVIDER_BASE_URLS = {
  457. openai: 'https://api.openai.com/v1',
  458. groq: 'https://api.groq.com/openai/v1',
  459. };
  460. // Returns decrypted runtime config for the currently active provider
  461. async function getActiveProviderConfig() {
  462. const aiConfig = await getCredentials('ai_config');
  463. const provider = aiConfig?.provider || 'ollama';
  464. if (provider === 'openai' || provider === 'groq') {
  465. const doc = await getCredentials(`${provider}_config`);
  466. return {
  467. provider,
  468. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  469. model: doc?.model || PROVIDER_MODELS[provider][0],
  470. baseUrl: PROVIDER_BASE_URLS[provider],
  471. };
  472. }
  473. if (provider === 'gemini') {
  474. const doc = await getCredentials('gemini_config');
  475. return {
  476. provider,
  477. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  478. model: doc?.model || PROVIDER_MODELS.gemini[0],
  479. };
  480. }
  481. return {
  482. provider: 'ollama',
  483. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  484. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  485. visionModel: aiConfig?.visionModel || 'llava',
  486. };
  487. }
  488. function buildOpenAIMessages(prompt, system) {
  489. const messages = [];
  490. if (system) messages.push({ role: 'system', content: system });
  491. messages.push({ role: 'user', content: prompt });
  492. return messages;
  493. }
  494. // Gemini encodes system as a leading user/model conversation pair
  495. function buildGeminiContents(prompt, system) {
  496. const contents = [];
  497. if (system) {
  498. contents.push({ role: 'user', parts: [{ text: system }] });
  499. contents.push({ role: 'model', parts: [{ text: 'Understood.' }] });
  500. }
  501. contents.push({ role: 'user', parts: [{ text: prompt }] });
  502. return contents;
  503. }
  504. app.get('/ai/config', async () => {
  505. const config = await getCredentials('ai_config');
  506. return {
  507. provider: config?.provider || 'ollama',
  508. endpoint: config?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  509. model: config?.model || DEFAULT_OLLAMA_MODEL,
  510. visionModel: config?.visionModel || 'llava',
  511. enabled: config?.enabled ?? true,
  512. };
  513. });
  514. app.put('/ai/config', async (request, reply) => {
  515. const { provider = 'ollama', endpoint, model, visionModel = 'llava', enabled = true } = request.body || {};
  516. if (provider === 'ollama' && !endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  517. await setCredentials('ai_config', { provider, endpoint, model, visionModel, enabled });
  518. return { success: true };
  519. });
  520. // ─── Provider management routes ───────────────────────────────────────────────
  521. app.get('/ai/providers', async () => {
  522. const aiConfig = await getCredentials('ai_config');
  523. const active = aiConfig?.provider || 'ollama';
  524. const [openaiDoc, groqDoc, geminiDoc] = await Promise.all([
  525. getCredentials('openai_config'),
  526. getCredentials('groq_config'),
  527. getCredentials('gemini_config'),
  528. ]);
  529. return {
  530. active,
  531. providers: [
  532. {
  533. name: 'ollama',
  534. configured: true,
  535. active: active === 'ollama',
  536. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  537. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  538. visionModel: aiConfig?.visionModel || 'llava',
  539. },
  540. {
  541. name: 'openai',
  542. configured: !!openaiDoc?.apiKey,
  543. active: active === 'openai',
  544. model: openaiDoc?.model || PROVIDER_MODELS.openai[0],
  545. apiKeyHint: openaiDoc?.apiKey ? `sk-...${decryptToken(openaiDoc.apiKey).slice(-4)}` : null,
  546. },
  547. {
  548. name: 'groq',
  549. configured: !!groqDoc?.apiKey,
  550. active: active === 'groq',
  551. model: groqDoc?.model || PROVIDER_MODELS.groq[0],
  552. apiKeyHint: groqDoc?.apiKey ? `gsk_...${decryptToken(groqDoc.apiKey).slice(-4)}` : null,
  553. },
  554. {
  555. name: 'gemini',
  556. configured: !!geminiDoc?.apiKey,
  557. active: active === 'gemini',
  558. model: geminiDoc?.model || PROVIDER_MODELS.gemini[0],
  559. apiKeyHint: geminiDoc?.apiKey ? `AIza...${decryptToken(geminiDoc.apiKey).slice(-4)}` : null,
  560. },
  561. ],
  562. };
  563. });
  564. // PUT /ai/provider/:name — save credentials and optionally set as active
  565. // ollama body: { endpoint, model, visionModel, setActive? }
  566. // others body: { apiKey, model, setActive? }
  567. app.put('/ai/provider/:name', async (request, reply) => {
  568. const { name } = request.params;
  569. const { apiKey, model, endpoint, visionModel, setActive = false } = request.body || {};
  570. if (name === 'ollama') {
  571. if (!endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  572. const existing = await getCredentials('ai_config') || {};
  573. await setCredentials('ai_config', {
  574. ...existing,
  575. provider: setActive ? 'ollama' : (existing.provider || 'ollama'),
  576. endpoint,
  577. model: model || DEFAULT_OLLAMA_MODEL,
  578. visionModel: visionModel || 'llava',
  579. });
  580. } else if (['openai', 'groq', 'gemini'].includes(name)) {
  581. if (!apiKey) return reply.code(400).send({ error: 'apiKey is required' });
  582. await setCredentials(`${name}_config`, {
  583. apiKey: encryptToken(apiKey),
  584. model: model || PROVIDER_MODELS[name][0],
  585. });
  586. if (setActive) {
  587. const existing = await getCredentials('ai_config') || {};
  588. await setCredentials('ai_config', { ...existing, provider: name });
  589. }
  590. } else {
  591. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  592. }
  593. return { success: true };
  594. });
  595. // DELETE /ai/provider/:name — remove provider credentials; falls back to ollama if it was active
  596. app.delete('/ai/provider/:name', async (request, reply) => {
  597. const { name } = request.params;
  598. if (name === 'ollama') return reply.code(400).send({ error: 'Cannot remove Ollama provider' });
  599. if (!['openai', 'groq', 'gemini'].includes(name)) return reply.code(404).send({ error: `Unknown provider: ${name}` });
  600. const db = await getDb();
  601. await db.collection('platform_credentials').deleteOne({ _id: `${name}_config` });
  602. const aiConfig = await getCredentials('ai_config') || {};
  603. if (aiConfig.provider === name) {
  604. await setCredentials('ai_config', { ...aiConfig, provider: 'ollama' });
  605. }
  606. return { success: true };
  607. });
  608. // POST /ai/provider/:name/models — list models for a provider (test without saving key)
  609. app.post('/ai/provider/:name/models', async (request, reply) => {
  610. const { name } = request.params;
  611. const { apiKey: bodyApiKey, endpoint: bodyEndpoint } = request.body || {};
  612. if (name === 'ollama') {
  613. const aiConfig = await getCredentials('ai_config');
  614. const ep = bodyEndpoint || aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  615. try {
  616. const res = await axios.get(`${ep}/api/tags`, { timeout: 5000 });
  617. return { models: (res.data.models || []).map((m) => m.name) };
  618. } catch (err) {
  619. return reply.code(503).send({ error: 'Could not reach Ollama', detail: err.message });
  620. }
  621. }
  622. if (['openai', 'groq', 'gemini'].includes(name)) {
  623. return { models: PROVIDER_MODELS[name] };
  624. }
  625. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  626. });
  627. app.get('/ai/models', async (request, reply) => {
  628. const config = await getCredentials('ai_config');
  629. const provider = config?.provider || 'ollama';
  630. if (provider !== 'ollama') {
  631. return { models: PROVIDER_MODELS[provider] || [], provider };
  632. }
  633. const endpoint = request.query.endpoint || config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  634. try {
  635. const res = await axios.get(`${endpoint}/api/tags`, { timeout: 5000 });
  636. const models = (res.data.models || []).map((m) => m.name);
  637. return { models, endpoint };
  638. } catch (err) {
  639. return reply.code(503).send({ error: 'Could not reach Ollama — check the endpoint', detail: err.message });
  640. }
  641. });
  642. app.post('/ai/generate', async (request, reply) => {
  643. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, destinations } = request.body || {};
  644. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  645. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  646. const platformRules = buildPlatformRulesBlock(destinations);
  647. const system = rawSystem ? rawSystem + competitorSuffix + platformRules : ((competitorSuffix + platformRules) || undefined);
  648. const pconf = await getActiveProviderConfig();
  649. const model = reqModel || pconf.model;
  650. try {
  651. if (pconf.provider === 'ollama') {
  652. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  653. return { text: res.data.response, model, done: res.data.done };
  654. }
  655. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  656. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  657. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  658. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  659. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  660. return { text: res.data.choices[0]?.message?.content || '', model, done: true };
  661. }
  662. if (pconf.provider === 'gemini') {
  663. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  664. const res = await axios.post(
  665. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  666. { contents: buildGeminiContents(prompt, system) },
  667. { timeout: 90000 },
  668. );
  669. return { text: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model, done: true };
  670. }
  671. return reply.code(400).send({ error: `Unknown provider: ${pconf.provider}` });
  672. } catch (err) {
  673. const status = err.response?.status || 503;
  674. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  675. }
  676. });
  677. 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.';
  678. // Vision caption — supports ollama, openai, gemini (groq has no vision)
  679. app.post('/ai/caption', async (request, reply) => {
  680. const { imageUrl, model: reqModel } = request.body || {};
  681. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  682. const pconf = await getActiveProviderConfig();
  683. let imageBase64, imageMime;
  684. try {
  685. let imageBuffer;
  686. if (imageUrl.startsWith('/media/')) {
  687. const filename = path.basename(imageUrl);
  688. imageBuffer = fs.readFileSync(path.join(UPLOAD_DIR, filename));
  689. } else {
  690. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  691. imageBuffer = Buffer.from(imgRes.data);
  692. imageMime = imgRes.headers['content-type'] || 'image/jpeg';
  693. }
  694. imageBase64 = imageBuffer.toString('base64');
  695. if (!imageMime) imageMime = 'image/jpeg';
  696. } catch (err) {
  697. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  698. }
  699. try {
  700. const model = reqModel || pconf.visionModel || pconf.model;
  701. if (pconf.provider === 'ollama') {
  702. const res = await axios.post(`${pconf.endpoint}/api/generate`, {
  703. model, prompt: CAPTION_PROMPT, images: [imageBase64], stream: false,
  704. }, { timeout: 90000 });
  705. return { caption: res.data.response, model };
  706. }
  707. if (pconf.provider === 'openai') {
  708. if (!pconf.apiKey) return reply.code(503).send({ error: 'OpenAI API key not configured' });
  709. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  710. model: model || 'gpt-4o',
  711. messages: [{ role: 'user', content: [
  712. { type: 'text', text: CAPTION_PROMPT },
  713. { type: 'image_url', image_url: { url: `data:${imageMime};base64,${imageBase64}` } },
  714. ]}],
  715. stream: false,
  716. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  717. return { caption: res.data.choices[0]?.message?.content || '', model };
  718. }
  719. if (pconf.provider === 'gemini') {
  720. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  721. const geminiModel = model || 'gemini-1.5-flash';
  722. const res = await axios.post(
  723. `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${pconf.apiKey}`,
  724. { contents: [{ role: 'user', parts: [
  725. { text: CAPTION_PROMPT },
  726. { inlineData: { mimeType: imageMime, data: imageBase64 } },
  727. ]}]},
  728. { timeout: 90000 },
  729. );
  730. return { caption: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model: geminiModel };
  731. }
  732. return reply.code(400).send({ error: `Provider ${pconf.provider} does not support vision captions` });
  733. } catch (err) {
  734. const status = err.response?.status || 503;
  735. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  736. }
  737. });
  738. // SSE streaming endpoint — normalized data: { token, done } format for all providers
  739. app.post('/ai/stream', async (request, reply) => {
  740. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, destinations } = request.body || {};
  741. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  742. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  743. const platformRules = buildPlatformRulesBlock(destinations);
  744. const system = rawSystem ? rawSystem + competitorSuffix + platformRules : ((competitorSuffix + platformRules) || undefined);
  745. const pconf = await getActiveProviderConfig();
  746. const model = reqModel || pconf.model;
  747. reply.raw.setHeader('Content-Type', 'text/event-stream');
  748. reply.raw.setHeader('Cache-Control', 'no-cache');
  749. reply.raw.setHeader('X-Accel-Buffering', 'no');
  750. reply.raw.setHeader('Connection', 'keep-alive');
  751. reply.raw.flushHeaders();
  752. const writeToken = (token, done = false) => reply.raw.write(`data: ${JSON.stringify({ token, done })}\n\n`);
  753. const writeError = (msg) => { reply.raw.write(`data: ${JSON.stringify({ error: msg, done: true })}\n\n`); reply.raw.end(); };
  754. try {
  755. if (pconf.provider === 'ollama') {
  756. const ollamaRes = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  757. ollamaRes.data.on('data', (chunk) => {
  758. try {
  759. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  760. const data = JSON.parse(line);
  761. writeToken(data.response || '', !!data.done);
  762. }
  763. } catch (_) {}
  764. });
  765. ollamaRes.data.on('end', () => reply.raw.end());
  766. ollamaRes.data.on('error', (err) => writeError(err.message));
  767. return;
  768. }
  769. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  770. if (!pconf.apiKey) return writeError(`${pconf.provider} API key not configured`);
  771. const upstreamRes = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  772. model, messages: buildOpenAIMessages(prompt, system), stream: true,
  773. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, responseType: 'stream', timeout: 120000 });
  774. upstreamRes.data.on('data', (chunk) => {
  775. try {
  776. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  777. if (!line.startsWith('data: ')) continue;
  778. const payload = line.slice(6).trim();
  779. if (payload === '[DONE]') { writeToken('', true); return; }
  780. const data = JSON.parse(payload);
  781. const token = data.choices?.[0]?.delta?.content || '';
  782. if (token) writeToken(token);
  783. }
  784. } catch (_) {}
  785. });
  786. upstreamRes.data.on('end', () => reply.raw.end());
  787. upstreamRes.data.on('error', (err) => writeError(err.message));
  788. return;
  789. }
  790. if (pconf.provider === 'gemini') {
  791. if (!pconf.apiKey) return writeError('Gemini API key not configured');
  792. const geminiRes = await axios.post(
  793. `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${pconf.apiKey}`,
  794. { contents: buildGeminiContents(prompt, system) },
  795. { responseType: 'stream', timeout: 120000 },
  796. );
  797. geminiRes.data.on('data', (chunk) => {
  798. try {
  799. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  800. if (!line.startsWith('data: ')) continue;
  801. const data = JSON.parse(line.slice(6));
  802. const token = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  803. if (token) writeToken(token);
  804. }
  805. } catch (_) {}
  806. });
  807. geminiRes.data.on('end', () => { writeToken('', true); reply.raw.end(); });
  808. geminiRes.data.on('error', (err) => writeError(err.message));
  809. return;
  810. }
  811. writeError(`Unknown provider: ${pconf.provider}`);
  812. } catch (err) {
  813. writeError(err.message);
  814. }
  815. });
  816. // ─── Monthly Content Calendar ─────────────────────────────────────────────────
  817. // POST /ai/content-calendar — generate a monthly content plan with narrative brief + sample posts
  818. // Body: { accountKey?, platforms[], month? (YYYY-MM) }
  819. app.post('/ai/content-calendar', async (request, reply) => {
  820. const { accountKey, platforms = [], month } = request.body || {};
  821. if (!platforms.length) return reply.code(400).send({ error: 'Select at least one platform' });
  822. const db = await getDb();
  823. const calMonth = month || new Date().toISOString().slice(0, 7);
  824. const [year, mon] = calMonth.split('-');
  825. const monthName = new Date(`${calMonth}-01`).toLocaleString('en', { month: 'long', year: 'numeric' });
  826. // Load account profile for context
  827. const profileKey = accountKey || null;
  828. const profile = profileKey
  829. ? await db.collection('account_profiles').findOne({ _id: profileKey })
  830. : await db.collection('account_profiles').findOne({});
  831. const contextParts = ['You are a social media content strategist.'];
  832. if (profile) {
  833. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  834. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  835. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  836. if (profile.toneOfVoice) contextParts.push(`Tone of voice: ${profile.toneOfVoice}`);
  837. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  838. if (profile.keywords) contextParts.push(`Keywords: ${profile.keywords}`);
  839. }
  840. const brandContext = contextParts.join('\n');
  841. // Per-platform post count: 3 per platform (weeks 1–3)
  842. const platformList = platforms.slice(0, 5).join(', ');
  843. const postsPerPlatform = 3;
  844. const totalPosts = platforms.slice(0, 5).length * postsPerPlatform;
  845. const system = 'You are a social media content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  846. const prompt = `${brandContext}
  847. Create a content calendar for ${monthName} across these platforms: ${platformList}.
  848. Return a JSON object with exactly these fields:
  849. {
  850. "brief": {
  851. "theme": "The overarching monthly narrative theme in one sentence",
  852. "pillars": ["3-4 content pillars that anchor all posts this month"],
  853. "toneGuidance": "One sentence on tone and voice for this month",
  854. "platformNotes": {
  855. ${platforms.slice(0, 5).map((p) => `"${p}": "One sentence of platform-specific content strategy for ${p}"`).join(',\n ')}
  856. }
  857. },
  858. "posts": [
  859. ${platforms.slice(0, 5).flatMap((p, pi) =>
  860. [1, 2, 3].map((w, wi) => `{
  861. "platform": "${p}",
  862. "week": ${w},
  863. "content": "<full post text ready to publish, following platform-specific best practices>",
  864. "hashtags": ["<2-4 relevant hashtags>"],
  865. "postType": "<educational|promotional|engagement|storytelling>",
  866. "suggestedDay": "<best day of week to publish on ${p}>"
  867. }${pi < platforms.length - 1 || wi < 2 ? ',' : ''}`)).join('\n ')}
  868. ]
  869. }
  870. Important: Each post must follow platform conventions — LinkedIn hooks in first 2 lines, TikTok scripts with second-0 hook, Instagram assuming silent viewing, etc.
  871. Return ONLY the JSON object.`;
  872. try {
  873. const pconf = await getActiveProviderConfig();
  874. const model = pconf.model;
  875. let text = '';
  876. if (pconf.provider === 'ollama') {
  877. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  878. text = res.data.response;
  879. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  880. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  881. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  882. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  883. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  884. text = res.data.choices[0]?.message?.content || '';
  885. } else if (pconf.provider === 'gemini') {
  886. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  887. const res = await axios.post(
  888. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  889. { contents: buildGeminiContents(prompt, system) },
  890. { timeout: 180000 },
  891. );
  892. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  893. } else {
  894. return reply.code(400).send({ error: 'AI not configured' });
  895. }
  896. let calendar = null;
  897. try {
  898. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  899. calendar = JSON.parse(jsonStr);
  900. if (!calendar.brief || !Array.isArray(calendar.posts)) throw new Error();
  901. // Normalise
  902. if (!Array.isArray(calendar.brief.pillars)) calendar.brief.pillars = [];
  903. if (typeof calendar.brief.theme !== 'string') calendar.brief.theme = '';
  904. calendar.posts = calendar.posts.filter((p) => p && typeof p.content === 'string').slice(0, totalPosts);
  905. } catch {
  906. return reply.code(503).send({ error: 'AI returned invalid calendar format — try again' });
  907. }
  908. const doc = {
  909. accountKey: accountKey || null,
  910. month: calMonth,
  911. monthName,
  912. platforms,
  913. brief: calendar.brief,
  914. posts: calendar.posts,
  915. createdAt: new Date(),
  916. };
  917. const result = await db.collection('content_calendars').insertOne(doc);
  918. log.info({ action: 'content_calendar', month: calMonth, platforms: platforms.join(','), posts: calendar.posts.length, outcome: 'success' });
  919. return { success: true, calendarId: result.insertedId.toString(), ...doc };
  920. } catch (err) {
  921. return reply.code(503).send({ error: 'Calendar generation failed', detail: err.message });
  922. }
  923. });
  924. // GET /ai/content-calendar/:id — retrieve a saved calendar
  925. app.get('/ai/content-calendar/:id', async (request, reply) => {
  926. let oid;
  927. try { oid = new ObjectId(request.params.id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  928. const db = await getDb();
  929. const cal = await db.collection('content_calendars').findOne({ _id: oid });
  930. if (!cal) return reply.code(404).send({ error: 'Calendar not found' });
  931. return { calendarId: cal._id.toString(), ...cal };
  932. });
  933. // GET /ai/content-calendars — list recent calendars
  934. app.get('/ai/content-calendars', async (request, reply) => {
  935. const db = await getDb();
  936. const cals = await db.collection('content_calendars')
  937. .find({}, { projection: { posts: 0 } })
  938. .sort({ createdAt: -1 })
  939. .limit(20)
  940. .toArray();
  941. return { calendars: cals.map((c) => ({ calendarId: c._id.toString(), month: c.month, monthName: c.monthName, platforms: c.platforms, brief: c.brief, createdAt: c.createdAt })) };
  942. });
  943. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  944. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  945. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  946. app.post('/ai/bulk-draft', async (request, reply) => {
  947. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  948. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  949. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  950. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  951. const db = await getDb();
  952. const batchId = new ObjectId();
  953. const now = new Date();
  954. await db.collection('bulk_draft_batches').insertOne({
  955. _id: batchId,
  956. total: filteredTopics.length,
  957. completed: 0,
  958. failed: 0,
  959. status: 'processing',
  960. createdAt: now,
  961. updatedAt: now,
  962. });
  963. const selectedDests = destinations.filter((d) => d.selected);
  964. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  965. const platformRules = buildPlatformRulesBlock(selectedDests);
  966. 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.${platformRules}`;
  967. // Fire-and-forget — process topics sequentially in the background
  968. (async () => {
  969. const pconf = await getActiveProviderConfig();
  970. const model = reqModel || pconf.model;
  971. for (const topic of filteredTopics) {
  972. try {
  973. const prompt = `Write a social media post about: ${topic}`;
  974. let content = '';
  975. if (pconf.provider === 'ollama') {
  976. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  977. content = res.data.response || '';
  978. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  979. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  980. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  981. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  982. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  983. content = res.data.choices[0]?.message?.content || '';
  984. } else if (pconf.provider === 'gemini') {
  985. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  986. const res = await axios.post(
  987. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  988. { contents: buildGeminiContents(prompt, system) },
  989. { timeout: 90000 },
  990. );
  991. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  992. }
  993. if (content.trim()) {
  994. const draftNow = new Date();
  995. await db.collection('drafts').insertOne({
  996. content: content.trim(),
  997. mediaUrl: '',
  998. scheduledAt: '',
  999. destinations: selectedDests,
  1000. batchId: batchId.toString(),
  1001. topic,
  1002. createdAt: draftNow,
  1003. updatedAt: draftNow,
  1004. });
  1005. }
  1006. await db.collection('bulk_draft_batches').updateOne(
  1007. { _id: batchId },
  1008. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  1009. );
  1010. } catch (err) {
  1011. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  1012. await db.collection('bulk_draft_batches').updateOne(
  1013. { _id: batchId },
  1014. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  1015. );
  1016. }
  1017. }
  1018. await db.collection('bulk_draft_batches').updateOne(
  1019. { _id: batchId },
  1020. { $set: { status: 'done', updatedAt: new Date() } },
  1021. );
  1022. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  1023. })().catch((err) => {
  1024. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  1025. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  1026. { _id: batchId },
  1027. { $set: { status: 'failed', updatedAt: new Date() } },
  1028. )).catch(() => {});
  1029. });
  1030. return reply.code(202).send({ batchId: batchId.toString() });
  1031. });
  1032. // GET /ai/bulk-draft/:batchId — poll batch progress
  1033. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  1034. const { batchId } = request.params;
  1035. let oid;
  1036. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  1037. const db = await getDb();
  1038. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid });
  1039. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  1040. return {
  1041. batchId: batch._id.toString(),
  1042. total: batch.total,
  1043. completed: batch.completed,
  1044. failed: batch.failed,
  1045. status: batch.status,
  1046. processed: batch.completed + batch.failed,
  1047. };
  1048. });
  1049. // ─── Platform service URLs ────────────────────────────────────────────────────
  1050. const PLATFORM_SERVICES = {
  1051. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  1052. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  1053. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  1054. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  1055. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  1056. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  1057. };
  1058. // Direct multi-platform post endpoint.
  1059. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  1060. app.post('/post', async (request, reply) => {
  1061. const { content, destinations = [], firstComment } = request.body || {};
  1062. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  1063. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  1064. const results = await Promise.allSettled(
  1065. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  1066. const serviceUrl = PLATFORM_SERVICES[platform];
  1067. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  1068. const res = await axios.post(
  1069. `${serviceUrl}/post`,
  1070. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  1071. { timeout: 30000 }
  1072. );
  1073. return { platform, accountId, ...res.data };
  1074. })
  1075. );
  1076. const output = results.map((r, i) =>
  1077. r.status === 'fulfilled'
  1078. ? r.value
  1079. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  1080. );
  1081. const anyFailed = output.some((r) => !r.success);
  1082. const anySucceeded = output.some((r) => r.success);
  1083. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  1084. // Record the post for analytics
  1085. try {
  1086. const db = await getDb();
  1087. await db.collection('posts').insertOne({
  1088. _id: crypto.randomUUID(),
  1089. type: 'immediate',
  1090. content,
  1091. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  1092. destinations,
  1093. platformResults: Object.fromEntries(
  1094. output.map((r) => [
  1095. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  1096. { success: r.success, ...(r.error && { error: r.error }) },
  1097. ])
  1098. ),
  1099. status: postStatus,
  1100. publishedAt: new Date(),
  1101. createdAt: new Date(),
  1102. });
  1103. } catch (err) {
  1104. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  1105. }
  1106. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  1107. });
  1108. // ─── Legacy post route ────────────────────────────────────────────────────────
  1109. let rabbitMQProducer = new RabbitMQProducer();
  1110. app.post('/', async (request, reply) => {
  1111. try {
  1112. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  1113. reply.send({ status: 'ok' });
  1114. } catch (error) {
  1115. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  1116. reply.status(500).send({ error: 'Internal Server Error' });
  1117. }
  1118. });
  1119. // ─── Meta App Credentials ────────────────────────────────────────────────────
  1120. // Save Facebook App ID + Secret (entered by user in Settings UI)
  1121. app.post('/credentials/meta-app', async (request, reply) => {
  1122. const { appId, appSecret } = request.body || {};
  1123. if (!appId || !appSecret) {
  1124. return reply.code(400).send({ error: 'appId and appSecret are required' });
  1125. }
  1126. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  1127. return { success: true };
  1128. });
  1129. // Get Meta App config (secret is masked for UI display)
  1130. app.get('/credentials/meta-app', async () => {
  1131. const cred = await getCredentials('meta_app');
  1132. if (!cred) return { configured: false };
  1133. const plainSecret = decryptToken(cred.appSecret) || '';
  1134. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  1135. });
  1136. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  1137. // Return the Facebook OAuth URL to redirect the user to
  1138. app.get('/auth/meta/init', async (request, reply) => {
  1139. const cred = await getCredentials('meta_app');
  1140. if (!cred?.appId) {
  1141. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  1142. }
  1143. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1144. const scopes = [
  1145. 'pages_manage_posts',
  1146. 'pages_read_engagement',
  1147. 'instagram_basic',
  1148. 'instagram_content_publish',
  1149. 'instagram_manage_insights',
  1150. ].join(',');
  1151. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  1152. return { url };
  1153. });
  1154. // OAuth callback — Facebook redirects here after user authorises
  1155. app.get('/auth/meta/callback', async (request, reply) => {
  1156. const { code, error: oauthError } = request.query;
  1157. if (oauthError) {
  1158. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  1159. }
  1160. if (!code) {
  1161. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  1162. }
  1163. try {
  1164. const appCred = await getCredentials('meta_app');
  1165. if (!appCred?.appId) throw new Error('App credentials not configured');
  1166. const appSecret = decryptToken(appCred.appSecret);
  1167. if (!appSecret) throw new Error('Failed to decrypt app secret');
  1168. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1169. // Exchange code for short-lived token
  1170. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1171. params: {
  1172. client_id: appCred.appId,
  1173. client_secret: appSecret,
  1174. redirect_uri: redirectUri,
  1175. code,
  1176. },
  1177. });
  1178. // Upgrade to long-lived user token (~60 days)
  1179. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1180. params: {
  1181. grant_type: 'fb_exchange_token',
  1182. client_id: appCred.appId,
  1183. client_secret: appSecret,
  1184. fb_exchange_token: shortRes.data.access_token,
  1185. },
  1186. });
  1187. const userToken = longRes.data.access_token;
  1188. // Fetch all managed Facebook Pages
  1189. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  1190. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  1191. });
  1192. const pages = [];
  1193. const igAccounts = [];
  1194. for (const page of pagesRes.data.data || []) {
  1195. pages.push({
  1196. id: page.id,
  1197. name: page.name,
  1198. accessToken: encryptToken(page.access_token),
  1199. picture: page.picture?.data?.url || null,
  1200. selected: false,
  1201. });
  1202. // Check for linked Instagram Business Account
  1203. try {
  1204. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  1205. params: {
  1206. fields: 'instagram_business_account',
  1207. access_token: page.access_token,
  1208. },
  1209. });
  1210. if (igRes.data.instagram_business_account?.id) {
  1211. const igId = igRes.data.instagram_business_account.id;
  1212. // Fetch IG account details
  1213. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1214. params: {
  1215. fields: 'id,username,name,profile_picture_url',
  1216. access_token: userToken,
  1217. },
  1218. });
  1219. igAccounts.push({
  1220. id: igId,
  1221. username: igProfile.data.username || igProfile.data.name,
  1222. name: igProfile.data.name,
  1223. avatar: igProfile.data.profile_picture_url || null,
  1224. accessToken: encryptToken(userToken),
  1225. pageId: page.id,
  1226. selected: false,
  1227. });
  1228. }
  1229. } catch (_) {
  1230. // Page has no linked Instagram account — skip
  1231. }
  1232. }
  1233. // Store discovery results for the UI to pick from
  1234. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1235. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1236. } catch (err) {
  1237. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1238. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1239. }
  1240. });
  1241. // Return pending discovery results so the UI can render the page picker
  1242. app.get('/auth/meta/discovered', async () => {
  1243. const discovery = await getCredentials('meta_discovery');
  1244. if (!discovery) return { pages: [], igAccounts: [] };
  1245. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1246. });
  1247. // User has chosen which pages/accounts to connect
  1248. app.post('/auth/meta/save', async (request, reply) => {
  1249. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1250. const discovery = await getCredentials('meta_discovery');
  1251. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1252. const fbPages = (discovery.pages || []).map((p) => ({
  1253. ...p,
  1254. selected: selectedPageIds.includes(p.id),
  1255. }));
  1256. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1257. ...a,
  1258. selected: selectedIgAccountIds.includes(a.id),
  1259. }));
  1260. await setCredentials('facebook', { pages: fbPages });
  1261. await setCredentials('instagram', { accounts: igAccounts });
  1262. await deleteCredentials('meta_discovery');
  1263. _tokenExpiryCache = null; // invalidate cache after reconnect
  1264. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1265. });
  1266. // Disconnect all Meta platforms
  1267. app.delete('/credentials/meta', async () => {
  1268. await deleteCredentials('facebook');
  1269. await deleteCredentials('instagram');
  1270. await deleteCredentials('meta_discovery');
  1271. return { success: true };
  1272. });
  1273. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1274. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1275. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1276. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1277. app.post('/credentials/pinterest-app', async (request, reply) => {
  1278. const { clientId, clientSecret } = request.body || {};
  1279. if (!clientId || !clientSecret) {
  1280. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1281. }
  1282. await setCredentials('pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1283. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1284. return { success: true };
  1285. });
  1286. app.get('/credentials/pinterest-app', async () => {
  1287. const cred = await getCredentials('pinterest_app');
  1288. if (!cred) return { configured: false };
  1289. const plain = decryptToken(cred.clientSecret) || '';
  1290. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1291. });
  1292. app.get('/auth/pinterest/init', async (request, reply) => {
  1293. const cred = await getCredentials('pinterest_app');
  1294. if (!cred?.clientId) {
  1295. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1296. }
  1297. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1298. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1299. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1300. return { url };
  1301. });
  1302. app.get('/auth/pinterest/callback', async (request, reply) => {
  1303. const { code, error: oauthError } = request.query;
  1304. if (oauthError) {
  1305. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1306. }
  1307. if (!code) {
  1308. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1309. }
  1310. try {
  1311. const appCred = await getCredentials('pinterest_app');
  1312. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1313. const clientSecret = decryptToken(appCred.clientSecret);
  1314. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1315. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1316. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1317. const tokenRes = await axios.post(
  1318. PINTEREST_TOKEN_URL,
  1319. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1320. {
  1321. headers: {
  1322. Authorization: `Basic ${basicAuth}`,
  1323. 'Content-Type': 'application/x-www-form-urlencoded',
  1324. },
  1325. timeout: 15000,
  1326. }
  1327. );
  1328. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1329. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1330. const [userRes, boardsRes] = await Promise.all([
  1331. axios.get(`${PINTEREST_API}/user_account`, {
  1332. headers: { Authorization: `Bearer ${access_token}` },
  1333. timeout: 10000,
  1334. }),
  1335. axios.get(`${PINTEREST_API}/boards`, {
  1336. headers: { Authorization: `Bearer ${access_token}` },
  1337. params: { page_size: 100 },
  1338. timeout: 15000,
  1339. }),
  1340. ]);
  1341. const boards = (boardsRes.data.items || []).map((b) => ({
  1342. id: b.id,
  1343. name: b.name,
  1344. privacy: b.privacy,
  1345. selected: false,
  1346. }));
  1347. await setCredentials('pinterest', {
  1348. userId: userRes.data.username,
  1349. username: userRes.data.username,
  1350. displayName: userRes.data.business_name || userRes.data.username,
  1351. avatar: userRes.data.profile_image,
  1352. accessToken: encryptToken(access_token),
  1353. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1354. tokenExpiry,
  1355. boards,
  1356. });
  1357. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1358. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1359. } catch (err) {
  1360. const msg = err.response?.data?.message || err.message;
  1361. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1362. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1363. }
  1364. });
  1365. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1366. const { selectedBoardIds = [] } = request.body || {};
  1367. const cred = await getCredentials('pinterest');
  1368. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1369. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1370. await setCredentials('pinterest', { ...cred, boards });
  1371. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1372. return { success: true, selected: boards.filter((b) => b.selected).length };
  1373. });
  1374. app.delete('/credentials/pinterest', async () => {
  1375. await deleteCredentials('pinterest');
  1376. return { success: true };
  1377. });
  1378. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1379. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1380. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1381. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1382. app.post('/credentials/tiktok-app', async (request, reply) => {
  1383. const { clientKey, clientSecret } = request.body || {};
  1384. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1385. await setCredentials('tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1386. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1387. return { success: true };
  1388. });
  1389. app.get('/credentials/tiktok-app', async () => {
  1390. const cred = await getCredentials('tiktok_app');
  1391. if (!cred?.clientKey) return { configured: false };
  1392. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1393. });
  1394. app.get('/auth/tiktok/init', async (request, reply) => {
  1395. const cred = await getCredentials('tiktok_app');
  1396. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1397. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1398. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1399. const state = crypto.randomBytes(16).toString('hex');
  1400. // Persist PKCE verifier for the callback
  1401. const db = await getDb();
  1402. await db.collection('platform_credentials').updateOne(
  1403. { _id: 'tiktok_pkce' },
  1404. { $set: { codeVerifier, state, createdAt: new Date() } },
  1405. { upsert: true }
  1406. );
  1407. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1408. const scopes = 'user.info.basic,video.list,video.publish';
  1409. const params = new URLSearchParams({
  1410. client_key: cred.clientKey,
  1411. scope: scopes,
  1412. response_type: 'code',
  1413. redirect_uri: redirectUri,
  1414. state,
  1415. code_challenge: codeChallenge,
  1416. code_challenge_method: 'S256',
  1417. });
  1418. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1419. });
  1420. app.get('/auth/tiktok/callback', async (request, reply) => {
  1421. const { code, state, error: oauthError, error_description } = request.query;
  1422. if (oauthError) {
  1423. const msg = error_description || oauthError;
  1424. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1425. }
  1426. if (!code) {
  1427. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1428. }
  1429. try {
  1430. const db = await getDb();
  1431. const pkce = await db.collection('platform_credentials').findOne({ _id: 'tiktok_pkce' });
  1432. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1433. if (state && pkce.state && state !== pkce.state) throw new Error('OAuth state mismatch');
  1434. const appCred = await getCredentials('tiktok_app');
  1435. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1436. const clientSecret = decryptToken(appCred.clientSecret);
  1437. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1438. const tokenRes = await axios.post(
  1439. TIKTOK_TOKEN_URL,
  1440. new URLSearchParams({
  1441. client_key: appCred.clientKey,
  1442. client_secret: clientSecret,
  1443. code,
  1444. grant_type: 'authorization_code',
  1445. redirect_uri: redirectUri,
  1446. code_verifier: pkce.codeVerifier,
  1447. }).toString(),
  1448. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1449. );
  1450. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1451. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1452. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1453. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1454. headers: { Authorization: `Bearer ${access_token}` },
  1455. params: { fields: 'open_id,display_name,avatar_url,username' },
  1456. timeout: 10000,
  1457. });
  1458. const user = userRes.data?.data?.user || {};
  1459. await setCredentials('tiktok', {
  1460. openId: open_id || user.open_id,
  1461. username: user.username || user.display_name,
  1462. displayName: user.display_name,
  1463. avatar: user.avatar_url || null,
  1464. accessToken: encryptToken(access_token),
  1465. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1466. tokenExpiry,
  1467. refreshExpiry,
  1468. });
  1469. // Clean up PKCE temp state
  1470. await db.collection('platform_credentials').deleteOne({ _id: 'tiktok_pkce' });
  1471. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1472. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1473. } catch (err) {
  1474. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1475. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1476. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1477. }
  1478. });
  1479. app.delete('/credentials/tiktok', async () => {
  1480. await deleteCredentials('tiktok');
  1481. return { success: true };
  1482. });
  1483. // ─── Credential Status ────────────────────────────────────────────────────────
  1484. // Aggregate connection status for all DB-managed platforms
  1485. app.get('/credentials', async () => {
  1486. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1487. getCredentials('meta_app'),
  1488. getCredentials('facebook'),
  1489. getCredentials('instagram'),
  1490. getCredentials('pinterest'),
  1491. getCredentials('tiktok'),
  1492. ]);
  1493. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1494. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1495. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1496. return {
  1497. metaApp: { configured: !!(metaApp?.appId) },
  1498. facebook: {
  1499. connected: fbPages.length > 0,
  1500. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1501. },
  1502. instagram: {
  1503. connected: igAccounts.length > 0,
  1504. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1505. },
  1506. pinterest: {
  1507. connected: pinterestBoards.length > 0,
  1508. username: pinterest?.username || null,
  1509. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1510. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1511. },
  1512. tiktok: {
  1513. connected: !!(tiktok?.accessToken),
  1514. username: tiktok?.username || null,
  1515. displayName: tiktok?.displayName || null,
  1516. avatar: tiktok?.avatar || null,
  1517. },
  1518. };
  1519. });
  1520. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1521. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1522. const INDUSTRY_DEFAULTS = {
  1523. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1524. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1525. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1526. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1527. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1528. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1529. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1530. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1531. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1532. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  1533. };
  1534. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  1535. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  1536. // at least `afterMs` milliseconds in the future.
  1537. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  1538. const candidate = new Date(afterMs);
  1539. candidate.setUTCHours(hourUTC, 0, 0, 0);
  1540. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  1541. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  1542. candidate.setUTCDate(candidate.getUTCDate() + 7);
  1543. } else {
  1544. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  1545. }
  1546. return candidate;
  1547. }
  1548. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  1549. app.get('/schedule/suggestions', async (request, reply) => {
  1550. const { platform, accountId } = request.query;
  1551. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  1552. const db = await getDb();
  1553. const query = { platform, ...(accountId && { accountId }) };
  1554. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  1555. let slots;
  1556. let source;
  1557. if (dataPoints >= 10) {
  1558. const agg = await db.collection('post_metrics').aggregate([
  1559. { $match: query },
  1560. { $group: {
  1561. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1562. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1563. count: { $sum: 1 },
  1564. }},
  1565. { $sort: { avgEngagement: -1 } },
  1566. { $limit: 5 },
  1567. ]).toArray();
  1568. slots = agg.map((r) => [r._id.day, r._id.hour]);
  1569. source = 'history';
  1570. } else {
  1571. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  1572. source = 'default';
  1573. }
  1574. // 30-minute lead time so the user has time to finish writing
  1575. const afterMs = Date.now() + 30 * 60 * 1000;
  1576. const suggestions = slots
  1577. .map(([day, hour]) => {
  1578. const dt = nextOccurrence(day, hour, afterMs);
  1579. const h12 = hour % 12 || 12;
  1580. const ampm = hour < 12 ? 'am' : 'pm';
  1581. return {
  1582. utc: dt.toISOString(),
  1583. dayOfWeek: day,
  1584. hour,
  1585. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  1586. };
  1587. })
  1588. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  1589. .slice(0, 4);
  1590. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  1591. return { source, suggestions };
  1592. });
  1593. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  1594. async function crawlFacebookMetrics(db) {
  1595. const fb = await getCredentials('facebook');
  1596. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  1597. if (!pages.length) return { count: 0 };
  1598. let count = 0;
  1599. for (const page of pages) {
  1600. const token = decryptToken(page.accessToken);
  1601. if (!token) continue;
  1602. try {
  1603. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  1604. params: {
  1605. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  1606. limit: 100,
  1607. access_token: token,
  1608. },
  1609. timeout: 30000,
  1610. });
  1611. for (const post of res.data.data || []) {
  1612. const likes = post.reactions?.summary?.total_count || 0;
  1613. const comments = post.comments?.summary?.total_count || 0;
  1614. const shares = post.shares?.count || 0;
  1615. const publishedAt = new Date(post.created_time);
  1616. await db.collection('post_metrics').updateOne(
  1617. { platform: 'facebook', postId: post.id },
  1618. {
  1619. $set: {
  1620. platform: 'facebook',
  1621. accountId: page.id,
  1622. accountName: page.name,
  1623. postId: post.id,
  1624. content: post.message || null,
  1625. publishedAt,
  1626. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  1627. hourOfDay: publishedAt.getUTCHours(),
  1628. dayOfWeek: publishedAt.getUTCDay(),
  1629. fetchedAt: new Date(),
  1630. },
  1631. },
  1632. { upsert: true }
  1633. );
  1634. count++;
  1635. }
  1636. } catch (err) {
  1637. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  1638. }
  1639. }
  1640. return { count };
  1641. }
  1642. async function crawlInstagramMetrics(db) {
  1643. const ig = await getCredentials('instagram');
  1644. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  1645. if (!accounts.length) return { count: 0 };
  1646. let count = 0;
  1647. for (const account of accounts) {
  1648. const token = decryptToken(account.accessToken);
  1649. if (!token) continue;
  1650. try {
  1651. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  1652. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  1653. timeout: 30000,
  1654. });
  1655. for (const media of mediaRes.data.data || []) {
  1656. const likes = media.like_count || 0;
  1657. const comments = media.comments_count || 0;
  1658. const publishedAt = new Date(media.timestamp);
  1659. let views = 0;
  1660. let saves = 0;
  1661. try {
  1662. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  1663. params: { metric: 'reach,saved', access_token: token },
  1664. timeout: 10000,
  1665. });
  1666. for (const ins of insRes.data.data || []) {
  1667. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  1668. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  1669. }
  1670. } catch (_) {}
  1671. await db.collection('post_metrics').updateOne(
  1672. { platform: 'instagram', postId: media.id },
  1673. {
  1674. $set: {
  1675. platform: 'instagram',
  1676. accountId: account.id,
  1677. accountName: account.username,
  1678. postId: media.id,
  1679. content: media.caption || null,
  1680. publishedAt,
  1681. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  1682. hourOfDay: publishedAt.getUTCHours(),
  1683. dayOfWeek: publishedAt.getUTCDay(),
  1684. fetchedAt: new Date(),
  1685. },
  1686. },
  1687. { upsert: true }
  1688. );
  1689. count++;
  1690. }
  1691. } catch (err) {
  1692. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  1693. }
  1694. }
  1695. return { count };
  1696. }
  1697. app.post('/analytics/crawl', async () => {
  1698. const db = await getDb();
  1699. const results = {};
  1700. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  1701. try {
  1702. results[platform] = await crawler(db);
  1703. } catch (err) {
  1704. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  1705. results[platform] = { count: 0, error: err.message };
  1706. }
  1707. }
  1708. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  1709. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  1710. return { success: true, total, byPlatform: results };
  1711. });
  1712. app.get('/analytics/insights', async (request) => {
  1713. const filter = parseAccountFilter(request.query.account);
  1714. const metricsMatch = filter
  1715. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1716. : {};
  1717. const db = await getDb();
  1718. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  1719. if (total === 0) return { empty: true };
  1720. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  1721. db.collection('post_metrics').aggregate([
  1722. { $match: metricsMatch },
  1723. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1724. { $sort: { _id: 1 } },
  1725. ]).toArray(),
  1726. db.collection('post_metrics').aggregate([
  1727. { $match: metricsMatch },
  1728. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1729. { $sort: { _id: 1 } },
  1730. ]).toArray(),
  1731. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  1732. db.collection('post_metrics').aggregate([
  1733. { $match: metricsMatch },
  1734. { $group: {
  1735. _id: '$platform',
  1736. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1737. avgLikes: { $avg: '$metrics.likes' },
  1738. avgComments: { $avg: '$metrics.comments' },
  1739. avgShares: { $avg: '$metrics.shares' },
  1740. totalPosts: { $sum: 1 },
  1741. }},
  1742. { $sort: { avgEngagement: -1 } },
  1743. ]).toArray(),
  1744. db.collection('post_metrics').aggregate([
  1745. { $match: metricsMatch },
  1746. { $group: {
  1747. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1748. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1749. count: { $sum: 1 },
  1750. }},
  1751. ]).toArray(),
  1752. ]);
  1753. const byHour = Array.from({ length: 24 }, (_, h) => {
  1754. const e = byHourRaw.find((r) => r._id === h);
  1755. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1756. });
  1757. const byDay = Array.from({ length: 7 }, (_, d) => {
  1758. const e = byDayRaw.find((r) => r._id === d);
  1759. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1760. });
  1761. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  1762. const day = Math.floor(i / 24);
  1763. const hour = i % 24;
  1764. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  1765. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1766. });
  1767. return {
  1768. empty: false,
  1769. total,
  1770. byHour,
  1771. byDay,
  1772. heatmap,
  1773. topPosts: topPosts.map((p) => ({
  1774. platform: p.platform, accountName: p.accountName, postId: p.postId,
  1775. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  1776. })),
  1777. platformComparison: platformComparison.map((p) => ({
  1778. platform: p._id,
  1779. avgEngagement: Math.round(p.avgEngagement),
  1780. avgLikes: Math.round(p.avgLikes),
  1781. avgComments: Math.round(p.avgComments),
  1782. avgShares: Math.round(p.avgShares),
  1783. totalPosts: p.totalPosts,
  1784. })),
  1785. };
  1786. });
  1787. // ─── Analytics ────────────────────────────────────────────────────────────────
  1788. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  1789. function parseAccountFilter(account) {
  1790. if (!account) return null;
  1791. const idx = account.indexOf(':');
  1792. if (idx === -1) return { platform: account };
  1793. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  1794. }
  1795. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  1796. function sjFilter(filter) {
  1797. if (!filter) return {};
  1798. return {
  1799. 'destinations.platform': filter.platform,
  1800. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1801. };
  1802. }
  1803. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  1804. function ipFilter(filter) {
  1805. if (!filter) return {};
  1806. return {
  1807. 'destinations.platform': filter.platform,
  1808. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1809. };
  1810. }
  1811. app.get('/analytics/summary', async (request) => {
  1812. const filter = parseAccountFilter(request.query.account);
  1813. const db = await getDb();
  1814. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1815. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1816. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  1817. // account filter after $unwind so a job targeting multiple platforms only
  1818. // counts the platform(s) that match the filter.
  1819. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  1820. const [
  1821. schedCompleted, schedFailed,
  1822. immPublished, immFailed,
  1823. recentSched, recentImm,
  1824. schedPlatformRaw, immPlatformRaw,
  1825. schedDayRaw, immDayRaw,
  1826. ] = await Promise.all([
  1827. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  1828. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  1829. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  1830. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  1831. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  1832. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  1833. // Platform breakdown from scheduled_jobs destinations
  1834. db.collection('scheduled_jobs').aggregate([
  1835. { $match: { status: 'completed', ...sjFilter(filter) } },
  1836. { $unwind: '$destinations' },
  1837. ...unwindFilter,
  1838. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  1839. { $sort: { count: -1 } },
  1840. ]).toArray(),
  1841. // Platform breakdown from immediate posts platformResults
  1842. db.collection('posts').aggregate([
  1843. { $match: { type: 'immediate', ...ipFilter(filter) } },
  1844. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  1845. { $unwind: '$results' },
  1846. { $match: { 'results.v.success': true } },
  1847. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  1848. { $group: { _id: '$platform', count: { $sum: 1 } } },
  1849. ]).toArray(),
  1850. // Activity by day from scheduled_jobs (using completedAt)
  1851. db.collection('scheduled_jobs').aggregate([
  1852. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  1853. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  1854. { $sort: { _id: 1 } },
  1855. ]).toArray(),
  1856. // Activity by day from immediate posts
  1857. db.collection('posts').aggregate([
  1858. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  1859. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  1860. { $sort: { _id: 1 } },
  1861. ]).toArray(),
  1862. ]);
  1863. const dayMap = {};
  1864. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1865. dayMap[_id] = (dayMap[_id] || 0) + count;
  1866. }
  1867. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1868. const platformMap = {};
  1869. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1870. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1871. }
  1872. const published = schedCompleted + immPublished;
  1873. const failed = schedFailed + immFailed;
  1874. const total = published + failed;
  1875. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1876. const recentCount = recentSched + recentImm;
  1877. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1878. });
  1879. app.get('/analytics/posts', async (request) => {
  1880. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1881. const skip = parseInt(request.query.skip || '0', 10);
  1882. const filter = parseAccountFilter(request.query.account);
  1883. const db = await getDb();
  1884. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1885. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1886. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1887. db.collection('scheduled_jobs')
  1888. .find(sjMatch)
  1889. .sort({ completedAt: -1, scheduledAt: -1 })
  1890. .skip(skip)
  1891. .limit(limit)
  1892. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1893. .toArray(),
  1894. db.collection('posts')
  1895. .find(ipMatch)
  1896. .sort({ publishedAt: -1 })
  1897. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1898. .toArray(),
  1899. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1900. db.collection('posts').countDocuments(ipMatch),
  1901. ]);
  1902. const normalised = [
  1903. ...scheduledJobs.map((j) => ({
  1904. _id: String(j._id),
  1905. type: 'scheduled',
  1906. content: j.content || null,
  1907. destinations: j.destinations || [],
  1908. platformResults: null,
  1909. status: j.status === 'completed' ? 'published' : 'failed',
  1910. publishedAt: j.completedAt || j.scheduledAt,
  1911. })),
  1912. ...immediatePosts.map((p) => ({
  1913. _id: String(p._id),
  1914. type: 'immediate',
  1915. content: p.content || null,
  1916. destinations: p.destinations || [],
  1917. platformResults: p.platformResults || null,
  1918. status: p.status,
  1919. publishedAt: p.publishedAt,
  1920. })),
  1921. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  1922. .slice(0, limit);
  1923. return { posts: normalised, total: schedTotal + immTotal };
  1924. });
  1925. // ─── Brand / Account Audit ────────────────────────────────────────────────────
  1926. app.post('/analytics/audit', async (request, reply) => {
  1927. const filter = parseAccountFilter(request.query.account);
  1928. const db = await getDb();
  1929. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1930. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1931. const recentPosts = await db.collection('posts').find({
  1932. publishedAt: { $gte: thirtyDaysAgo },
  1933. ...ipFilter(filter),
  1934. }, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } }).toArray();
  1935. if (recentPosts.length < 3) {
  1936. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 3 posts first.' });
  1937. }
  1938. // Posting frequency
  1939. const postsLast30 = recentPosts.length;
  1940. const postsLast7 = recentPosts.filter((p) => new Date(p.publishedAt) >= sevenDaysAgo).length;
  1941. const postsPerWeek = Math.round((postsLast30 / 4) * 10) / 10;
  1942. // Platforms used
  1943. const platforms = [...new Set(recentPosts.flatMap((p) => (p.destinations || []).map((d) => d.platform)).filter(Boolean))];
  1944. // Success rate
  1945. const publishedCount = recentPosts.filter((p) => p.status === 'published').length;
  1946. const successRate = Math.round((publishedCount / postsLast30) * 100);
  1947. // Top hashtags from post content
  1948. const hashtagCounts = {};
  1949. for (const post of recentPosts) {
  1950. const re = /#([a-zA-Z]\w*)/g;
  1951. let m;
  1952. re.lastIndex = 0;
  1953. while ((m = re.exec(post.content || '')) !== null) {
  1954. const tag = `#${m[1].toLowerCase()}`;
  1955. hashtagCounts[tag] = (hashtagCounts[tag] || 0) + 1;
  1956. }
  1957. }
  1958. const topHashtags = Object.entries(hashtagCounts)
  1959. .sort((a, b) => b[1] - a[1])
  1960. .slice(0, 5)
  1961. .map(([tag, count]) => `${tag} (${count}x)`)
  1962. .join(', ');
  1963. // Posting hour distribution — identify peak hours
  1964. const hourCounts = {};
  1965. for (const post of recentPosts) {
  1966. if (post.publishedAt) {
  1967. const h = new Date(post.publishedAt).getUTCHours();
  1968. hourCounts[h] = (hourCounts[h] || 0) + 1;
  1969. }
  1970. }
  1971. const peakHours = Object.entries(hourCounts)
  1972. .sort((a, b) => b[1] - a[1])
  1973. .slice(0, 3)
  1974. .map(([h]) => `${h}:00 UTC`)
  1975. .join(', ');
  1976. // Engagement data from post_metrics
  1977. const metricsFilter = filter
  1978. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1979. : {};
  1980. const metrics = await db.collection('post_metrics')
  1981. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  1982. .toArray();
  1983. const avgEngagement = metrics.length > 0
  1984. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  1985. : 0;
  1986. const statsBlock = [
  1987. `Publishing stats (last 30 days):`,
  1988. `- Total posts: ${postsLast30}`,
  1989. `- Posts this week: ${postsLast7}`,
  1990. `- Posts per week (avg): ${postsPerWeek}`,
  1991. `- Platforms used: ${platforms.join(', ') || 'unknown'}`,
  1992. `- Success rate: ${successRate}%`,
  1993. `- Average engagement per post: ${avgEngagement}`,
  1994. `- Current peak posting hours (UTC): ${peakHours || 'not enough data'}`,
  1995. `- Top hashtags in use: ${topHashtags || 'none detected'}`,
  1996. ].join('\n');
  1997. const system = 'You are a social media performance analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  1998. const prompt = `Audit this social media account and return a structured report.
  1999. ${statsBlock}
  2000. Return a JSON object with exactly these fields:
  2001. {
  2002. "score": <overall health score 0-100>,
  2003. "summary": "<2-3 sentence assessment>",
  2004. "postingFrequency": { "score": <0-10>, "assessment": "<one sentence>" },
  2005. "engagement": { "score": <0-10>, "benchmark": "<Excellent|Good|Average|Below Average>", "assessment": "<one sentence>" },
  2006. "contentMix": { "score": <0-10>, "assessment": "<one sentence on variety and platform fit>" },
  2007. "recommendations": ["<specific action 1>", "<specific action 2>", "<specific action 3>"]
  2008. }
  2009. Scoring benchmarks: posting 5+x/week = 8-10, 3-4x = 6-7, 1-2x = 4-5, less = 1-3.
  2010. Engagement benchmarks: >5 avg = Excellent, 3-5 = Good, 1-3 = Average, <1 = Below Average.
  2011. Return ONLY the JSON object.`;
  2012. try {
  2013. const pconf = await getActiveProviderConfig();
  2014. const model = pconf.model;
  2015. let text = '';
  2016. if (pconf.provider === 'ollama') {
  2017. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2018. text = res.data.response;
  2019. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2020. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2021. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2022. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2023. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2024. text = res.data.choices[0]?.message?.content || '';
  2025. } else if (pconf.provider === 'gemini') {
  2026. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2027. const res = await axios.post(
  2028. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2029. { contents: buildGeminiContents(prompt, system) },
  2030. { timeout: 120000 },
  2031. );
  2032. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2033. } else {
  2034. return reply.code(400).send({ error: 'AI not configured' });
  2035. }
  2036. let audit = null;
  2037. try {
  2038. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2039. audit = JSON.parse(jsonStr);
  2040. if (typeof audit.score !== 'number') throw new Error();
  2041. } catch {
  2042. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  2043. }
  2044. log.info({ action: 'analytics_audit', account: request.query.account || 'all', outcome: 'success' });
  2045. return {
  2046. success: true,
  2047. ...audit,
  2048. stats: { postsLast30, postsLast7, postsPerWeek, platforms, successRate, avgEngagement },
  2049. generatedAt: new Date(),
  2050. };
  2051. } catch (err) {
  2052. return reply.code(503).send({ error: 'Audit failed', detail: err.message });
  2053. }
  2054. });
  2055. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  2056. app.get('/hashtag-groups', async () => {
  2057. const db = await getDb();
  2058. const groups = await db.collection('hashtag_groups').find({}).sort({ name: 1 }).toArray();
  2059. return { groups };
  2060. });
  2061. app.post('/hashtag-groups', async (request, reply) => {
  2062. const { name, hashtags } = request.body || {};
  2063. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  2064. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2065. const db = await getDb();
  2066. const result = await db.collection('hashtag_groups').insertOne({
  2067. name: name.trim(),
  2068. hashtags: [...new Set(tags)],
  2069. createdAt: new Date(),
  2070. updatedAt: new Date(),
  2071. });
  2072. return { success: true, _id: result.insertedId };
  2073. });
  2074. app.put('/hashtag-groups/:id', async (request, reply) => {
  2075. const { id } = request.params;
  2076. const { name, hashtags } = request.body || {};
  2077. const update = { updatedAt: new Date() };
  2078. if (name?.trim()) update.name = name.trim();
  2079. if (hashtags) {
  2080. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2081. update.hashtags = [...new Set(tags)];
  2082. }
  2083. const db = await getDb();
  2084. let oid;
  2085. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2086. await db.collection('hashtag_groups').updateOne({ _id: oid }, { $set: update });
  2087. return { success: true };
  2088. });
  2089. app.delete('/hashtag-groups/:id', async (request, reply) => {
  2090. const { id } = request.params;
  2091. const db = await getDb();
  2092. let oid;
  2093. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2094. await db.collection('hashtag_groups').deleteOne({ _id: oid });
  2095. return { success: true };
  2096. });
  2097. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  2098. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  2099. function extractHashtags(text) {
  2100. if (!text) return [];
  2101. const tags = [];
  2102. let m;
  2103. HASHTAG_RE.lastIndex = 0;
  2104. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  2105. return tags;
  2106. }
  2107. function gradeHashtag(count, avgEngagement) {
  2108. if (count >= 5 && avgEngagement >= 10) return 'A';
  2109. if (count >= 3 && avgEngagement >= 3) return 'B';
  2110. if (count >= 2) return 'C';
  2111. return 'D';
  2112. }
  2113. // POST /hashtags/scrape — scan YOUR published posts per-account.
  2114. // Body: { accountKey?: string } — omit to scan all accounts at once.
  2115. app.post('/hashtags/scrape', async (request) => {
  2116. const { accountKey: filterAccount } = request.body || {};
  2117. const db = await getDb();
  2118. // tagMap key: `${accountKey}||${hashtag}`
  2119. const tagMap = {};
  2120. function touch(tag, accountKey, platform, engagement) {
  2121. const key = `${accountKey}||${tag}`;
  2122. if (!tagMap[key]) tagMap[key] = { tag, accountKey, count: 0, totalEngagement: 0, platforms: new Set() };
  2123. tagMap[key].count++;
  2124. tagMap[key].totalEngagement += engagement;
  2125. tagMap[key].platforms.add(platform);
  2126. }
  2127. // Engagement lookup keyed by content fingerprint
  2128. const postMetrics = await db.collection('post_metrics').find({}).toArray();
  2129. const metricsByContent = {};
  2130. for (const m of postMetrics) {
  2131. if (m.content) {
  2132. const key = m.content.slice(0, 100).toLowerCase().trim();
  2133. metricsByContent[key] = (metricsByContent[key] || 0) + (m.metrics?.engagementTotal || 0);
  2134. }
  2135. }
  2136. // Scan YOUR published posts only — feeds are others' content, not your performance
  2137. const posts = await db.collection('posts').find({}, { projection: { content: 1, destinations: 1 } }).toArray();
  2138. for (const post of posts) {
  2139. const tags = extractHashtags(post.content || '');
  2140. if (!tags.length) continue;
  2141. const engagement = post.content
  2142. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  2143. : 0;
  2144. const destinations = post.destinations?.length ? post.destinations : [{ platform: 'unknown' }];
  2145. for (const dest of destinations) {
  2146. const acctKey = dest.accountId ? `${dest.platform}:${dest.accountId}` : dest.platform;
  2147. if (filterAccount && acctKey !== filterAccount) continue;
  2148. for (const tag of tags) {
  2149. touch(tag, acctKey, dest.platform, engagement / Math.max(tags.length, 1));
  2150. }
  2151. }
  2152. }
  2153. let scraped = 0;
  2154. for (const [compoundKey, data] of Object.entries(tagMap)) {
  2155. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  2156. await db.collection('hashtag_stats').updateOne(
  2157. { _id: compoundKey },
  2158. {
  2159. $set: {
  2160. hashtag: data.tag,
  2161. accountKey: data.accountKey,
  2162. count: data.count,
  2163. avgEngagement: Math.round(avgEngagement * 10) / 10,
  2164. grade: gradeHashtag(data.count, avgEngagement),
  2165. platforms: [...data.platforms],
  2166. lastScraped: new Date(),
  2167. },
  2168. },
  2169. { upsert: true }
  2170. );
  2171. scraped++;
  2172. }
  2173. log.info({ action: 'hashtag_scrape', accountKey: filterAccount || 'all', outcome: 'success', scraped });
  2174. return { success: true, scraped };
  2175. });
  2176. app.get('/hashtags/stats', async (request) => {
  2177. const { sort, accountKey } = request.query;
  2178. const db = await getDb();
  2179. const sortField = sort === 'engagement' ? 'avgEngagement' : 'count';
  2180. if (accountKey) {
  2181. // Per-account view
  2182. const stats = await db.collection('hashtag_stats')
  2183. .find({ accountKey })
  2184. .sort({ [sortField]: -1 })
  2185. .limit(200)
  2186. .toArray();
  2187. return { stats };
  2188. }
  2189. // Aggregate view: group by hashtag across all accounts
  2190. const allStats = await db.collection('hashtag_stats').find({ accountKey: { $exists: true } }).toArray();
  2191. const grouped = new Map();
  2192. for (const s of allStats) {
  2193. if (!s.hashtag) continue;
  2194. if (!grouped.has(s.hashtag)) {
  2195. grouped.set(s.hashtag, { count: 0, totalEngagement: 0, totalCount: 0, platforms: new Set(), lastScraped: null });
  2196. }
  2197. const g = grouped.get(s.hashtag);
  2198. g.count += s.count;
  2199. g.totalEngagement += s.avgEngagement * s.count;
  2200. g.totalCount += s.count;
  2201. for (const p of (s.platforms || [])) g.platforms.add(p);
  2202. if (!g.lastScraped || (s.lastScraped && new Date(s.lastScraped) > new Date(g.lastScraped))) g.lastScraped = s.lastScraped;
  2203. }
  2204. const stats = [...grouped.entries()]
  2205. .map(([tag, g]) => {
  2206. const avgEngagement = g.totalCount > 0 ? Math.round((g.totalEngagement / g.totalCount) * 10) / 10 : 0;
  2207. return {
  2208. _id: tag,
  2209. hashtag: tag,
  2210. accountKey: null,
  2211. count: g.count,
  2212. avgEngagement,
  2213. grade: gradeHashtag(g.count, avgEngagement),
  2214. platforms: [...g.platforms],
  2215. lastScraped: g.lastScraped,
  2216. };
  2217. })
  2218. .sort((a, b) => b[sortField] - a[sortField])
  2219. .slice(0, 200);
  2220. return { stats };
  2221. });
  2222. app.post('/hashtags/ai-suggest', async (request, reply) => {
  2223. const { accountKey, topTags = [], count = 20 } = request.body || {};
  2224. let profileCtx = '';
  2225. if (accountKey) {
  2226. try {
  2227. const db = await getDb();
  2228. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  2229. if (profile) {
  2230. const parts = [];
  2231. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  2232. if (profile.description) parts.push(`Description: ${profile.description}`);
  2233. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  2234. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  2235. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  2236. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  2237. profileCtx = parts.join('\n');
  2238. }
  2239. } catch (_) {}
  2240. }
  2241. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  2242. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  2243. const prompt = [
  2244. `Suggest ${count} high-performing hashtags for a social media account.`,
  2245. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  2246. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  2247. `\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`,
  2248. ].filter(Boolean).join('');
  2249. try {
  2250. const pconf = await getActiveProviderConfig();
  2251. const model = pconf.model;
  2252. let text = '';
  2253. if (pconf.provider === 'ollama') {
  2254. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  2255. text = res.data.response;
  2256. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2257. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2258. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2259. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2260. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  2261. text = res.data.choices[0]?.message?.content || '';
  2262. } else if (pconf.provider === 'gemini') {
  2263. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2264. const res = await axios.post(
  2265. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2266. { contents: buildGeminiContents(prompt, system) },
  2267. { timeout: 60000 },
  2268. );
  2269. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2270. } else {
  2271. return reply.code(400).send({ error: 'AI not configured' });
  2272. }
  2273. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  2274. return { success: true, hashtags: tags };
  2275. } catch (err) {
  2276. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  2277. }
  2278. });
  2279. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  2280. async function extractTextFromUrl(url) {
  2281. try {
  2282. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  2283. const html = res.data || '';
  2284. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  2285. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  2286. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  2287. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  2288. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  2289. } catch {
  2290. return '';
  2291. }
  2292. }
  2293. async function scrapeBluesky(profileUrl) {
  2294. try {
  2295. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  2296. if (!handle) return '';
  2297. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  2298. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  2299. return posts.join('\n').slice(0, 3000);
  2300. } catch {
  2301. return '';
  2302. }
  2303. }
  2304. async function scrapeMastodon(profileUrl) {
  2305. try {
  2306. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  2307. if (!m) return '';
  2308. const [, instance, username] = m;
  2309. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  2310. const accountId = lookupRes.data?.id;
  2311. if (!accountId) return '';
  2312. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  2313. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  2314. return posts.join('\n').slice(0, 3000);
  2315. } catch {
  2316. return '';
  2317. }
  2318. }
  2319. async function runCompetitorScrape(competitorId) {
  2320. const db = await getDb();
  2321. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  2322. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  2323. const newItems = [];
  2324. if (competitor.websiteUrl) {
  2325. const text = await extractTextFromUrl(competitor.websiteUrl);
  2326. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  2327. }
  2328. const socialEntries = Object.entries(competitor.socialUrls || {});
  2329. for (const [platform, url] of socialEntries) {
  2330. if (!url) continue;
  2331. let text = '';
  2332. if (platform === 'bluesky') text = await scrapeBluesky(url);
  2333. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  2334. else text = await extractTextFromUrl(url);
  2335. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  2336. }
  2337. const existing = competitor.scrapedContent || [];
  2338. // Detect whether any newly scraped content differs from what was previously stored
  2339. const existingFingerprints = new Set(existing.map((s) => s.url + '||' + s.text.slice(0, 200)));
  2340. const contentChanged = newItems.some((item) => !existingFingerprints.has(item.url + '||' + item.text.slice(0, 200)));
  2341. const combined = [...newItems, ...existing].slice(0, 20);
  2342. await db.collection('competitors').updateOne(
  2343. { _id: new ObjectId(competitorId) },
  2344. { $set: { scrapedContent: combined, contentChanged, lastScraped: new Date(), updatedAt: new Date() } },
  2345. );
  2346. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  2347. }
  2348. async function buildCompetitorSystemSuffix() {
  2349. try {
  2350. const db = await getDb();
  2351. const competitors = await db.collection('competitors').find({
  2352. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  2353. }).toArray();
  2354. if (!competitors.length) return '';
  2355. const lines = competitors.map((c) => {
  2356. if (c.aiAnalysis?.positioning) {
  2357. const a = c.aiAnalysis;
  2358. const parts = [`- ${c.name}:`];
  2359. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  2360. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  2361. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  2362. return parts.join('\n');
  2363. }
  2364. return `- ${c.name}: ${c.aiSummary}`;
  2365. }).join('\n');
  2366. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  2367. } catch {
  2368. return '';
  2369. }
  2370. }
  2371. // Discover competitors automatically using AI + account profile context
  2372. app.post('/competitors/discover', async (request, reply) => {
  2373. const db = await getDb();
  2374. // Use the first account profile for business context
  2375. const profile = await db.collection('account_profiles').findOne({});
  2376. const contextParts = [];
  2377. if (profile) {
  2378. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  2379. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  2380. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  2381. if (profile.websiteUrl) contextParts.push(`Website: ${profile.websiteUrl}`);
  2382. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  2383. }
  2384. if (!contextParts.length) {
  2385. return reply.code(400).send({ error: 'Set up at least one Account Profile in Settings before discovering competitors.' });
  2386. }
  2387. const system = 'You are a market research analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2388. const prompt = `Based on the following business profile, identify the top 5 direct competitors.
  2389. ${contextParts.join('\n')}
  2390. Return ONLY a JSON array of objects, e.g.:
  2391. [{"name":"Competitor Name","websiteUrl":"https://example.com","reason":"One sentence on why they compete directly"}]
  2392. Rules:
  2393. - Return real, existing businesses only.
  2394. - Include only direct competitors (same product/service category, same target audience).
  2395. - websiteUrl must be a valid https URL to the competitor's main website.
  2396. - No explanation outside the JSON array.`;
  2397. try {
  2398. const pconf = await getActiveProviderConfig();
  2399. const model = pconf.model;
  2400. let text = '';
  2401. if (pconf.provider === 'ollama') {
  2402. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2403. text = res.data.response;
  2404. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2405. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2406. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2407. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2408. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2409. text = res.data.choices[0]?.message?.content || '';
  2410. } else if (pconf.provider === 'gemini') {
  2411. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2412. const res = await axios.post(
  2413. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2414. { contents: buildGeminiContents(prompt, system) },
  2415. { timeout: 120000 },
  2416. );
  2417. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2418. } else {
  2419. return reply.code(400).send({ error: 'AI not configured' });
  2420. }
  2421. let suggestions = [];
  2422. try {
  2423. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2424. const parsed = JSON.parse(jsonStr);
  2425. if (!Array.isArray(parsed)) throw new Error();
  2426. suggestions = parsed
  2427. .filter((s) => s && typeof s.name === 'string' && typeof s.websiteUrl === 'string')
  2428. .slice(0, 5)
  2429. .map((s) => ({
  2430. name: s.name.trim(),
  2431. websiteUrl: s.websiteUrl.trim(),
  2432. reason: typeof s.reason === 'string' ? s.reason.trim() : '',
  2433. }));
  2434. } catch {
  2435. return reply.code(503).send({ error: 'AI returned invalid format — try again' });
  2436. }
  2437. log.info({ action: 'competitor_discover', count: suggestions.length, outcome: 'success' });
  2438. return { success: true, suggestions };
  2439. } catch (err) {
  2440. return reply.code(503).send({ error: 'Discovery failed', detail: err.message });
  2441. }
  2442. });
  2443. // List competitors
  2444. app.get('/competitors', async (request, reply) => {
  2445. const db = await getDb();
  2446. const list = await db.collection('competitors').find({}).sort({ createdAt: 1 }).toArray();
  2447. return list;
  2448. });
  2449. // Add competitor (max 2)
  2450. app.post('/competitors', async (request, reply) => {
  2451. const db = await getDb();
  2452. const count = await db.collection('competitors').countDocuments();
  2453. if (count >= 5) return reply.code(400).send({ error: 'Maximum 5 competitors allowed' });
  2454. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  2455. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  2456. const now = new Date();
  2457. const result = await db.collection('competitors').insertOne({
  2458. name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  2459. });
  2460. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  2461. return doc;
  2462. });
  2463. // Update competitor
  2464. app.put('/competitors/:id', async (request, reply) => {
  2465. const db = await getDb();
  2466. const { name, websiteUrl, socialUrls } = request.body || {};
  2467. const updates = { updatedAt: new Date() };
  2468. if (name !== undefined) updates.name = name;
  2469. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  2470. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  2471. await db.collection('competitors').updateOne({ _id: new ObjectId(request.params.id) }, { $set: updates });
  2472. const doc = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2473. return doc;
  2474. });
  2475. // Delete competitor
  2476. app.delete('/competitors/:id', async (request, reply) => {
  2477. const db = await getDb();
  2478. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id) });
  2479. return { success: true };
  2480. });
  2481. // Scrape one competitor — returns jobId immediately, runs in background
  2482. app.post('/competitors/:id/scrape', async (request, reply) => {
  2483. const jobId = new ObjectId().toString();
  2484. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  2485. (async () => {
  2486. try {
  2487. const result = await runCompetitorScrape(request.params.id);
  2488. activeScrapeJobs.set(jobId, {
  2489. status: result.ok ? 'done' : 'failed',
  2490. sources: result.sources,
  2491. message: result.message,
  2492. });
  2493. } catch (err) {
  2494. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  2495. }
  2496. })();
  2497. return reply.code(202).send({ jobId });
  2498. });
  2499. // Poll scrape job status
  2500. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  2501. const job = activeScrapeJobs.get(request.params.jobId);
  2502. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  2503. return job;
  2504. });
  2505. // Scrape all competitors (called by scheduler)
  2506. app.post('/competitors/scrape-all', async (request, reply) => {
  2507. const db = await getDb();
  2508. const all = await db.collection('competitors').find({}).toArray();
  2509. const results = [];
  2510. for (const c of all) {
  2511. const r = await runCompetitorScrape(c._id.toString());
  2512. results.push({ id: c._id.toString(), name: c.name, ...r });
  2513. }
  2514. return { success: true, results };
  2515. });
  2516. // Summarize competitor content with AI — returns structured analysis
  2517. app.post('/competitors/:id/summarize', async (request, reply) => {
  2518. const db = await getDb();
  2519. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2520. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2521. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  2522. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  2523. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2524. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  2525. {
  2526. "themes": ["3-5 main content topics or pillars they focus on"],
  2527. "tone": "one sentence describing their voice and communication style",
  2528. "positioning": "one sentence on how they position themselves in the market",
  2529. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  2530. "moves": ["3 specific content angles you could use to stand out against them"],
  2531. "profile": {
  2532. "pricing": "one sentence on their pricing model or tier (e.g. 'Freemium with $49/mo Pro plan', 'Premium only, starts at $99/mo', or 'Pricing not visible' if unclear)",
  2533. "keyFeatures": ["3-5 core product or service features they emphasise"],
  2534. "marketingChannels": ["2-4 social/marketing channels they actively use based on content"],
  2535. "targetCustomer": "one sentence describing their apparent ideal customer"
  2536. },
  2537. "prediction": {
  2538. "satisfiedWithPosition": <true if they appear content with their current position, false if they seem to be pushing for growth>,
  2539. "likelyNextMoves": ["2-3 strategic moves they will probably make based on current trajectory"],
  2540. "vulnerabilities": ["2-3 specific weaknesses or blind spots visible in their content"],
  2541. "retaliationTriggers": ["1-2 moves by a competitor that would most likely provoke a strong response from them"]
  2542. }
  2543. }
  2544. Content:
  2545. ${content}
  2546. Return ONLY the JSON object. No explanation, no markdown.`;
  2547. try {
  2548. const pconf = await getActiveProviderConfig();
  2549. const model = pconf.model;
  2550. let text = '';
  2551. if (pconf.provider === 'ollama') {
  2552. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2553. text = res.data.response;
  2554. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2555. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2556. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2557. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2558. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2559. text = res.data.choices[0]?.message?.content || '';
  2560. } else if (pconf.provider === 'gemini') {
  2561. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2562. const res = await axios.post(
  2563. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2564. { contents: buildGeminiContents(prompt, system) },
  2565. { timeout: 180000 },
  2566. );
  2567. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2568. } else {
  2569. return reply.code(400).send({ error: 'AI not configured' });
  2570. }
  2571. let aiAnalysis = null;
  2572. try {
  2573. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2574. aiAnalysis = JSON.parse(jsonStr);
  2575. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  2576. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  2577. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  2578. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  2579. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  2580. // Validate profile block
  2581. if (!aiAnalysis.profile || typeof aiAnalysis.profile !== 'object') aiAnalysis.profile = {};
  2582. if (typeof aiAnalysis.profile.pricing !== 'string') aiAnalysis.profile.pricing = '';
  2583. if (!Array.isArray(aiAnalysis.profile.keyFeatures)) aiAnalysis.profile.keyFeatures = [];
  2584. if (!Array.isArray(aiAnalysis.profile.marketingChannels)) aiAnalysis.profile.marketingChannels = [];
  2585. if (typeof aiAnalysis.profile.targetCustomer !== 'string') aiAnalysis.profile.targetCustomer = '';
  2586. // Validate prediction block
  2587. if (!aiAnalysis.prediction || typeof aiAnalysis.prediction !== 'object') aiAnalysis.prediction = {};
  2588. if (typeof aiAnalysis.prediction.satisfiedWithPosition !== 'boolean') aiAnalysis.prediction.satisfiedWithPosition = true;
  2589. if (!Array.isArray(aiAnalysis.prediction.likelyNextMoves)) aiAnalysis.prediction.likelyNextMoves = [];
  2590. if (!Array.isArray(aiAnalysis.prediction.vulnerabilities)) aiAnalysis.prediction.vulnerabilities = [];
  2591. if (!Array.isArray(aiAnalysis.prediction.retaliationTriggers)) aiAnalysis.prediction.retaliationTriggers = [];
  2592. } catch {
  2593. aiAnalysis = null;
  2594. }
  2595. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  2596. await db.collection('competitors').updateOne(
  2597. { _id: new ObjectId(request.params.id) },
  2598. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  2599. );
  2600. return { success: true, aiAnalysis };
  2601. } catch (err) {
  2602. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  2603. }
  2604. });
  2605. // Extract keywords from scraped content using AI (item 34)
  2606. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  2607. const db = await getDb();
  2608. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2609. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2610. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  2611. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  2612. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2613. const prompt = `Analyse the following content from "${competitor.name}" and extract the top 20 keywords and key phrases they appear to be targeting. For each keyword, classify its search intent using one of these four types:
  2614. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  2615. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  2616. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  2617. - navigational: user is searching for a specific brand or tool by name
  2618. Content:
  2619. ${content}
  2620. Return ONLY a JSON array, e.g.:
  2621. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  2622. No explanation, no markdown.`;
  2623. try {
  2624. const pconf = await getActiveProviderConfig();
  2625. const model = pconf.model;
  2626. let text = '';
  2627. if (pconf.provider === 'ollama') {
  2628. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2629. text = res.data.response;
  2630. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2631. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2632. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2633. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2634. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2635. text = res.data.choices[0]?.message?.content || '';
  2636. } else if (pconf.provider === 'gemini') {
  2637. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2638. const res = await axios.post(
  2639. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2640. { contents: buildGeminiContents(prompt, system) },
  2641. { timeout: 120000 },
  2642. );
  2643. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2644. } else {
  2645. return reply.code(400).send({ error: 'AI not configured' });
  2646. }
  2647. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  2648. let keywords = [];
  2649. try {
  2650. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2651. const parsed = JSON.parse(jsonStr);
  2652. if (!Array.isArray(parsed)) throw new Error();
  2653. const now = new Date();
  2654. keywords = parsed
  2655. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  2656. .slice(0, 20)
  2657. .map((k) => ({
  2658. term: k.term.trim(),
  2659. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  2660. extractedAt: now,
  2661. }));
  2662. } catch {
  2663. keywords = [];
  2664. }
  2665. await db.collection('competitors').updateOne(
  2666. { _id: new ObjectId(request.params.id) },
  2667. { $set: { keywords, updatedAt: new Date() } },
  2668. );
  2669. return { success: true, keywords };
  2670. } catch (err) {
  2671. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  2672. }
  2673. });
  2674. // Analyse content gaps — compare competitor keywords against user's hashtag_stats
  2675. app.post('/competitors/:id/analyze-gaps', async (request, reply) => {
  2676. const db = await getDb();
  2677. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2678. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2679. const keywords = (competitor.keywords || []);
  2680. if (!keywords.length) return reply.code(400).send({ error: 'Extract keywords first before analysing gaps' });
  2681. const hashtagDocs = await db.collection('hashtag_stats')
  2682. .find({ accountKey: { $exists: true } }, { projection: { _id: 0, hashtag: 1 } })
  2683. .toArray();
  2684. const hashtagStatsEmpty = hashtagDocs.length === 0;
  2685. // Deduplicate across accounts — same hashtag used by any account counts as covered
  2686. const uniqueTags = [...new Set(hashtagDocs.map((h) => h.hashtag).filter(Boolean))];
  2687. const hashtagTexts = uniqueTags.map((tag) => ({ id: tag, text: tag.replace(/^#/, '').toLowerCase() }));
  2688. const INTENT_ORDER = { transactional: 0, commercial: 1, informational: 2, navigational: 3 };
  2689. function findMatchingHashtags(term) {
  2690. const words = term.toLowerCase().split(/\s+/).filter((w) => w.length >= 4);
  2691. return hashtagTexts
  2692. .filter(({ text }) => words.some((w) => text.includes(w)))
  2693. .map(({ id }) => id);
  2694. }
  2695. const gaps = [];
  2696. const covered = [];
  2697. for (const kw of keywords) {
  2698. const term = typeof kw === 'string' ? kw : kw.term;
  2699. const intent = typeof kw === 'string' ? 'informational' : (kw.intent || 'informational');
  2700. const matched = findMatchingHashtags(term);
  2701. if (matched.length) {
  2702. covered.push({ term, intent, matchedHashtags: matched.slice(0, 4) });
  2703. } else {
  2704. gaps.push({ term, intent });
  2705. }
  2706. }
  2707. gaps.sort((a, b) => (INTENT_ORDER[a.intent] ?? 99) - (INTENT_ORDER[b.intent] ?? 99));
  2708. const gapAnalysis = { gaps, covered, totalKeywords: keywords.length, hashtagStatsEmpty, lastAnalyzed: new Date() };
  2709. await db.collection('competitors').updateOne(
  2710. { _id: new ObjectId(request.params.id) },
  2711. { $set: { gapAnalysis, updatedAt: new Date() } },
  2712. );
  2713. return { success: true, ...gapAnalysis };
  2714. });
  2715. // Detect and classify market signals from latest scraped content
  2716. app.post('/competitors/:id/detect-signals', async (request, reply) => {
  2717. const db = await getDb();
  2718. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2719. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2720. const recentContent = (competitor.scrapedContent || []).slice(0, 10);
  2721. if (!recentContent.length) return reply.code(400).send({ error: 'Scrape first before detecting signals' });
  2722. const contentText = recentContent.map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 4000);
  2723. const baseline = competitor.aiAnalysis
  2724. ? `Previous profile — Themes: ${(competitor.aiAnalysis.themes || []).join(', ')}. Tone: ${competitor.aiAnalysis.tone || 'unknown'}.`
  2725. : 'No prior analysis available.';
  2726. const system = 'You are a competitive intelligence analyst specialising in market signal detection. Return only valid JSON with no explanation, no markdown.';
  2727. const prompt = `Analyse the latest content from competitor "${competitor.name}" and detect any notable changes or strategic signals.
  2728. Baseline context:
  2729. ${baseline}
  2730. Latest scraped content:
  2731. ${contentText}
  2732. Classify any changes you detect. Use these signal types:
  2733. - topic_expansion: new content themes or topics not previously seen
  2734. - tone_shift: measurable change in communication style or voice
  2735. - campaign_launch: evidence of a new marketing campaign or product promotion
  2736. - pricing_change: any mention of new pricing, offers, or discounts
  2737. - market_entry: signs of entering a new platform, audience, or geography
  2738. - competitive_aggression: direct competitor comparisons, attack marketing, or poaching language
  2739. - frequency_change: evidence of significantly more or less content activity
  2740. Return ONLY a JSON array (empty array [] if no significant signals):
  2741. [{"type":"<type>","description":"<one sentence describing the specific change>","severity":"<low|medium|high>"}]
  2742. Severity guide: high = major strategic shift, medium = notable change worth monitoring, low = minor or uncertain change.`;
  2743. try {
  2744. const pconf = await getActiveProviderConfig();
  2745. const model = pconf.model;
  2746. let text = '';
  2747. if (pconf.provider === 'ollama') {
  2748. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2749. text = res.data.response;
  2750. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2751. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2752. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2753. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2754. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2755. text = res.data.choices[0]?.message?.content || '';
  2756. } else if (pconf.provider === 'gemini') {
  2757. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2758. const res = await axios.post(
  2759. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2760. { contents: buildGeminiContents(prompt, system) },
  2761. { timeout: 120000 },
  2762. );
  2763. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2764. } else {
  2765. return reply.code(400).send({ error: 'AI not configured' });
  2766. }
  2767. const VALID_TYPES = new Set(['topic_expansion', 'tone_shift', 'campaign_launch', 'pricing_change', 'market_entry', 'competitive_aggression', 'frequency_change']);
  2768. const VALID_SEVERITIES = new Set(['low', 'medium', 'high']);
  2769. let signals = [];
  2770. try {
  2771. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2772. const parsed = JSON.parse(jsonStr);
  2773. if (!Array.isArray(parsed)) throw new Error();
  2774. const now = new Date();
  2775. signals = parsed
  2776. .filter((s) => s && VALID_TYPES.has(s.type) && typeof s.description === 'string')
  2777. .slice(0, 8)
  2778. .map((s) => ({
  2779. type: s.type,
  2780. description: s.description.trim(),
  2781. severity: VALID_SEVERITIES.has(s.severity) ? s.severity : 'medium',
  2782. detectedAt: now,
  2783. }));
  2784. } catch {
  2785. signals = [];
  2786. }
  2787. await db.collection('competitors').updateOne(
  2788. { _id: new ObjectId(request.params.id) },
  2789. { $set: { signals, contentChanged: false, updatedAt: new Date() } },
  2790. );
  2791. log.info({ action: 'detect_signals', competitorId: request.params.id, count: signals.length, outcome: 'success' });
  2792. return { success: true, signals };
  2793. } catch (err) {
  2794. return reply.code(503).send({ error: 'Signal detection failed', detail: err.message });
  2795. }
  2796. });
  2797. // Generate a 5-post content roadmap from competitor keywords and gaps
  2798. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  2799. const db = await getDb();
  2800. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2801. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2802. const keywords = (competitor.keywords || []);
  2803. const hasKeywords = keywords.length > 0;
  2804. const hasContent = (competitor.scrapedContent || []).length > 0;
  2805. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  2806. const kwList = hasKeywords
  2807. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  2808. : '';
  2809. const gaps = competitor.aiAnalysis?.gaps || [];
  2810. const moves = competitor.aiAnalysis?.moves || [];
  2811. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  2812. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  2813. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  2814. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2815. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  2816. ${kwSection}${gapsSection}${movesSection}
  2817. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  2818. - topic: short topic name, max 8 words
  2819. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  2820. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  2821. - rationale: one sentence on why this post wins against ${competitor.name}
  2822. Return ONLY a JSON array:
  2823. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  2824. No explanation, no markdown.`;
  2825. try {
  2826. const pconf = await getActiveProviderConfig();
  2827. const model = pconf.model;
  2828. let text = '';
  2829. if (pconf.provider === 'ollama') {
  2830. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2831. text = res.data.response;
  2832. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2833. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2834. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2835. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2836. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2837. text = res.data.choices[0]?.message?.content || '';
  2838. } else if (pconf.provider === 'gemini') {
  2839. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2840. const res = await axios.post(
  2841. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2842. { contents: buildGeminiContents(prompt, system) },
  2843. { timeout: 180000 },
  2844. );
  2845. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2846. } else {
  2847. return reply.code(400).send({ error: 'AI not configured' });
  2848. }
  2849. let roadmap = [];
  2850. try {
  2851. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2852. const parsed = JSON.parse(jsonStr);
  2853. if (!Array.isArray(parsed)) throw new Error();
  2854. roadmap = parsed
  2855. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  2856. .slice(0, 5)
  2857. .map((p) => ({
  2858. topic: p.topic.trim(),
  2859. headline: p.headline.trim(),
  2860. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  2861. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  2862. }));
  2863. } catch {
  2864. roadmap = [];
  2865. }
  2866. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  2867. await db.collection('competitors').updateOne(
  2868. { _id: new ObjectId(request.params.id) },
  2869. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  2870. );
  2871. return { success: true, contentRoadmap: roadmap };
  2872. } catch (err) {
  2873. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  2874. }
  2875. });
  2876. module.exports = app;