server.js 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015
  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. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  817. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  818. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  819. app.post('/ai/bulk-draft', async (request, reply) => {
  820. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  821. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  822. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  823. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  824. const db = await getDb();
  825. const batchId = new ObjectId();
  826. const now = new Date();
  827. await db.collection('bulk_draft_batches').insertOne({
  828. _id: batchId,
  829. total: filteredTopics.length,
  830. completed: 0,
  831. failed: 0,
  832. status: 'processing',
  833. createdAt: now,
  834. updatedAt: now,
  835. });
  836. const selectedDests = destinations.filter((d) => d.selected);
  837. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  838. const platformRules = buildPlatformRulesBlock(selectedDests);
  839. 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}`;
  840. // Fire-and-forget — process topics sequentially in the background
  841. (async () => {
  842. const pconf = await getActiveProviderConfig();
  843. const model = reqModel || pconf.model;
  844. for (const topic of filteredTopics) {
  845. try {
  846. const prompt = `Write a social media post about: ${topic}`;
  847. let content = '';
  848. if (pconf.provider === 'ollama') {
  849. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  850. content = res.data.response || '';
  851. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  852. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  853. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  854. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  855. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  856. content = res.data.choices[0]?.message?.content || '';
  857. } else if (pconf.provider === 'gemini') {
  858. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  859. const res = await axios.post(
  860. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  861. { contents: buildGeminiContents(prompt, system) },
  862. { timeout: 90000 },
  863. );
  864. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  865. }
  866. if (content.trim()) {
  867. const draftNow = new Date();
  868. await db.collection('drafts').insertOne({
  869. content: content.trim(),
  870. mediaUrl: '',
  871. scheduledAt: '',
  872. destinations: selectedDests,
  873. batchId: batchId.toString(),
  874. topic,
  875. createdAt: draftNow,
  876. updatedAt: draftNow,
  877. });
  878. }
  879. await db.collection('bulk_draft_batches').updateOne(
  880. { _id: batchId },
  881. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  882. );
  883. } catch (err) {
  884. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  885. await db.collection('bulk_draft_batches').updateOne(
  886. { _id: batchId },
  887. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  888. );
  889. }
  890. }
  891. await db.collection('bulk_draft_batches').updateOne(
  892. { _id: batchId },
  893. { $set: { status: 'done', updatedAt: new Date() } },
  894. );
  895. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  896. })().catch((err) => {
  897. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  898. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  899. { _id: batchId },
  900. { $set: { status: 'failed', updatedAt: new Date() } },
  901. )).catch(() => {});
  902. });
  903. return reply.code(202).send({ batchId: batchId.toString() });
  904. });
  905. // GET /ai/bulk-draft/:batchId — poll batch progress
  906. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  907. const { batchId } = request.params;
  908. let oid;
  909. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  910. const db = await getDb();
  911. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid });
  912. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  913. return {
  914. batchId: batch._id.toString(),
  915. total: batch.total,
  916. completed: batch.completed,
  917. failed: batch.failed,
  918. status: batch.status,
  919. processed: batch.completed + batch.failed,
  920. };
  921. });
  922. // ─── Platform service URLs ────────────────────────────────────────────────────
  923. const PLATFORM_SERVICES = {
  924. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  925. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  926. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  927. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  928. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  929. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  930. };
  931. // Direct multi-platform post endpoint.
  932. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  933. app.post('/post', async (request, reply) => {
  934. const { content, destinations = [], firstComment } = request.body || {};
  935. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  936. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  937. const results = await Promise.allSettled(
  938. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  939. const serviceUrl = PLATFORM_SERVICES[platform];
  940. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  941. const res = await axios.post(
  942. `${serviceUrl}/post`,
  943. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  944. { timeout: 30000 }
  945. );
  946. return { platform, accountId, ...res.data };
  947. })
  948. );
  949. const output = results.map((r, i) =>
  950. r.status === 'fulfilled'
  951. ? r.value
  952. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  953. );
  954. const anyFailed = output.some((r) => !r.success);
  955. const anySucceeded = output.some((r) => r.success);
  956. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  957. // Record the post for analytics
  958. try {
  959. const db = await getDb();
  960. await db.collection('posts').insertOne({
  961. _id: crypto.randomUUID(),
  962. type: 'immediate',
  963. content,
  964. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  965. destinations,
  966. platformResults: Object.fromEntries(
  967. output.map((r) => [
  968. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  969. { success: r.success, ...(r.error && { error: r.error }) },
  970. ])
  971. ),
  972. status: postStatus,
  973. publishedAt: new Date(),
  974. createdAt: new Date(),
  975. });
  976. } catch (err) {
  977. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  978. }
  979. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  980. });
  981. // ─── Legacy post route ────────────────────────────────────────────────────────
  982. let rabbitMQProducer = new RabbitMQProducer();
  983. app.post('/', async (request, reply) => {
  984. try {
  985. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  986. reply.send({ status: 'ok' });
  987. } catch (error) {
  988. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  989. reply.status(500).send({ error: 'Internal Server Error' });
  990. }
  991. });
  992. // ─── Meta App Credentials ────────────────────────────────────────────────────
  993. // Save Facebook App ID + Secret (entered by user in Settings UI)
  994. app.post('/credentials/meta-app', async (request, reply) => {
  995. const { appId, appSecret } = request.body || {};
  996. if (!appId || !appSecret) {
  997. return reply.code(400).send({ error: 'appId and appSecret are required' });
  998. }
  999. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  1000. return { success: true };
  1001. });
  1002. // Get Meta App config (secret is masked for UI display)
  1003. app.get('/credentials/meta-app', async () => {
  1004. const cred = await getCredentials('meta_app');
  1005. if (!cred) return { configured: false };
  1006. const plainSecret = decryptToken(cred.appSecret) || '';
  1007. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  1008. });
  1009. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  1010. // Return the Facebook OAuth URL to redirect the user to
  1011. app.get('/auth/meta/init', async (request, reply) => {
  1012. const cred = await getCredentials('meta_app');
  1013. if (!cred?.appId) {
  1014. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  1015. }
  1016. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1017. const scopes = [
  1018. 'pages_manage_posts',
  1019. 'pages_read_engagement',
  1020. 'instagram_basic',
  1021. 'instagram_content_publish',
  1022. 'instagram_manage_insights',
  1023. ].join(',');
  1024. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  1025. return { url };
  1026. });
  1027. // OAuth callback — Facebook redirects here after user authorises
  1028. app.get('/auth/meta/callback', async (request, reply) => {
  1029. const { code, error: oauthError } = request.query;
  1030. if (oauthError) {
  1031. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  1032. }
  1033. if (!code) {
  1034. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  1035. }
  1036. try {
  1037. const appCred = await getCredentials('meta_app');
  1038. if (!appCred?.appId) throw new Error('App credentials not configured');
  1039. const appSecret = decryptToken(appCred.appSecret);
  1040. if (!appSecret) throw new Error('Failed to decrypt app secret');
  1041. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1042. // Exchange code for short-lived token
  1043. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1044. params: {
  1045. client_id: appCred.appId,
  1046. client_secret: appSecret,
  1047. redirect_uri: redirectUri,
  1048. code,
  1049. },
  1050. });
  1051. // Upgrade to long-lived user token (~60 days)
  1052. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1053. params: {
  1054. grant_type: 'fb_exchange_token',
  1055. client_id: appCred.appId,
  1056. client_secret: appSecret,
  1057. fb_exchange_token: shortRes.data.access_token,
  1058. },
  1059. });
  1060. const userToken = longRes.data.access_token;
  1061. // Fetch all managed Facebook Pages
  1062. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  1063. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  1064. });
  1065. const pages = [];
  1066. const igAccounts = [];
  1067. for (const page of pagesRes.data.data || []) {
  1068. pages.push({
  1069. id: page.id,
  1070. name: page.name,
  1071. accessToken: encryptToken(page.access_token),
  1072. picture: page.picture?.data?.url || null,
  1073. selected: false,
  1074. });
  1075. // Check for linked Instagram Business Account
  1076. try {
  1077. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  1078. params: {
  1079. fields: 'instagram_business_account',
  1080. access_token: page.access_token,
  1081. },
  1082. });
  1083. if (igRes.data.instagram_business_account?.id) {
  1084. const igId = igRes.data.instagram_business_account.id;
  1085. // Fetch IG account details
  1086. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1087. params: {
  1088. fields: 'id,username,name,profile_picture_url',
  1089. access_token: userToken,
  1090. },
  1091. });
  1092. igAccounts.push({
  1093. id: igId,
  1094. username: igProfile.data.username || igProfile.data.name,
  1095. name: igProfile.data.name,
  1096. avatar: igProfile.data.profile_picture_url || null,
  1097. accessToken: encryptToken(userToken),
  1098. pageId: page.id,
  1099. selected: false,
  1100. });
  1101. }
  1102. } catch (_) {
  1103. // Page has no linked Instagram account — skip
  1104. }
  1105. }
  1106. // Store discovery results for the UI to pick from
  1107. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1108. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1109. } catch (err) {
  1110. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1111. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1112. }
  1113. });
  1114. // Return pending discovery results so the UI can render the page picker
  1115. app.get('/auth/meta/discovered', async () => {
  1116. const discovery = await getCredentials('meta_discovery');
  1117. if (!discovery) return { pages: [], igAccounts: [] };
  1118. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1119. });
  1120. // User has chosen which pages/accounts to connect
  1121. app.post('/auth/meta/save', async (request, reply) => {
  1122. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1123. const discovery = await getCredentials('meta_discovery');
  1124. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1125. const fbPages = (discovery.pages || []).map((p) => ({
  1126. ...p,
  1127. selected: selectedPageIds.includes(p.id),
  1128. }));
  1129. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1130. ...a,
  1131. selected: selectedIgAccountIds.includes(a.id),
  1132. }));
  1133. await setCredentials('facebook', { pages: fbPages });
  1134. await setCredentials('instagram', { accounts: igAccounts });
  1135. await deleteCredentials('meta_discovery');
  1136. _tokenExpiryCache = null; // invalidate cache after reconnect
  1137. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1138. });
  1139. // Disconnect all Meta platforms
  1140. app.delete('/credentials/meta', async () => {
  1141. await deleteCredentials('facebook');
  1142. await deleteCredentials('instagram');
  1143. await deleteCredentials('meta_discovery');
  1144. return { success: true };
  1145. });
  1146. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1147. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1148. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1149. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1150. app.post('/credentials/pinterest-app', async (request, reply) => {
  1151. const { clientId, clientSecret } = request.body || {};
  1152. if (!clientId || !clientSecret) {
  1153. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1154. }
  1155. await setCredentials('pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1156. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1157. return { success: true };
  1158. });
  1159. app.get('/credentials/pinterest-app', async () => {
  1160. const cred = await getCredentials('pinterest_app');
  1161. if (!cred) return { configured: false };
  1162. const plain = decryptToken(cred.clientSecret) || '';
  1163. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1164. });
  1165. app.get('/auth/pinterest/init', async (request, reply) => {
  1166. const cred = await getCredentials('pinterest_app');
  1167. if (!cred?.clientId) {
  1168. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1169. }
  1170. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1171. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1172. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1173. return { url };
  1174. });
  1175. app.get('/auth/pinterest/callback', async (request, reply) => {
  1176. const { code, error: oauthError } = request.query;
  1177. if (oauthError) {
  1178. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1179. }
  1180. if (!code) {
  1181. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1182. }
  1183. try {
  1184. const appCred = await getCredentials('pinterest_app');
  1185. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1186. const clientSecret = decryptToken(appCred.clientSecret);
  1187. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1188. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1189. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1190. const tokenRes = await axios.post(
  1191. PINTEREST_TOKEN_URL,
  1192. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1193. {
  1194. headers: {
  1195. Authorization: `Basic ${basicAuth}`,
  1196. 'Content-Type': 'application/x-www-form-urlencoded',
  1197. },
  1198. timeout: 15000,
  1199. }
  1200. );
  1201. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1202. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1203. const [userRes, boardsRes] = await Promise.all([
  1204. axios.get(`${PINTEREST_API}/user_account`, {
  1205. headers: { Authorization: `Bearer ${access_token}` },
  1206. timeout: 10000,
  1207. }),
  1208. axios.get(`${PINTEREST_API}/boards`, {
  1209. headers: { Authorization: `Bearer ${access_token}` },
  1210. params: { page_size: 100 },
  1211. timeout: 15000,
  1212. }),
  1213. ]);
  1214. const boards = (boardsRes.data.items || []).map((b) => ({
  1215. id: b.id,
  1216. name: b.name,
  1217. privacy: b.privacy,
  1218. selected: false,
  1219. }));
  1220. await setCredentials('pinterest', {
  1221. userId: userRes.data.username,
  1222. username: userRes.data.username,
  1223. displayName: userRes.data.business_name || userRes.data.username,
  1224. avatar: userRes.data.profile_image,
  1225. accessToken: encryptToken(access_token),
  1226. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1227. tokenExpiry,
  1228. boards,
  1229. });
  1230. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1231. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1232. } catch (err) {
  1233. const msg = err.response?.data?.message || err.message;
  1234. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1235. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1236. }
  1237. });
  1238. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1239. const { selectedBoardIds = [] } = request.body || {};
  1240. const cred = await getCredentials('pinterest');
  1241. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1242. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1243. await setCredentials('pinterest', { ...cred, boards });
  1244. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1245. return { success: true, selected: boards.filter((b) => b.selected).length };
  1246. });
  1247. app.delete('/credentials/pinterest', async () => {
  1248. await deleteCredentials('pinterest');
  1249. return { success: true };
  1250. });
  1251. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1252. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1253. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1254. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1255. app.post('/credentials/tiktok-app', async (request, reply) => {
  1256. const { clientKey, clientSecret } = request.body || {};
  1257. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1258. await setCredentials('tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1259. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1260. return { success: true };
  1261. });
  1262. app.get('/credentials/tiktok-app', async () => {
  1263. const cred = await getCredentials('tiktok_app');
  1264. if (!cred?.clientKey) return { configured: false };
  1265. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1266. });
  1267. app.get('/auth/tiktok/init', async (request, reply) => {
  1268. const cred = await getCredentials('tiktok_app');
  1269. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1270. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1271. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1272. const state = crypto.randomBytes(16).toString('hex');
  1273. // Persist PKCE verifier for the callback
  1274. const db = await getDb();
  1275. await db.collection('platform_credentials').updateOne(
  1276. { _id: 'tiktok_pkce' },
  1277. { $set: { codeVerifier, state, createdAt: new Date() } },
  1278. { upsert: true }
  1279. );
  1280. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1281. const scopes = 'user.info.basic,video.list,video.publish';
  1282. const params = new URLSearchParams({
  1283. client_key: cred.clientKey,
  1284. scope: scopes,
  1285. response_type: 'code',
  1286. redirect_uri: redirectUri,
  1287. state,
  1288. code_challenge: codeChallenge,
  1289. code_challenge_method: 'S256',
  1290. });
  1291. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1292. });
  1293. app.get('/auth/tiktok/callback', async (request, reply) => {
  1294. const { code, state, error: oauthError, error_description } = request.query;
  1295. if (oauthError) {
  1296. const msg = error_description || oauthError;
  1297. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1298. }
  1299. if (!code) {
  1300. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1301. }
  1302. try {
  1303. const db = await getDb();
  1304. const pkce = await db.collection('platform_credentials').findOne({ _id: 'tiktok_pkce' });
  1305. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1306. if (state && pkce.state && state !== pkce.state) throw new Error('OAuth state mismatch');
  1307. const appCred = await getCredentials('tiktok_app');
  1308. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1309. const clientSecret = decryptToken(appCred.clientSecret);
  1310. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1311. const tokenRes = await axios.post(
  1312. TIKTOK_TOKEN_URL,
  1313. new URLSearchParams({
  1314. client_key: appCred.clientKey,
  1315. client_secret: clientSecret,
  1316. code,
  1317. grant_type: 'authorization_code',
  1318. redirect_uri: redirectUri,
  1319. code_verifier: pkce.codeVerifier,
  1320. }).toString(),
  1321. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1322. );
  1323. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1324. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1325. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1326. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1327. headers: { Authorization: `Bearer ${access_token}` },
  1328. params: { fields: 'open_id,display_name,avatar_url,username' },
  1329. timeout: 10000,
  1330. });
  1331. const user = userRes.data?.data?.user || {};
  1332. await setCredentials('tiktok', {
  1333. openId: open_id || user.open_id,
  1334. username: user.username || user.display_name,
  1335. displayName: user.display_name,
  1336. avatar: user.avatar_url || null,
  1337. accessToken: encryptToken(access_token),
  1338. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1339. tokenExpiry,
  1340. refreshExpiry,
  1341. });
  1342. // Clean up PKCE temp state
  1343. await db.collection('platform_credentials').deleteOne({ _id: 'tiktok_pkce' });
  1344. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1345. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1346. } catch (err) {
  1347. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1348. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1349. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1350. }
  1351. });
  1352. app.delete('/credentials/tiktok', async () => {
  1353. await deleteCredentials('tiktok');
  1354. return { success: true };
  1355. });
  1356. // ─── Credential Status ────────────────────────────────────────────────────────
  1357. // Aggregate connection status for all DB-managed platforms
  1358. app.get('/credentials', async () => {
  1359. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1360. getCredentials('meta_app'),
  1361. getCredentials('facebook'),
  1362. getCredentials('instagram'),
  1363. getCredentials('pinterest'),
  1364. getCredentials('tiktok'),
  1365. ]);
  1366. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1367. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1368. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1369. return {
  1370. metaApp: { configured: !!(metaApp?.appId) },
  1371. facebook: {
  1372. connected: fbPages.length > 0,
  1373. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1374. },
  1375. instagram: {
  1376. connected: igAccounts.length > 0,
  1377. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1378. },
  1379. pinterest: {
  1380. connected: pinterestBoards.length > 0,
  1381. username: pinterest?.username || null,
  1382. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1383. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1384. },
  1385. tiktok: {
  1386. connected: !!(tiktok?.accessToken),
  1387. username: tiktok?.username || null,
  1388. displayName: tiktok?.displayName || null,
  1389. avatar: tiktok?.avatar || null,
  1390. },
  1391. };
  1392. });
  1393. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1394. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1395. const INDUSTRY_DEFAULTS = {
  1396. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1397. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1398. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1399. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1400. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1401. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1402. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1403. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1404. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1405. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  1406. };
  1407. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  1408. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  1409. // at least `afterMs` milliseconds in the future.
  1410. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  1411. const candidate = new Date(afterMs);
  1412. candidate.setUTCHours(hourUTC, 0, 0, 0);
  1413. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  1414. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  1415. candidate.setUTCDate(candidate.getUTCDate() + 7);
  1416. } else {
  1417. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  1418. }
  1419. return candidate;
  1420. }
  1421. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  1422. app.get('/schedule/suggestions', async (request, reply) => {
  1423. const { platform, accountId } = request.query;
  1424. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  1425. const db = await getDb();
  1426. const query = { platform, ...(accountId && { accountId }) };
  1427. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  1428. let slots;
  1429. let source;
  1430. if (dataPoints >= 10) {
  1431. const agg = await db.collection('post_metrics').aggregate([
  1432. { $match: query },
  1433. { $group: {
  1434. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1435. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1436. count: { $sum: 1 },
  1437. }},
  1438. { $sort: { avgEngagement: -1 } },
  1439. { $limit: 5 },
  1440. ]).toArray();
  1441. slots = agg.map((r) => [r._id.day, r._id.hour]);
  1442. source = 'history';
  1443. } else {
  1444. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  1445. source = 'default';
  1446. }
  1447. // 30-minute lead time so the user has time to finish writing
  1448. const afterMs = Date.now() + 30 * 60 * 1000;
  1449. const suggestions = slots
  1450. .map(([day, hour]) => {
  1451. const dt = nextOccurrence(day, hour, afterMs);
  1452. const h12 = hour % 12 || 12;
  1453. const ampm = hour < 12 ? 'am' : 'pm';
  1454. return {
  1455. utc: dt.toISOString(),
  1456. dayOfWeek: day,
  1457. hour,
  1458. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  1459. };
  1460. })
  1461. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  1462. .slice(0, 4);
  1463. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  1464. return { source, suggestions };
  1465. });
  1466. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  1467. async function crawlFacebookMetrics(db) {
  1468. const fb = await getCredentials('facebook');
  1469. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  1470. if (!pages.length) return { count: 0 };
  1471. let count = 0;
  1472. for (const page of pages) {
  1473. const token = decryptToken(page.accessToken);
  1474. if (!token) continue;
  1475. try {
  1476. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  1477. params: {
  1478. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  1479. limit: 100,
  1480. access_token: token,
  1481. },
  1482. timeout: 30000,
  1483. });
  1484. for (const post of res.data.data || []) {
  1485. const likes = post.reactions?.summary?.total_count || 0;
  1486. const comments = post.comments?.summary?.total_count || 0;
  1487. const shares = post.shares?.count || 0;
  1488. const publishedAt = new Date(post.created_time);
  1489. await db.collection('post_metrics').updateOne(
  1490. { platform: 'facebook', postId: post.id },
  1491. {
  1492. $set: {
  1493. platform: 'facebook',
  1494. accountId: page.id,
  1495. accountName: page.name,
  1496. postId: post.id,
  1497. content: post.message || null,
  1498. publishedAt,
  1499. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  1500. hourOfDay: publishedAt.getUTCHours(),
  1501. dayOfWeek: publishedAt.getUTCDay(),
  1502. fetchedAt: new Date(),
  1503. },
  1504. },
  1505. { upsert: true }
  1506. );
  1507. count++;
  1508. }
  1509. } catch (err) {
  1510. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  1511. }
  1512. }
  1513. return { count };
  1514. }
  1515. async function crawlInstagramMetrics(db) {
  1516. const ig = await getCredentials('instagram');
  1517. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  1518. if (!accounts.length) return { count: 0 };
  1519. let count = 0;
  1520. for (const account of accounts) {
  1521. const token = decryptToken(account.accessToken);
  1522. if (!token) continue;
  1523. try {
  1524. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  1525. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  1526. timeout: 30000,
  1527. });
  1528. for (const media of mediaRes.data.data || []) {
  1529. const likes = media.like_count || 0;
  1530. const comments = media.comments_count || 0;
  1531. const publishedAt = new Date(media.timestamp);
  1532. let views = 0;
  1533. let saves = 0;
  1534. try {
  1535. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  1536. params: { metric: 'reach,saved', access_token: token },
  1537. timeout: 10000,
  1538. });
  1539. for (const ins of insRes.data.data || []) {
  1540. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  1541. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  1542. }
  1543. } catch (_) {}
  1544. await db.collection('post_metrics').updateOne(
  1545. { platform: 'instagram', postId: media.id },
  1546. {
  1547. $set: {
  1548. platform: 'instagram',
  1549. accountId: account.id,
  1550. accountName: account.username,
  1551. postId: media.id,
  1552. content: media.caption || null,
  1553. publishedAt,
  1554. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  1555. hourOfDay: publishedAt.getUTCHours(),
  1556. dayOfWeek: publishedAt.getUTCDay(),
  1557. fetchedAt: new Date(),
  1558. },
  1559. },
  1560. { upsert: true }
  1561. );
  1562. count++;
  1563. }
  1564. } catch (err) {
  1565. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  1566. }
  1567. }
  1568. return { count };
  1569. }
  1570. app.post('/analytics/crawl', async () => {
  1571. const db = await getDb();
  1572. const results = {};
  1573. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  1574. try {
  1575. results[platform] = await crawler(db);
  1576. } catch (err) {
  1577. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  1578. results[platform] = { count: 0, error: err.message };
  1579. }
  1580. }
  1581. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  1582. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  1583. return { success: true, total, byPlatform: results };
  1584. });
  1585. app.get('/analytics/insights', async (request) => {
  1586. const filter = parseAccountFilter(request.query.account);
  1587. const metricsMatch = filter
  1588. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1589. : {};
  1590. const db = await getDb();
  1591. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  1592. if (total === 0) return { empty: true };
  1593. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  1594. db.collection('post_metrics').aggregate([
  1595. { $match: metricsMatch },
  1596. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1597. { $sort: { _id: 1 } },
  1598. ]).toArray(),
  1599. db.collection('post_metrics').aggregate([
  1600. { $match: metricsMatch },
  1601. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1602. { $sort: { _id: 1 } },
  1603. ]).toArray(),
  1604. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  1605. db.collection('post_metrics').aggregate([
  1606. { $match: metricsMatch },
  1607. { $group: {
  1608. _id: '$platform',
  1609. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1610. avgLikes: { $avg: '$metrics.likes' },
  1611. avgComments: { $avg: '$metrics.comments' },
  1612. avgShares: { $avg: '$metrics.shares' },
  1613. totalPosts: { $sum: 1 },
  1614. }},
  1615. { $sort: { avgEngagement: -1 } },
  1616. ]).toArray(),
  1617. db.collection('post_metrics').aggregate([
  1618. { $match: metricsMatch },
  1619. { $group: {
  1620. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1621. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1622. count: { $sum: 1 },
  1623. }},
  1624. ]).toArray(),
  1625. ]);
  1626. const byHour = Array.from({ length: 24 }, (_, h) => {
  1627. const e = byHourRaw.find((r) => r._id === h);
  1628. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1629. });
  1630. const byDay = Array.from({ length: 7 }, (_, d) => {
  1631. const e = byDayRaw.find((r) => r._id === d);
  1632. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1633. });
  1634. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  1635. const day = Math.floor(i / 24);
  1636. const hour = i % 24;
  1637. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  1638. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1639. });
  1640. return {
  1641. empty: false,
  1642. total,
  1643. byHour,
  1644. byDay,
  1645. heatmap,
  1646. topPosts: topPosts.map((p) => ({
  1647. platform: p.platform, accountName: p.accountName, postId: p.postId,
  1648. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  1649. })),
  1650. platformComparison: platformComparison.map((p) => ({
  1651. platform: p._id,
  1652. avgEngagement: Math.round(p.avgEngagement),
  1653. avgLikes: Math.round(p.avgLikes),
  1654. avgComments: Math.round(p.avgComments),
  1655. avgShares: Math.round(p.avgShares),
  1656. totalPosts: p.totalPosts,
  1657. })),
  1658. };
  1659. });
  1660. // ─── Analytics ────────────────────────────────────────────────────────────────
  1661. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  1662. function parseAccountFilter(account) {
  1663. if (!account) return null;
  1664. const idx = account.indexOf(':');
  1665. if (idx === -1) return { platform: account };
  1666. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  1667. }
  1668. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  1669. function sjFilter(filter) {
  1670. if (!filter) return {};
  1671. return {
  1672. 'destinations.platform': filter.platform,
  1673. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1674. };
  1675. }
  1676. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  1677. function ipFilter(filter) {
  1678. if (!filter) return {};
  1679. return {
  1680. 'destinations.platform': filter.platform,
  1681. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1682. };
  1683. }
  1684. app.get('/analytics/summary', async (request) => {
  1685. const filter = parseAccountFilter(request.query.account);
  1686. const db = await getDb();
  1687. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1688. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1689. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  1690. // account filter after $unwind so a job targeting multiple platforms only
  1691. // counts the platform(s) that match the filter.
  1692. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  1693. const [
  1694. schedCompleted, schedFailed,
  1695. immPublished, immFailed,
  1696. recentSched, recentImm,
  1697. schedPlatformRaw, immPlatformRaw,
  1698. schedDayRaw, immDayRaw,
  1699. ] = await Promise.all([
  1700. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  1701. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  1702. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  1703. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  1704. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  1705. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  1706. // Platform breakdown from scheduled_jobs destinations
  1707. db.collection('scheduled_jobs').aggregate([
  1708. { $match: { status: 'completed', ...sjFilter(filter) } },
  1709. { $unwind: '$destinations' },
  1710. ...unwindFilter,
  1711. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  1712. { $sort: { count: -1 } },
  1713. ]).toArray(),
  1714. // Platform breakdown from immediate posts platformResults
  1715. db.collection('posts').aggregate([
  1716. { $match: { type: 'immediate', ...ipFilter(filter) } },
  1717. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  1718. { $unwind: '$results' },
  1719. { $match: { 'results.v.success': true } },
  1720. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  1721. { $group: { _id: '$platform', count: { $sum: 1 } } },
  1722. ]).toArray(),
  1723. // Activity by day from scheduled_jobs (using completedAt)
  1724. db.collection('scheduled_jobs').aggregate([
  1725. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  1726. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  1727. { $sort: { _id: 1 } },
  1728. ]).toArray(),
  1729. // Activity by day from immediate posts
  1730. db.collection('posts').aggregate([
  1731. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  1732. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  1733. { $sort: { _id: 1 } },
  1734. ]).toArray(),
  1735. ]);
  1736. const dayMap = {};
  1737. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1738. dayMap[_id] = (dayMap[_id] || 0) + count;
  1739. }
  1740. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1741. const platformMap = {};
  1742. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1743. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1744. }
  1745. const published = schedCompleted + immPublished;
  1746. const failed = schedFailed + immFailed;
  1747. const total = published + failed;
  1748. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1749. const recentCount = recentSched + recentImm;
  1750. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1751. });
  1752. app.get('/analytics/posts', async (request) => {
  1753. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1754. const skip = parseInt(request.query.skip || '0', 10);
  1755. const filter = parseAccountFilter(request.query.account);
  1756. const db = await getDb();
  1757. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1758. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1759. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1760. db.collection('scheduled_jobs')
  1761. .find(sjMatch)
  1762. .sort({ completedAt: -1, scheduledAt: -1 })
  1763. .skip(skip)
  1764. .limit(limit)
  1765. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1766. .toArray(),
  1767. db.collection('posts')
  1768. .find(ipMatch)
  1769. .sort({ publishedAt: -1 })
  1770. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1771. .toArray(),
  1772. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1773. db.collection('posts').countDocuments(ipMatch),
  1774. ]);
  1775. const normalised = [
  1776. ...scheduledJobs.map((j) => ({
  1777. _id: String(j._id),
  1778. type: 'scheduled',
  1779. content: j.content || null,
  1780. destinations: j.destinations || [],
  1781. platformResults: null,
  1782. status: j.status === 'completed' ? 'published' : 'failed',
  1783. publishedAt: j.completedAt || j.scheduledAt,
  1784. })),
  1785. ...immediatePosts.map((p) => ({
  1786. _id: String(p._id),
  1787. type: 'immediate',
  1788. content: p.content || null,
  1789. destinations: p.destinations || [],
  1790. platformResults: p.platformResults || null,
  1791. status: p.status,
  1792. publishedAt: p.publishedAt,
  1793. })),
  1794. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  1795. .slice(0, limit);
  1796. return { posts: normalised, total: schedTotal + immTotal };
  1797. });
  1798. // ─── Brand / Account Audit ────────────────────────────────────────────────────
  1799. app.post('/analytics/audit', async (request, reply) => {
  1800. const filter = parseAccountFilter(request.query.account);
  1801. const db = await getDb();
  1802. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1803. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1804. const recentPosts = await db.collection('posts').find({
  1805. publishedAt: { $gte: thirtyDaysAgo },
  1806. ...ipFilter(filter),
  1807. }, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } }).toArray();
  1808. if (recentPosts.length < 3) {
  1809. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 3 posts first.' });
  1810. }
  1811. // Posting frequency
  1812. const postsLast30 = recentPosts.length;
  1813. const postsLast7 = recentPosts.filter((p) => new Date(p.publishedAt) >= sevenDaysAgo).length;
  1814. const postsPerWeek = Math.round((postsLast30 / 4) * 10) / 10;
  1815. // Platforms used
  1816. const platforms = [...new Set(recentPosts.flatMap((p) => (p.destinations || []).map((d) => d.platform)).filter(Boolean))];
  1817. // Success rate
  1818. const publishedCount = recentPosts.filter((p) => p.status === 'published').length;
  1819. const successRate = Math.round((publishedCount / postsLast30) * 100);
  1820. // Top hashtags from post content
  1821. const hashtagCounts = {};
  1822. for (const post of recentPosts) {
  1823. const re = /#([a-zA-Z]\w*)/g;
  1824. let m;
  1825. re.lastIndex = 0;
  1826. while ((m = re.exec(post.content || '')) !== null) {
  1827. const tag = `#${m[1].toLowerCase()}`;
  1828. hashtagCounts[tag] = (hashtagCounts[tag] || 0) + 1;
  1829. }
  1830. }
  1831. const topHashtags = Object.entries(hashtagCounts)
  1832. .sort((a, b) => b[1] - a[1])
  1833. .slice(0, 5)
  1834. .map(([tag, count]) => `${tag} (${count}x)`)
  1835. .join(', ');
  1836. // Posting hour distribution — identify peak hours
  1837. const hourCounts = {};
  1838. for (const post of recentPosts) {
  1839. if (post.publishedAt) {
  1840. const h = new Date(post.publishedAt).getUTCHours();
  1841. hourCounts[h] = (hourCounts[h] || 0) + 1;
  1842. }
  1843. }
  1844. const peakHours = Object.entries(hourCounts)
  1845. .sort((a, b) => b[1] - a[1])
  1846. .slice(0, 3)
  1847. .map(([h]) => `${h}:00 UTC`)
  1848. .join(', ');
  1849. // Engagement data from post_metrics
  1850. const metricsFilter = filter
  1851. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1852. : {};
  1853. const metrics = await db.collection('post_metrics')
  1854. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  1855. .toArray();
  1856. const avgEngagement = metrics.length > 0
  1857. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  1858. : 0;
  1859. const statsBlock = [
  1860. `Publishing stats (last 30 days):`,
  1861. `- Total posts: ${postsLast30}`,
  1862. `- Posts this week: ${postsLast7}`,
  1863. `- Posts per week (avg): ${postsPerWeek}`,
  1864. `- Platforms used: ${platforms.join(', ') || 'unknown'}`,
  1865. `- Success rate: ${successRate}%`,
  1866. `- Average engagement per post: ${avgEngagement}`,
  1867. `- Current peak posting hours (UTC): ${peakHours || 'not enough data'}`,
  1868. `- Top hashtags in use: ${topHashtags || 'none detected'}`,
  1869. ].join('\n');
  1870. const system = 'You are a social media performance analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  1871. const prompt = `Audit this social media account and return a structured report.
  1872. ${statsBlock}
  1873. Return a JSON object with exactly these fields:
  1874. {
  1875. "score": <overall health score 0-100>,
  1876. "summary": "<2-3 sentence assessment>",
  1877. "postingFrequency": { "score": <0-10>, "assessment": "<one sentence>" },
  1878. "engagement": { "score": <0-10>, "benchmark": "<Excellent|Good|Average|Below Average>", "assessment": "<one sentence>" },
  1879. "contentMix": { "score": <0-10>, "assessment": "<one sentence on variety and platform fit>" },
  1880. "recommendations": ["<specific action 1>", "<specific action 2>", "<specific action 3>"]
  1881. }
  1882. Scoring benchmarks: posting 5+x/week = 8-10, 3-4x = 6-7, 1-2x = 4-5, less = 1-3.
  1883. Engagement benchmarks: >5 avg = Excellent, 3-5 = Good, 1-3 = Average, <1 = Below Average.
  1884. Return ONLY the JSON object.`;
  1885. try {
  1886. const pconf = await getActiveProviderConfig();
  1887. const model = pconf.model;
  1888. let text = '';
  1889. if (pconf.provider === 'ollama') {
  1890. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  1891. text = res.data.response;
  1892. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1893. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  1894. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1895. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1896. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  1897. text = res.data.choices[0]?.message?.content || '';
  1898. } else if (pconf.provider === 'gemini') {
  1899. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  1900. const res = await axios.post(
  1901. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1902. { contents: buildGeminiContents(prompt, system) },
  1903. { timeout: 120000 },
  1904. );
  1905. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1906. } else {
  1907. return reply.code(400).send({ error: 'AI not configured' });
  1908. }
  1909. let audit = null;
  1910. try {
  1911. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  1912. audit = JSON.parse(jsonStr);
  1913. if (typeof audit.score !== 'number') throw new Error();
  1914. } catch {
  1915. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  1916. }
  1917. log.info({ action: 'analytics_audit', account: request.query.account || 'all', outcome: 'success' });
  1918. return {
  1919. success: true,
  1920. ...audit,
  1921. stats: { postsLast30, postsLast7, postsPerWeek, platforms, successRate, avgEngagement },
  1922. generatedAt: new Date(),
  1923. };
  1924. } catch (err) {
  1925. return reply.code(503).send({ error: 'Audit failed', detail: err.message });
  1926. }
  1927. });
  1928. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  1929. app.get('/hashtag-groups', async () => {
  1930. const db = await getDb();
  1931. const groups = await db.collection('hashtag_groups').find({}).sort({ name: 1 }).toArray();
  1932. return { groups };
  1933. });
  1934. app.post('/hashtag-groups', async (request, reply) => {
  1935. const { name, hashtags } = request.body || {};
  1936. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  1937. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  1938. const db = await getDb();
  1939. const result = await db.collection('hashtag_groups').insertOne({
  1940. name: name.trim(),
  1941. hashtags: [...new Set(tags)],
  1942. createdAt: new Date(),
  1943. updatedAt: new Date(),
  1944. });
  1945. return { success: true, _id: result.insertedId };
  1946. });
  1947. app.put('/hashtag-groups/:id', async (request, reply) => {
  1948. const { id } = request.params;
  1949. const { name, hashtags } = request.body || {};
  1950. const update = { updatedAt: new Date() };
  1951. if (name?.trim()) update.name = name.trim();
  1952. if (hashtags) {
  1953. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  1954. update.hashtags = [...new Set(tags)];
  1955. }
  1956. const db = await getDb();
  1957. let oid;
  1958. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1959. await db.collection('hashtag_groups').updateOne({ _id: oid }, { $set: update });
  1960. return { success: true };
  1961. });
  1962. app.delete('/hashtag-groups/:id', async (request, reply) => {
  1963. const { id } = request.params;
  1964. const db = await getDb();
  1965. let oid;
  1966. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1967. await db.collection('hashtag_groups').deleteOne({ _id: oid });
  1968. return { success: true };
  1969. });
  1970. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  1971. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  1972. function extractHashtags(text) {
  1973. if (!text) return [];
  1974. const tags = [];
  1975. let m;
  1976. HASHTAG_RE.lastIndex = 0;
  1977. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  1978. return tags;
  1979. }
  1980. function gradeHashtag(count, avgEngagement) {
  1981. if (count >= 5 && avgEngagement >= 10) return 'A';
  1982. if (count >= 3 && avgEngagement >= 3) return 'B';
  1983. if (count >= 2) return 'C';
  1984. return 'D';
  1985. }
  1986. // POST /hashtags/scrape — scan YOUR published posts per-account.
  1987. // Body: { accountKey?: string } — omit to scan all accounts at once.
  1988. app.post('/hashtags/scrape', async (request) => {
  1989. const { accountKey: filterAccount } = request.body || {};
  1990. const db = await getDb();
  1991. // tagMap key: `${accountKey}||${hashtag}`
  1992. const tagMap = {};
  1993. function touch(tag, accountKey, platform, engagement) {
  1994. const key = `${accountKey}||${tag}`;
  1995. if (!tagMap[key]) tagMap[key] = { tag, accountKey, count: 0, totalEngagement: 0, platforms: new Set() };
  1996. tagMap[key].count++;
  1997. tagMap[key].totalEngagement += engagement;
  1998. tagMap[key].platforms.add(platform);
  1999. }
  2000. // Engagement lookup keyed by content fingerprint
  2001. const postMetrics = await db.collection('post_metrics').find({}).toArray();
  2002. const metricsByContent = {};
  2003. for (const m of postMetrics) {
  2004. if (m.content) {
  2005. const key = m.content.slice(0, 100).toLowerCase().trim();
  2006. metricsByContent[key] = (metricsByContent[key] || 0) + (m.metrics?.engagementTotal || 0);
  2007. }
  2008. }
  2009. // Scan YOUR published posts only — feeds are others' content, not your performance
  2010. const posts = await db.collection('posts').find({}, { projection: { content: 1, destinations: 1 } }).toArray();
  2011. for (const post of posts) {
  2012. const tags = extractHashtags(post.content || '');
  2013. if (!tags.length) continue;
  2014. const engagement = post.content
  2015. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  2016. : 0;
  2017. const destinations = post.destinations?.length ? post.destinations : [{ platform: 'unknown' }];
  2018. for (const dest of destinations) {
  2019. const acctKey = dest.accountId ? `${dest.platform}:${dest.accountId}` : dest.platform;
  2020. if (filterAccount && acctKey !== filterAccount) continue;
  2021. for (const tag of tags) {
  2022. touch(tag, acctKey, dest.platform, engagement / Math.max(tags.length, 1));
  2023. }
  2024. }
  2025. }
  2026. let scraped = 0;
  2027. for (const [compoundKey, data] of Object.entries(tagMap)) {
  2028. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  2029. await db.collection('hashtag_stats').updateOne(
  2030. { _id: compoundKey },
  2031. {
  2032. $set: {
  2033. hashtag: data.tag,
  2034. accountKey: data.accountKey,
  2035. count: data.count,
  2036. avgEngagement: Math.round(avgEngagement * 10) / 10,
  2037. grade: gradeHashtag(data.count, avgEngagement),
  2038. platforms: [...data.platforms],
  2039. lastScraped: new Date(),
  2040. },
  2041. },
  2042. { upsert: true }
  2043. );
  2044. scraped++;
  2045. }
  2046. log.info({ action: 'hashtag_scrape', accountKey: filterAccount || 'all', outcome: 'success', scraped });
  2047. return { success: true, scraped };
  2048. });
  2049. app.get('/hashtags/stats', async (request) => {
  2050. const { sort, accountKey } = request.query;
  2051. const db = await getDb();
  2052. const sortField = sort === 'engagement' ? 'avgEngagement' : 'count';
  2053. if (accountKey) {
  2054. // Per-account view
  2055. const stats = await db.collection('hashtag_stats')
  2056. .find({ accountKey })
  2057. .sort({ [sortField]: -1 })
  2058. .limit(200)
  2059. .toArray();
  2060. return { stats };
  2061. }
  2062. // Aggregate view: group by hashtag across all accounts
  2063. const allStats = await db.collection('hashtag_stats').find({ accountKey: { $exists: true } }).toArray();
  2064. const grouped = new Map();
  2065. for (const s of allStats) {
  2066. if (!s.hashtag) continue;
  2067. if (!grouped.has(s.hashtag)) {
  2068. grouped.set(s.hashtag, { count: 0, totalEngagement: 0, totalCount: 0, platforms: new Set(), lastScraped: null });
  2069. }
  2070. const g = grouped.get(s.hashtag);
  2071. g.count += s.count;
  2072. g.totalEngagement += s.avgEngagement * s.count;
  2073. g.totalCount += s.count;
  2074. for (const p of (s.platforms || [])) g.platforms.add(p);
  2075. if (!g.lastScraped || (s.lastScraped && new Date(s.lastScraped) > new Date(g.lastScraped))) g.lastScraped = s.lastScraped;
  2076. }
  2077. const stats = [...grouped.entries()]
  2078. .map(([tag, g]) => {
  2079. const avgEngagement = g.totalCount > 0 ? Math.round((g.totalEngagement / g.totalCount) * 10) / 10 : 0;
  2080. return {
  2081. _id: tag,
  2082. hashtag: tag,
  2083. accountKey: null,
  2084. count: g.count,
  2085. avgEngagement,
  2086. grade: gradeHashtag(g.count, avgEngagement),
  2087. platforms: [...g.platforms],
  2088. lastScraped: g.lastScraped,
  2089. };
  2090. })
  2091. .sort((a, b) => b[sortField] - a[sortField])
  2092. .slice(0, 200);
  2093. return { stats };
  2094. });
  2095. app.post('/hashtags/ai-suggest', async (request, reply) => {
  2096. const { accountKey, topTags = [], count = 20 } = request.body || {};
  2097. let profileCtx = '';
  2098. if (accountKey) {
  2099. try {
  2100. const db = await getDb();
  2101. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  2102. if (profile) {
  2103. const parts = [];
  2104. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  2105. if (profile.description) parts.push(`Description: ${profile.description}`);
  2106. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  2107. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  2108. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  2109. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  2110. profileCtx = parts.join('\n');
  2111. }
  2112. } catch (_) {}
  2113. }
  2114. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  2115. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  2116. const prompt = [
  2117. `Suggest ${count} high-performing hashtags for a social media account.`,
  2118. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  2119. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  2120. `\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`,
  2121. ].filter(Boolean).join('');
  2122. try {
  2123. const pconf = await getActiveProviderConfig();
  2124. const model = pconf.model;
  2125. let text = '';
  2126. if (pconf.provider === 'ollama') {
  2127. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  2128. text = res.data.response;
  2129. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2130. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2131. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2132. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2133. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  2134. text = res.data.choices[0]?.message?.content || '';
  2135. } else if (pconf.provider === 'gemini') {
  2136. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2137. const res = await axios.post(
  2138. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2139. { contents: buildGeminiContents(prompt, system) },
  2140. { timeout: 60000 },
  2141. );
  2142. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2143. } else {
  2144. return reply.code(400).send({ error: 'AI not configured' });
  2145. }
  2146. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  2147. return { success: true, hashtags: tags };
  2148. } catch (err) {
  2149. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  2150. }
  2151. });
  2152. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  2153. async function extractTextFromUrl(url) {
  2154. try {
  2155. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  2156. const html = res.data || '';
  2157. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  2158. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  2159. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  2160. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  2161. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  2162. } catch {
  2163. return '';
  2164. }
  2165. }
  2166. async function scrapeBluesky(profileUrl) {
  2167. try {
  2168. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  2169. if (!handle) return '';
  2170. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  2171. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  2172. return posts.join('\n').slice(0, 3000);
  2173. } catch {
  2174. return '';
  2175. }
  2176. }
  2177. async function scrapeMastodon(profileUrl) {
  2178. try {
  2179. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  2180. if (!m) return '';
  2181. const [, instance, username] = m;
  2182. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  2183. const accountId = lookupRes.data?.id;
  2184. if (!accountId) return '';
  2185. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  2186. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  2187. return posts.join('\n').slice(0, 3000);
  2188. } catch {
  2189. return '';
  2190. }
  2191. }
  2192. async function runCompetitorScrape(competitorId) {
  2193. const db = await getDb();
  2194. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  2195. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  2196. const newItems = [];
  2197. if (competitor.websiteUrl) {
  2198. const text = await extractTextFromUrl(competitor.websiteUrl);
  2199. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  2200. }
  2201. const socialEntries = Object.entries(competitor.socialUrls || {});
  2202. for (const [platform, url] of socialEntries) {
  2203. if (!url) continue;
  2204. let text = '';
  2205. if (platform === 'bluesky') text = await scrapeBluesky(url);
  2206. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  2207. else text = await extractTextFromUrl(url);
  2208. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  2209. }
  2210. const existing = competitor.scrapedContent || [];
  2211. // Detect whether any newly scraped content differs from what was previously stored
  2212. const existingFingerprints = new Set(existing.map((s) => s.url + '||' + s.text.slice(0, 200)));
  2213. const contentChanged = newItems.some((item) => !existingFingerprints.has(item.url + '||' + item.text.slice(0, 200)));
  2214. const combined = [...newItems, ...existing].slice(0, 20);
  2215. await db.collection('competitors').updateOne(
  2216. { _id: new ObjectId(competitorId) },
  2217. { $set: { scrapedContent: combined, contentChanged, lastScraped: new Date(), updatedAt: new Date() } },
  2218. );
  2219. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  2220. }
  2221. async function buildCompetitorSystemSuffix() {
  2222. try {
  2223. const db = await getDb();
  2224. const competitors = await db.collection('competitors').find({
  2225. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  2226. }).toArray();
  2227. if (!competitors.length) return '';
  2228. const lines = competitors.map((c) => {
  2229. if (c.aiAnalysis?.positioning) {
  2230. const a = c.aiAnalysis;
  2231. const parts = [`- ${c.name}:`];
  2232. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  2233. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  2234. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  2235. return parts.join('\n');
  2236. }
  2237. return `- ${c.name}: ${c.aiSummary}`;
  2238. }).join('\n');
  2239. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  2240. } catch {
  2241. return '';
  2242. }
  2243. }
  2244. // Discover competitors automatically using AI + account profile context
  2245. app.post('/competitors/discover', async (request, reply) => {
  2246. const db = await getDb();
  2247. // Use the first account profile for business context
  2248. const profile = await db.collection('account_profiles').findOne({});
  2249. const contextParts = [];
  2250. if (profile) {
  2251. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  2252. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  2253. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  2254. if (profile.websiteUrl) contextParts.push(`Website: ${profile.websiteUrl}`);
  2255. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  2256. }
  2257. if (!contextParts.length) {
  2258. return reply.code(400).send({ error: 'Set up at least one Account Profile in Settings before discovering competitors.' });
  2259. }
  2260. const system = 'You are a market research analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2261. const prompt = `Based on the following business profile, identify the top 5 direct competitors.
  2262. ${contextParts.join('\n')}
  2263. Return ONLY a JSON array of objects, e.g.:
  2264. [{"name":"Competitor Name","websiteUrl":"https://example.com","reason":"One sentence on why they compete directly"}]
  2265. Rules:
  2266. - Return real, existing businesses only.
  2267. - Include only direct competitors (same product/service category, same target audience).
  2268. - websiteUrl must be a valid https URL to the competitor's main website.
  2269. - No explanation outside the JSON array.`;
  2270. try {
  2271. const pconf = await getActiveProviderConfig();
  2272. const model = pconf.model;
  2273. let text = '';
  2274. if (pconf.provider === 'ollama') {
  2275. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2276. text = res.data.response;
  2277. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2278. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2279. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2280. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2281. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2282. text = res.data.choices[0]?.message?.content || '';
  2283. } else if (pconf.provider === 'gemini') {
  2284. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2285. const res = await axios.post(
  2286. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2287. { contents: buildGeminiContents(prompt, system) },
  2288. { timeout: 120000 },
  2289. );
  2290. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2291. } else {
  2292. return reply.code(400).send({ error: 'AI not configured' });
  2293. }
  2294. let suggestions = [];
  2295. try {
  2296. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2297. const parsed = JSON.parse(jsonStr);
  2298. if (!Array.isArray(parsed)) throw new Error();
  2299. suggestions = parsed
  2300. .filter((s) => s && typeof s.name === 'string' && typeof s.websiteUrl === 'string')
  2301. .slice(0, 5)
  2302. .map((s) => ({
  2303. name: s.name.trim(),
  2304. websiteUrl: s.websiteUrl.trim(),
  2305. reason: typeof s.reason === 'string' ? s.reason.trim() : '',
  2306. }));
  2307. } catch {
  2308. return reply.code(503).send({ error: 'AI returned invalid format — try again' });
  2309. }
  2310. log.info({ action: 'competitor_discover', count: suggestions.length, outcome: 'success' });
  2311. return { success: true, suggestions };
  2312. } catch (err) {
  2313. return reply.code(503).send({ error: 'Discovery failed', detail: err.message });
  2314. }
  2315. });
  2316. // List competitors
  2317. app.get('/competitors', async (request, reply) => {
  2318. const db = await getDb();
  2319. const list = await db.collection('competitors').find({}).sort({ createdAt: 1 }).toArray();
  2320. return list;
  2321. });
  2322. // Add competitor (max 2)
  2323. app.post('/competitors', async (request, reply) => {
  2324. const db = await getDb();
  2325. const count = await db.collection('competitors').countDocuments();
  2326. if (count >= 5) return reply.code(400).send({ error: 'Maximum 5 competitors allowed' });
  2327. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  2328. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  2329. const now = new Date();
  2330. const result = await db.collection('competitors').insertOne({
  2331. name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  2332. });
  2333. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  2334. return doc;
  2335. });
  2336. // Update competitor
  2337. app.put('/competitors/:id', async (request, reply) => {
  2338. const db = await getDb();
  2339. const { name, websiteUrl, socialUrls } = request.body || {};
  2340. const updates = { updatedAt: new Date() };
  2341. if (name !== undefined) updates.name = name;
  2342. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  2343. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  2344. await db.collection('competitors').updateOne({ _id: new ObjectId(request.params.id) }, { $set: updates });
  2345. const doc = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2346. return doc;
  2347. });
  2348. // Delete competitor
  2349. app.delete('/competitors/:id', async (request, reply) => {
  2350. const db = await getDb();
  2351. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id) });
  2352. return { success: true };
  2353. });
  2354. // Scrape one competitor — returns jobId immediately, runs in background
  2355. app.post('/competitors/:id/scrape', async (request, reply) => {
  2356. const jobId = new ObjectId().toString();
  2357. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  2358. (async () => {
  2359. try {
  2360. const result = await runCompetitorScrape(request.params.id);
  2361. activeScrapeJobs.set(jobId, {
  2362. status: result.ok ? 'done' : 'failed',
  2363. sources: result.sources,
  2364. message: result.message,
  2365. });
  2366. } catch (err) {
  2367. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  2368. }
  2369. })();
  2370. return reply.code(202).send({ jobId });
  2371. });
  2372. // Poll scrape job status
  2373. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  2374. const job = activeScrapeJobs.get(request.params.jobId);
  2375. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  2376. return job;
  2377. });
  2378. // Scrape all competitors (called by scheduler)
  2379. app.post('/competitors/scrape-all', async (request, reply) => {
  2380. const db = await getDb();
  2381. const all = await db.collection('competitors').find({}).toArray();
  2382. const results = [];
  2383. for (const c of all) {
  2384. const r = await runCompetitorScrape(c._id.toString());
  2385. results.push({ id: c._id.toString(), name: c.name, ...r });
  2386. }
  2387. return { success: true, results };
  2388. });
  2389. // Summarize competitor content with AI — returns structured analysis
  2390. app.post('/competitors/:id/summarize', async (request, reply) => {
  2391. const db = await getDb();
  2392. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2393. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2394. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  2395. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  2396. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2397. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  2398. {
  2399. "themes": ["3-5 main content topics or pillars they focus on"],
  2400. "tone": "one sentence describing their voice and communication style",
  2401. "positioning": "one sentence on how they position themselves in the market",
  2402. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  2403. "moves": ["3 specific content angles you could use to stand out against them"],
  2404. "profile": {
  2405. "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)",
  2406. "keyFeatures": ["3-5 core product or service features they emphasise"],
  2407. "marketingChannels": ["2-4 social/marketing channels they actively use based on content"],
  2408. "targetCustomer": "one sentence describing their apparent ideal customer"
  2409. }
  2410. }
  2411. Content:
  2412. ${content}
  2413. Return ONLY the JSON object. No explanation, no markdown.`;
  2414. try {
  2415. const pconf = await getActiveProviderConfig();
  2416. const model = pconf.model;
  2417. let text = '';
  2418. if (pconf.provider === 'ollama') {
  2419. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2420. text = res.data.response;
  2421. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2422. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2423. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2424. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2425. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2426. text = res.data.choices[0]?.message?.content || '';
  2427. } else if (pconf.provider === 'gemini') {
  2428. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2429. const res = await axios.post(
  2430. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2431. { contents: buildGeminiContents(prompt, system) },
  2432. { timeout: 180000 },
  2433. );
  2434. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2435. } else {
  2436. return reply.code(400).send({ error: 'AI not configured' });
  2437. }
  2438. let aiAnalysis = null;
  2439. try {
  2440. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2441. aiAnalysis = JSON.parse(jsonStr);
  2442. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  2443. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  2444. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  2445. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  2446. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  2447. // Validate profile block
  2448. if (!aiAnalysis.profile || typeof aiAnalysis.profile !== 'object') aiAnalysis.profile = {};
  2449. if (typeof aiAnalysis.profile.pricing !== 'string') aiAnalysis.profile.pricing = '';
  2450. if (!Array.isArray(aiAnalysis.profile.keyFeatures)) aiAnalysis.profile.keyFeatures = [];
  2451. if (!Array.isArray(aiAnalysis.profile.marketingChannels)) aiAnalysis.profile.marketingChannels = [];
  2452. if (typeof aiAnalysis.profile.targetCustomer !== 'string') aiAnalysis.profile.targetCustomer = '';
  2453. } catch {
  2454. aiAnalysis = null;
  2455. }
  2456. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  2457. await db.collection('competitors').updateOne(
  2458. { _id: new ObjectId(request.params.id) },
  2459. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  2460. );
  2461. return { success: true, aiAnalysis };
  2462. } catch (err) {
  2463. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  2464. }
  2465. });
  2466. // Extract keywords from scraped content using AI (item 34)
  2467. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  2468. const db = await getDb();
  2469. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2470. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2471. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  2472. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  2473. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2474. 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:
  2475. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  2476. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  2477. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  2478. - navigational: user is searching for a specific brand or tool by name
  2479. Content:
  2480. ${content}
  2481. Return ONLY a JSON array, e.g.:
  2482. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  2483. No explanation, no markdown.`;
  2484. try {
  2485. const pconf = await getActiveProviderConfig();
  2486. const model = pconf.model;
  2487. let text = '';
  2488. if (pconf.provider === 'ollama') {
  2489. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2490. text = res.data.response;
  2491. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2492. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2493. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2494. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2495. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2496. text = res.data.choices[0]?.message?.content || '';
  2497. } else if (pconf.provider === 'gemini') {
  2498. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2499. const res = await axios.post(
  2500. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2501. { contents: buildGeminiContents(prompt, system) },
  2502. { timeout: 120000 },
  2503. );
  2504. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2505. } else {
  2506. return reply.code(400).send({ error: 'AI not configured' });
  2507. }
  2508. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  2509. let keywords = [];
  2510. try {
  2511. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2512. const parsed = JSON.parse(jsonStr);
  2513. if (!Array.isArray(parsed)) throw new Error();
  2514. const now = new Date();
  2515. keywords = parsed
  2516. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  2517. .slice(0, 20)
  2518. .map((k) => ({
  2519. term: k.term.trim(),
  2520. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  2521. extractedAt: now,
  2522. }));
  2523. } catch {
  2524. keywords = [];
  2525. }
  2526. await db.collection('competitors').updateOne(
  2527. { _id: new ObjectId(request.params.id) },
  2528. { $set: { keywords, updatedAt: new Date() } },
  2529. );
  2530. return { success: true, keywords };
  2531. } catch (err) {
  2532. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  2533. }
  2534. });
  2535. // Analyse content gaps — compare competitor keywords against user's hashtag_stats
  2536. app.post('/competitors/:id/analyze-gaps', async (request, reply) => {
  2537. const db = await getDb();
  2538. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2539. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2540. const keywords = (competitor.keywords || []);
  2541. if (!keywords.length) return reply.code(400).send({ error: 'Extract keywords first before analysing gaps' });
  2542. const hashtagDocs = await db.collection('hashtag_stats')
  2543. .find({ accountKey: { $exists: true } }, { projection: { _id: 0, hashtag: 1 } })
  2544. .toArray();
  2545. const hashtagStatsEmpty = hashtagDocs.length === 0;
  2546. // Deduplicate across accounts — same hashtag used by any account counts as covered
  2547. const uniqueTags = [...new Set(hashtagDocs.map((h) => h.hashtag).filter(Boolean))];
  2548. const hashtagTexts = uniqueTags.map((tag) => ({ id: tag, text: tag.replace(/^#/, '').toLowerCase() }));
  2549. const INTENT_ORDER = { transactional: 0, commercial: 1, informational: 2, navigational: 3 };
  2550. function findMatchingHashtags(term) {
  2551. const words = term.toLowerCase().split(/\s+/).filter((w) => w.length >= 4);
  2552. return hashtagTexts
  2553. .filter(({ text }) => words.some((w) => text.includes(w)))
  2554. .map(({ id }) => id);
  2555. }
  2556. const gaps = [];
  2557. const covered = [];
  2558. for (const kw of keywords) {
  2559. const term = typeof kw === 'string' ? kw : kw.term;
  2560. const intent = typeof kw === 'string' ? 'informational' : (kw.intent || 'informational');
  2561. const matched = findMatchingHashtags(term);
  2562. if (matched.length) {
  2563. covered.push({ term, intent, matchedHashtags: matched.slice(0, 4) });
  2564. } else {
  2565. gaps.push({ term, intent });
  2566. }
  2567. }
  2568. gaps.sort((a, b) => (INTENT_ORDER[a.intent] ?? 99) - (INTENT_ORDER[b.intent] ?? 99));
  2569. const gapAnalysis = { gaps, covered, totalKeywords: keywords.length, hashtagStatsEmpty, lastAnalyzed: new Date() };
  2570. await db.collection('competitors').updateOne(
  2571. { _id: new ObjectId(request.params.id) },
  2572. { $set: { gapAnalysis, updatedAt: new Date() } },
  2573. );
  2574. return { success: true, ...gapAnalysis };
  2575. });
  2576. // Generate a 5-post content roadmap from competitor keywords and gaps
  2577. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  2578. const db = await getDb();
  2579. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2580. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2581. const keywords = (competitor.keywords || []);
  2582. const hasKeywords = keywords.length > 0;
  2583. const hasContent = (competitor.scrapedContent || []).length > 0;
  2584. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  2585. const kwList = hasKeywords
  2586. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  2587. : '';
  2588. const gaps = competitor.aiAnalysis?.gaps || [];
  2589. const moves = competitor.aiAnalysis?.moves || [];
  2590. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  2591. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  2592. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  2593. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2594. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  2595. ${kwSection}${gapsSection}${movesSection}
  2596. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  2597. - topic: short topic name, max 8 words
  2598. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  2599. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  2600. - rationale: one sentence on why this post wins against ${competitor.name}
  2601. Return ONLY a JSON array:
  2602. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  2603. No explanation, no markdown.`;
  2604. try {
  2605. const pconf = await getActiveProviderConfig();
  2606. const model = pconf.model;
  2607. let text = '';
  2608. if (pconf.provider === 'ollama') {
  2609. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2610. text = res.data.response;
  2611. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2612. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2613. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2614. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2615. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2616. text = res.data.choices[0]?.message?.content || '';
  2617. } else if (pconf.provider === 'gemini') {
  2618. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2619. const res = await axios.post(
  2620. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2621. { contents: buildGeminiContents(prompt, system) },
  2622. { timeout: 180000 },
  2623. );
  2624. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2625. } else {
  2626. return reply.code(400).send({ error: 'AI not configured' });
  2627. }
  2628. let roadmap = [];
  2629. try {
  2630. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2631. const parsed = JSON.parse(jsonStr);
  2632. if (!Array.isArray(parsed)) throw new Error();
  2633. roadmap = parsed
  2634. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  2635. .slice(0, 5)
  2636. .map((p) => ({
  2637. topic: p.topic.trim(),
  2638. headline: p.headline.trim(),
  2639. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  2640. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  2641. }));
  2642. } catch {
  2643. roadmap = [];
  2644. }
  2645. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  2646. await db.collection('competitors').updateOne(
  2647. { _id: new ObjectId(request.params.id) },
  2648. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  2649. );
  2650. return { success: true, contentRoadmap: roadmap };
  2651. } catch (err) {
  2652. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  2653. }
  2654. });
  2655. module.exports = app;