server.js 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527
  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. // Strategy consistency audit — check if a profile's fields are internally coherent
  449. app.post('/profiles/:accountKey/audit', async (request, reply) => {
  450. const { accountKey } = request.params;
  451. const db = await getDb();
  452. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  453. if (!profile) return reply.code(404).send({ error: 'Profile not found' });
  454. const filled = [
  455. profile.businessName, profile.description, profile.industry,
  456. profile.toneOfVoice, profile.targetAudience, profile.keywords,
  457. profile.hashtags, profile.postingGuidelines,
  458. ].filter(Boolean);
  459. if (filled.length < 3) {
  460. return reply.code(400).send({ error: 'Fill in at least 3 profile fields before running an audit' });
  461. }
  462. const profileBlock = [
  463. profile.businessName && `Business: ${profile.businessName}`,
  464. profile.description && `Description: ${profile.description}`,
  465. profile.industry && `Industry: ${profile.industry}`,
  466. profile.toneOfVoice && `Tone of voice: ${profile.toneOfVoice}`,
  467. profile.targetAudience && `Target audience: ${profile.targetAudience}`,
  468. profile.keywords && `Keywords: ${profile.keywords}`,
  469. profile.hashtags && `Preferred hashtags: ${profile.hashtags}`,
  470. profile.postingGuidelines && `Posting guidelines: ${profile.postingGuidelines}`,
  471. ].filter(Boolean).join('\n');
  472. const system = 'You are a brand strategy consultant. Return only valid JSON with no explanation, no markdown code blocks.';
  473. const prompt = `Audit the internal consistency of this social media account profile and identify any conflicts or misalignments.
  474. PROFILE:
  475. ${profileBlock}
  476. Check for these issues:
  477. 1. Audience-tone mismatch (e.g. B2B business using casual/Gen-Z tone)
  478. 2. Industry-keyword misalignment (keywords don't reflect stated industry)
  479. 3. Hashtag-audience misalignment (hashtags target a different audience than described)
  480. 4. Tone-guideline conflicts (tone of voice contradicts posting guidelines)
  481. 5. Missing critical context (fields that are vague and would hurt AI content quality)
  482. Return a JSON object:
  483. {
  484. "score": <consistency score 0-100>,
  485. "summary": "<2-3 sentence overall assessment>",
  486. "issues": [
  487. { "severity": "<high|medium|low>", "field": "<which field(s)>", "issue": "<what the conflict is>", "fix": "<specific recommendation>" }
  488. ],
  489. "strengths": ["<1-3 things the profile does well>"]
  490. }
  491. Return [] for issues if no problems found. Return ONLY the JSON object.`;
  492. try {
  493. const pconf = await getActiveProviderConfig();
  494. const model = pconf.model;
  495. let text = '';
  496. if (pconf.provider === 'ollama') {
  497. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  498. text = res.data.response;
  499. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  500. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  501. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  502. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  503. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  504. text = res.data.choices[0]?.message?.content || '';
  505. } else if (pconf.provider === 'gemini') {
  506. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  507. const res = await axios.post(
  508. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  509. { contents: buildGeminiContents(prompt, system) },
  510. { timeout: 90000 },
  511. );
  512. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  513. } else {
  514. return reply.code(400).send({ error: 'AI not configured' });
  515. }
  516. let result = null;
  517. try {
  518. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  519. result = JSON.parse(jsonStr);
  520. if (typeof result.score !== 'number') throw new Error();
  521. if (!Array.isArray(result.issues)) result.issues = [];
  522. if (!Array.isArray(result.strengths)) result.strengths = [];
  523. } catch {
  524. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  525. }
  526. log.info({ action: 'profile_audit', accountKey, score: result.score, issues: result.issues.length, outcome: 'success' });
  527. return { success: true, ...result };
  528. } catch (err) {
  529. return reply.code(503).send({ error: 'Profile audit failed', detail: err.message });
  530. }
  531. });
  532. // ─── AI / Multi-provider ─────────────────────────────────────────────────────
  533. const DEFAULT_OLLAMA_ENDPOINT = process.env.OLLAMA_ENDPOINT || 'http://ollama:11434';
  534. const DEFAULT_OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2';
  535. const PROVIDER_MODELS = {
  536. openai: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-3.5-turbo'],
  537. groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768', 'gemma2-9b-it'],
  538. gemini: ['gemini-2.0-flash', 'gemini-1.5-flash', 'gemini-1.5-pro'],
  539. };
  540. const PROVIDER_BASE_URLS = {
  541. openai: 'https://api.openai.com/v1',
  542. groq: 'https://api.groq.com/openai/v1',
  543. };
  544. // Returns decrypted runtime config for the currently active provider
  545. async function getActiveProviderConfig() {
  546. const aiConfig = await getCredentials('ai_config');
  547. const provider = aiConfig?.provider || 'ollama';
  548. if (provider === 'openai' || provider === 'groq') {
  549. const doc = await getCredentials(`${provider}_config`);
  550. return {
  551. provider,
  552. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  553. model: doc?.model || PROVIDER_MODELS[provider][0],
  554. baseUrl: PROVIDER_BASE_URLS[provider],
  555. };
  556. }
  557. if (provider === 'gemini') {
  558. const doc = await getCredentials('gemini_config');
  559. return {
  560. provider,
  561. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  562. model: doc?.model || PROVIDER_MODELS.gemini[0],
  563. };
  564. }
  565. return {
  566. provider: 'ollama',
  567. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  568. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  569. visionModel: aiConfig?.visionModel || 'llava',
  570. };
  571. }
  572. function buildOpenAIMessages(prompt, system) {
  573. const messages = [];
  574. if (system) messages.push({ role: 'system', content: system });
  575. messages.push({ role: 'user', content: prompt });
  576. return messages;
  577. }
  578. // Gemini encodes system as a leading user/model conversation pair
  579. function buildGeminiContents(prompt, system) {
  580. const contents = [];
  581. if (system) {
  582. contents.push({ role: 'user', parts: [{ text: system }] });
  583. contents.push({ role: 'model', parts: [{ text: 'Understood.' }] });
  584. }
  585. contents.push({ role: 'user', parts: [{ text: prompt }] });
  586. return contents;
  587. }
  588. app.get('/ai/config', async () => {
  589. const config = await getCredentials('ai_config');
  590. return {
  591. provider: config?.provider || 'ollama',
  592. endpoint: config?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  593. model: config?.model || DEFAULT_OLLAMA_MODEL,
  594. visionModel: config?.visionModel || 'llava',
  595. enabled: config?.enabled ?? true,
  596. };
  597. });
  598. app.put('/ai/config', async (request, reply) => {
  599. const { provider = 'ollama', endpoint, model, visionModel = 'llava', enabled = true } = request.body || {};
  600. if (provider === 'ollama' && !endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  601. await setCredentials('ai_config', { provider, endpoint, model, visionModel, enabled });
  602. return { success: true };
  603. });
  604. // ─── Provider management routes ───────────────────────────────────────────────
  605. app.get('/ai/providers', async () => {
  606. const aiConfig = await getCredentials('ai_config');
  607. const active = aiConfig?.provider || 'ollama';
  608. const [openaiDoc, groqDoc, geminiDoc] = await Promise.all([
  609. getCredentials('openai_config'),
  610. getCredentials('groq_config'),
  611. getCredentials('gemini_config'),
  612. ]);
  613. return {
  614. active,
  615. providers: [
  616. {
  617. name: 'ollama',
  618. configured: true,
  619. active: active === 'ollama',
  620. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  621. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  622. visionModel: aiConfig?.visionModel || 'llava',
  623. },
  624. {
  625. name: 'openai',
  626. configured: !!openaiDoc?.apiKey,
  627. active: active === 'openai',
  628. model: openaiDoc?.model || PROVIDER_MODELS.openai[0],
  629. apiKeyHint: openaiDoc?.apiKey ? `sk-...${decryptToken(openaiDoc.apiKey).slice(-4)}` : null,
  630. },
  631. {
  632. name: 'groq',
  633. configured: !!groqDoc?.apiKey,
  634. active: active === 'groq',
  635. model: groqDoc?.model || PROVIDER_MODELS.groq[0],
  636. apiKeyHint: groqDoc?.apiKey ? `gsk_...${decryptToken(groqDoc.apiKey).slice(-4)}` : null,
  637. },
  638. {
  639. name: 'gemini',
  640. configured: !!geminiDoc?.apiKey,
  641. active: active === 'gemini',
  642. model: geminiDoc?.model || PROVIDER_MODELS.gemini[0],
  643. apiKeyHint: geminiDoc?.apiKey ? `AIza...${decryptToken(geminiDoc.apiKey).slice(-4)}` : null,
  644. },
  645. ],
  646. };
  647. });
  648. // PUT /ai/provider/:name — save credentials and optionally set as active
  649. // ollama body: { endpoint, model, visionModel, setActive? }
  650. // others body: { apiKey, model, setActive? }
  651. app.put('/ai/provider/:name', async (request, reply) => {
  652. const { name } = request.params;
  653. const { apiKey, model, endpoint, visionModel, setActive = false } = request.body || {};
  654. if (name === 'ollama') {
  655. if (!endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  656. const existing = await getCredentials('ai_config') || {};
  657. await setCredentials('ai_config', {
  658. ...existing,
  659. provider: setActive ? 'ollama' : (existing.provider || 'ollama'),
  660. endpoint,
  661. model: model || DEFAULT_OLLAMA_MODEL,
  662. visionModel: visionModel || 'llava',
  663. });
  664. } else if (['openai', 'groq', 'gemini'].includes(name)) {
  665. if (!apiKey) return reply.code(400).send({ error: 'apiKey is required' });
  666. await setCredentials(`${name}_config`, {
  667. apiKey: encryptToken(apiKey),
  668. model: model || PROVIDER_MODELS[name][0],
  669. });
  670. if (setActive) {
  671. const existing = await getCredentials('ai_config') || {};
  672. await setCredentials('ai_config', { ...existing, provider: name });
  673. }
  674. } else {
  675. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  676. }
  677. return { success: true };
  678. });
  679. // DELETE /ai/provider/:name — remove provider credentials; falls back to ollama if it was active
  680. app.delete('/ai/provider/:name', async (request, reply) => {
  681. const { name } = request.params;
  682. if (name === 'ollama') return reply.code(400).send({ error: 'Cannot remove Ollama provider' });
  683. if (!['openai', 'groq', 'gemini'].includes(name)) return reply.code(404).send({ error: `Unknown provider: ${name}` });
  684. const db = await getDb();
  685. await db.collection('platform_credentials').deleteOne({ _id: `${name}_config` });
  686. const aiConfig = await getCredentials('ai_config') || {};
  687. if (aiConfig.provider === name) {
  688. await setCredentials('ai_config', { ...aiConfig, provider: 'ollama' });
  689. }
  690. return { success: true };
  691. });
  692. // POST /ai/provider/:name/models — list models for a provider (test without saving key)
  693. app.post('/ai/provider/:name/models', async (request, reply) => {
  694. const { name } = request.params;
  695. const { apiKey: bodyApiKey, endpoint: bodyEndpoint } = request.body || {};
  696. if (name === 'ollama') {
  697. const aiConfig = await getCredentials('ai_config');
  698. const ep = bodyEndpoint || aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  699. try {
  700. const res = await axios.get(`${ep}/api/tags`, { timeout: 5000 });
  701. return { models: (res.data.models || []).map((m) => m.name) };
  702. } catch (err) {
  703. return reply.code(503).send({ error: 'Could not reach Ollama', detail: err.message });
  704. }
  705. }
  706. if (['openai', 'groq', 'gemini'].includes(name)) {
  707. return { models: PROVIDER_MODELS[name] };
  708. }
  709. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  710. });
  711. app.get('/ai/models', async (request, reply) => {
  712. const config = await getCredentials('ai_config');
  713. const provider = config?.provider || 'ollama';
  714. if (provider !== 'ollama') {
  715. return { models: PROVIDER_MODELS[provider] || [], provider };
  716. }
  717. const endpoint = request.query.endpoint || config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  718. try {
  719. const res = await axios.get(`${endpoint}/api/tags`, { timeout: 5000 });
  720. const models = (res.data.models || []).map((m) => m.name);
  721. return { models, endpoint };
  722. } catch (err) {
  723. return reply.code(503).send({ error: 'Could not reach Ollama — check the endpoint', detail: err.message });
  724. }
  725. });
  726. app.post('/ai/generate', async (request, reply) => {
  727. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, destinations } = request.body || {};
  728. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  729. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  730. const platformRules = buildPlatformRulesBlock(destinations);
  731. const system = rawSystem ? rawSystem + competitorSuffix + platformRules : ((competitorSuffix + platformRules) || undefined);
  732. const pconf = await getActiveProviderConfig();
  733. const model = reqModel || pconf.model;
  734. try {
  735. if (pconf.provider === 'ollama') {
  736. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  737. return { text: res.data.response, model, done: res.data.done };
  738. }
  739. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  740. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  741. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  742. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  743. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  744. return { text: res.data.choices[0]?.message?.content || '', model, done: true };
  745. }
  746. if (pconf.provider === 'gemini') {
  747. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  748. const res = await axios.post(
  749. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  750. { contents: buildGeminiContents(prompt, system) },
  751. { timeout: 90000 },
  752. );
  753. return { text: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model, done: true };
  754. }
  755. return reply.code(400).send({ error: `Unknown provider: ${pconf.provider}` });
  756. } catch (err) {
  757. const status = err.response?.status || 503;
  758. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  759. }
  760. });
  761. 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.';
  762. // Vision caption — supports ollama, openai, gemini (groq has no vision)
  763. app.post('/ai/caption', async (request, reply) => {
  764. const { imageUrl, model: reqModel } = request.body || {};
  765. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  766. const pconf = await getActiveProviderConfig();
  767. let imageBase64, imageMime;
  768. try {
  769. let imageBuffer;
  770. if (imageUrl.startsWith('/media/')) {
  771. const filename = path.basename(imageUrl);
  772. imageBuffer = fs.readFileSync(path.join(UPLOAD_DIR, filename));
  773. } else {
  774. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  775. imageBuffer = Buffer.from(imgRes.data);
  776. imageMime = imgRes.headers['content-type'] || 'image/jpeg';
  777. }
  778. imageBase64 = imageBuffer.toString('base64');
  779. if (!imageMime) imageMime = 'image/jpeg';
  780. } catch (err) {
  781. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  782. }
  783. try {
  784. const model = reqModel || pconf.visionModel || pconf.model;
  785. if (pconf.provider === 'ollama') {
  786. const res = await axios.post(`${pconf.endpoint}/api/generate`, {
  787. model, prompt: CAPTION_PROMPT, images: [imageBase64], stream: false,
  788. }, { timeout: 90000 });
  789. return { caption: res.data.response, model };
  790. }
  791. if (pconf.provider === 'openai') {
  792. if (!pconf.apiKey) return reply.code(503).send({ error: 'OpenAI API key not configured' });
  793. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  794. model: model || 'gpt-4o',
  795. messages: [{ role: 'user', content: [
  796. { type: 'text', text: CAPTION_PROMPT },
  797. { type: 'image_url', image_url: { url: `data:${imageMime};base64,${imageBase64}` } },
  798. ]}],
  799. stream: false,
  800. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  801. return { caption: res.data.choices[0]?.message?.content || '', model };
  802. }
  803. if (pconf.provider === 'gemini') {
  804. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  805. const geminiModel = model || 'gemini-1.5-flash';
  806. const res = await axios.post(
  807. `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${pconf.apiKey}`,
  808. { contents: [{ role: 'user', parts: [
  809. { text: CAPTION_PROMPT },
  810. { inlineData: { mimeType: imageMime, data: imageBase64 } },
  811. ]}]},
  812. { timeout: 90000 },
  813. );
  814. return { caption: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model: geminiModel };
  815. }
  816. return reply.code(400).send({ error: `Provider ${pconf.provider} does not support vision captions` });
  817. } catch (err) {
  818. const status = err.response?.status || 503;
  819. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  820. }
  821. });
  822. // SSE streaming endpoint — normalized data: { token, done } format for all providers
  823. app.post('/ai/stream', async (request, reply) => {
  824. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, destinations } = request.body || {};
  825. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  826. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  827. const platformRules = buildPlatformRulesBlock(destinations);
  828. const system = rawSystem ? rawSystem + competitorSuffix + platformRules : ((competitorSuffix + platformRules) || undefined);
  829. const pconf = await getActiveProviderConfig();
  830. const model = reqModel || pconf.model;
  831. reply.raw.setHeader('Content-Type', 'text/event-stream');
  832. reply.raw.setHeader('Cache-Control', 'no-cache');
  833. reply.raw.setHeader('X-Accel-Buffering', 'no');
  834. reply.raw.setHeader('Connection', 'keep-alive');
  835. reply.raw.flushHeaders();
  836. const writeToken = (token, done = false) => reply.raw.write(`data: ${JSON.stringify({ token, done })}\n\n`);
  837. const writeError = (msg) => { reply.raw.write(`data: ${JSON.stringify({ error: msg, done: true })}\n\n`); reply.raw.end(); };
  838. try {
  839. if (pconf.provider === 'ollama') {
  840. const ollamaRes = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  841. ollamaRes.data.on('data', (chunk) => {
  842. try {
  843. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  844. const data = JSON.parse(line);
  845. writeToken(data.response || '', !!data.done);
  846. }
  847. } catch (_) {}
  848. });
  849. ollamaRes.data.on('end', () => reply.raw.end());
  850. ollamaRes.data.on('error', (err) => writeError(err.message));
  851. return;
  852. }
  853. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  854. if (!pconf.apiKey) return writeError(`${pconf.provider} API key not configured`);
  855. const upstreamRes = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  856. model, messages: buildOpenAIMessages(prompt, system), stream: true,
  857. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, responseType: 'stream', timeout: 120000 });
  858. upstreamRes.data.on('data', (chunk) => {
  859. try {
  860. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  861. if (!line.startsWith('data: ')) continue;
  862. const payload = line.slice(6).trim();
  863. if (payload === '[DONE]') { writeToken('', true); return; }
  864. const data = JSON.parse(payload);
  865. const token = data.choices?.[0]?.delta?.content || '';
  866. if (token) writeToken(token);
  867. }
  868. } catch (_) {}
  869. });
  870. upstreamRes.data.on('end', () => reply.raw.end());
  871. upstreamRes.data.on('error', (err) => writeError(err.message));
  872. return;
  873. }
  874. if (pconf.provider === 'gemini') {
  875. if (!pconf.apiKey) return writeError('Gemini API key not configured');
  876. const geminiRes = await axios.post(
  877. `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${pconf.apiKey}`,
  878. { contents: buildGeminiContents(prompt, system) },
  879. { responseType: 'stream', timeout: 120000 },
  880. );
  881. geminiRes.data.on('data', (chunk) => {
  882. try {
  883. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  884. if (!line.startsWith('data: ')) continue;
  885. const data = JSON.parse(line.slice(6));
  886. const token = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  887. if (token) writeToken(token);
  888. }
  889. } catch (_) {}
  890. });
  891. geminiRes.data.on('end', () => { writeToken('', true); reply.raw.end(); });
  892. geminiRes.data.on('error', (err) => writeError(err.message));
  893. return;
  894. }
  895. writeError(`Unknown provider: ${pconf.provider}`);
  896. } catch (err) {
  897. writeError(err.message);
  898. }
  899. });
  900. // ─── Monthly Content Calendar ─────────────────────────────────────────────────
  901. // POST /ai/content-calendar — generate a monthly content plan with narrative brief + sample posts
  902. // Body: { accountKey?, platforms[], month? (YYYY-MM) }
  903. app.post('/ai/content-calendar', async (request, reply) => {
  904. const { accountKey, platforms = [], month } = request.body || {};
  905. if (!platforms.length) return reply.code(400).send({ error: 'Select at least one platform' });
  906. const db = await getDb();
  907. const calMonth = month || new Date().toISOString().slice(0, 7);
  908. const [year, mon] = calMonth.split('-');
  909. const monthName = new Date(`${calMonth}-01`).toLocaleString('en', { month: 'long', year: 'numeric' });
  910. // Load account profile for context
  911. const profileKey = accountKey || null;
  912. const profile = profileKey
  913. ? await db.collection('account_profiles').findOne({ _id: profileKey })
  914. : await db.collection('account_profiles').findOne({});
  915. const contextParts = ['You are a social media content strategist.'];
  916. if (profile) {
  917. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  918. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  919. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  920. if (profile.toneOfVoice) contextParts.push(`Tone of voice: ${profile.toneOfVoice}`);
  921. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  922. if (profile.keywords) contextParts.push(`Keywords: ${profile.keywords}`);
  923. }
  924. const brandContext = contextParts.join('\n');
  925. // Per-platform post count: 3 per platform (weeks 1–3)
  926. const platformList = platforms.slice(0, 5).join(', ');
  927. const postsPerPlatform = 3;
  928. const totalPosts = platforms.slice(0, 5).length * postsPerPlatform;
  929. const system = 'You are a social media content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  930. const prompt = `${brandContext}
  931. Create a content calendar for ${monthName} across these platforms: ${platformList}.
  932. Return a JSON object with exactly these fields:
  933. {
  934. "brief": {
  935. "theme": "The overarching monthly narrative theme in one sentence",
  936. "pillars": ["3-4 content pillars that anchor all posts this month"],
  937. "toneGuidance": "One sentence on tone and voice for this month",
  938. "platformNotes": {
  939. ${platforms.slice(0, 5).map((p) => `"${p}": "One sentence of platform-specific content strategy for ${p}"`).join(',\n ')}
  940. }
  941. },
  942. "posts": [
  943. ${platforms.slice(0, 5).flatMap((p, pi) =>
  944. [1, 2, 3].map((w, wi) => `{
  945. "platform": "${p}",
  946. "week": ${w},
  947. "content": "<full post text ready to publish, following platform-specific best practices>",
  948. "hashtags": ["<2-4 relevant hashtags>"],
  949. "postType": "<educational|promotional|engagement|storytelling>",
  950. "suggestedDay": "<best day of week to publish on ${p}>"
  951. }${pi < platforms.length - 1 || wi < 2 ? ',' : ''}`)).join('\n ')}
  952. ]
  953. }
  954. Important: Each post must follow platform conventions — LinkedIn hooks in first 2 lines, TikTok scripts with second-0 hook, Instagram assuming silent viewing, etc.
  955. Return ONLY the JSON object.`;
  956. try {
  957. const pconf = await getActiveProviderConfig();
  958. const model = pconf.model;
  959. let text = '';
  960. if (pconf.provider === 'ollama') {
  961. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  962. text = res.data.response;
  963. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  964. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  965. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  966. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  967. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  968. text = res.data.choices[0]?.message?.content || '';
  969. } else if (pconf.provider === 'gemini') {
  970. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  971. const res = await axios.post(
  972. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  973. { contents: buildGeminiContents(prompt, system) },
  974. { timeout: 180000 },
  975. );
  976. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  977. } else {
  978. return reply.code(400).send({ error: 'AI not configured' });
  979. }
  980. let calendar = null;
  981. try {
  982. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  983. calendar = JSON.parse(jsonStr);
  984. if (!calendar.brief || !Array.isArray(calendar.posts)) throw new Error();
  985. // Normalise
  986. if (!Array.isArray(calendar.brief.pillars)) calendar.brief.pillars = [];
  987. if (typeof calendar.brief.theme !== 'string') calendar.brief.theme = '';
  988. calendar.posts = calendar.posts.filter((p) => p && typeof p.content === 'string').slice(0, totalPosts);
  989. } catch {
  990. return reply.code(503).send({ error: 'AI returned invalid calendar format — try again' });
  991. }
  992. const doc = {
  993. accountKey: accountKey || null,
  994. month: calMonth,
  995. monthName,
  996. platforms,
  997. brief: calendar.brief,
  998. posts: calendar.posts,
  999. createdAt: new Date(),
  1000. };
  1001. const result = await db.collection('content_calendars').insertOne(doc);
  1002. log.info({ action: 'content_calendar', month: calMonth, platforms: platforms.join(','), posts: calendar.posts.length, outcome: 'success' });
  1003. return { success: true, calendarId: result.insertedId.toString(), ...doc };
  1004. } catch (err) {
  1005. return reply.code(503).send({ error: 'Calendar generation failed', detail: err.message });
  1006. }
  1007. });
  1008. // GET /ai/content-calendar/:id — retrieve a saved calendar
  1009. app.get('/ai/content-calendar/:id', async (request, reply) => {
  1010. let oid;
  1011. try { oid = new ObjectId(request.params.id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1012. const db = await getDb();
  1013. const cal = await db.collection('content_calendars').findOne({ _id: oid });
  1014. if (!cal) return reply.code(404).send({ error: 'Calendar not found' });
  1015. return { calendarId: cal._id.toString(), ...cal };
  1016. });
  1017. // GET /ai/content-calendars — list recent calendars
  1018. app.get('/ai/content-calendars', async (request, reply) => {
  1019. const db = await getDb();
  1020. const cals = await db.collection('content_calendars')
  1021. .find({}, { projection: { posts: 0 } })
  1022. .sort({ createdAt: -1 })
  1023. .limit(20)
  1024. .toArray();
  1025. return { calendars: cals.map((c) => ({ calendarId: c._id.toString(), month: c.month, monthName: c.monthName, platforms: c.platforms, brief: c.brief, createdAt: c.createdAt })) };
  1026. });
  1027. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  1028. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  1029. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  1030. app.post('/ai/bulk-draft', async (request, reply) => {
  1031. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  1032. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  1033. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  1034. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  1035. const db = await getDb();
  1036. const batchId = new ObjectId();
  1037. const now = new Date();
  1038. await db.collection('bulk_draft_batches').insertOne({
  1039. _id: batchId,
  1040. total: filteredTopics.length,
  1041. completed: 0,
  1042. failed: 0,
  1043. status: 'processing',
  1044. createdAt: now,
  1045. updatedAt: now,
  1046. });
  1047. const selectedDests = destinations.filter((d) => d.selected);
  1048. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  1049. const platformRules = buildPlatformRulesBlock(selectedDests);
  1050. 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}`;
  1051. // Fire-and-forget — process topics sequentially in the background
  1052. (async () => {
  1053. const pconf = await getActiveProviderConfig();
  1054. const model = reqModel || pconf.model;
  1055. for (const topic of filteredTopics) {
  1056. try {
  1057. const prompt = `Write a social media post about: ${topic}`;
  1058. let content = '';
  1059. if (pconf.provider === 'ollama') {
  1060. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  1061. content = res.data.response || '';
  1062. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1063. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  1064. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1065. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1066. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  1067. content = res.data.choices[0]?.message?.content || '';
  1068. } else if (pconf.provider === 'gemini') {
  1069. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  1070. const res = await axios.post(
  1071. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1072. { contents: buildGeminiContents(prompt, system) },
  1073. { timeout: 90000 },
  1074. );
  1075. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1076. }
  1077. if (content.trim()) {
  1078. const draftNow = new Date();
  1079. await db.collection('drafts').insertOne({
  1080. content: content.trim(),
  1081. mediaUrl: '',
  1082. scheduledAt: '',
  1083. destinations: selectedDests,
  1084. batchId: batchId.toString(),
  1085. topic,
  1086. createdAt: draftNow,
  1087. updatedAt: draftNow,
  1088. });
  1089. }
  1090. await db.collection('bulk_draft_batches').updateOne(
  1091. { _id: batchId },
  1092. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  1093. );
  1094. } catch (err) {
  1095. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  1096. await db.collection('bulk_draft_batches').updateOne(
  1097. { _id: batchId },
  1098. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  1099. );
  1100. }
  1101. }
  1102. await db.collection('bulk_draft_batches').updateOne(
  1103. { _id: batchId },
  1104. { $set: { status: 'done', updatedAt: new Date() } },
  1105. );
  1106. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  1107. })().catch((err) => {
  1108. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  1109. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  1110. { _id: batchId },
  1111. { $set: { status: 'failed', updatedAt: new Date() } },
  1112. )).catch(() => {});
  1113. });
  1114. return reply.code(202).send({ batchId: batchId.toString() });
  1115. });
  1116. // GET /ai/bulk-draft/:batchId — poll batch progress
  1117. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  1118. const { batchId } = request.params;
  1119. let oid;
  1120. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  1121. const db = await getDb();
  1122. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid });
  1123. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  1124. return {
  1125. batchId: batch._id.toString(),
  1126. total: batch.total,
  1127. completed: batch.completed,
  1128. failed: batch.failed,
  1129. status: batch.status,
  1130. processed: batch.completed + batch.failed,
  1131. };
  1132. });
  1133. // ─── Platform service URLs ────────────────────────────────────────────────────
  1134. const PLATFORM_SERVICES = {
  1135. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  1136. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  1137. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  1138. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  1139. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  1140. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  1141. };
  1142. // Direct multi-platform post endpoint.
  1143. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  1144. app.post('/post', async (request, reply) => {
  1145. const { content, destinations = [], firstComment } = request.body || {};
  1146. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  1147. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  1148. const results = await Promise.allSettled(
  1149. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  1150. const serviceUrl = PLATFORM_SERVICES[platform];
  1151. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  1152. const res = await axios.post(
  1153. `${serviceUrl}/post`,
  1154. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  1155. { timeout: 30000 }
  1156. );
  1157. return { platform, accountId, ...res.data };
  1158. })
  1159. );
  1160. const output = results.map((r, i) =>
  1161. r.status === 'fulfilled'
  1162. ? r.value
  1163. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  1164. );
  1165. const anyFailed = output.some((r) => !r.success);
  1166. const anySucceeded = output.some((r) => r.success);
  1167. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  1168. // Record the post for analytics
  1169. try {
  1170. const db = await getDb();
  1171. await db.collection('posts').insertOne({
  1172. _id: crypto.randomUUID(),
  1173. type: 'immediate',
  1174. content,
  1175. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  1176. destinations,
  1177. platformResults: Object.fromEntries(
  1178. output.map((r) => [
  1179. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  1180. { success: r.success, ...(r.error && { error: r.error }) },
  1181. ])
  1182. ),
  1183. status: postStatus,
  1184. publishedAt: new Date(),
  1185. createdAt: new Date(),
  1186. });
  1187. } catch (err) {
  1188. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  1189. }
  1190. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  1191. });
  1192. // ─── Legacy post route ────────────────────────────────────────────────────────
  1193. let rabbitMQProducer = new RabbitMQProducer();
  1194. app.post('/', async (request, reply) => {
  1195. try {
  1196. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  1197. reply.send({ status: 'ok' });
  1198. } catch (error) {
  1199. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  1200. reply.status(500).send({ error: 'Internal Server Error' });
  1201. }
  1202. });
  1203. // ─── Meta App Credentials ────────────────────────────────────────────────────
  1204. // Save Facebook App ID + Secret (entered by user in Settings UI)
  1205. app.post('/credentials/meta-app', async (request, reply) => {
  1206. const { appId, appSecret } = request.body || {};
  1207. if (!appId || !appSecret) {
  1208. return reply.code(400).send({ error: 'appId and appSecret are required' });
  1209. }
  1210. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  1211. return { success: true };
  1212. });
  1213. // Get Meta App config (secret is masked for UI display)
  1214. app.get('/credentials/meta-app', async () => {
  1215. const cred = await getCredentials('meta_app');
  1216. if (!cred) return { configured: false };
  1217. const plainSecret = decryptToken(cred.appSecret) || '';
  1218. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  1219. });
  1220. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  1221. // Return the Facebook OAuth URL to redirect the user to
  1222. app.get('/auth/meta/init', async (request, reply) => {
  1223. const cred = await getCredentials('meta_app');
  1224. if (!cred?.appId) {
  1225. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  1226. }
  1227. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1228. const scopes = [
  1229. 'pages_manage_posts',
  1230. 'pages_read_engagement',
  1231. 'instagram_basic',
  1232. 'instagram_content_publish',
  1233. 'instagram_manage_insights',
  1234. ].join(',');
  1235. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  1236. return { url };
  1237. });
  1238. // OAuth callback — Facebook redirects here after user authorises
  1239. app.get('/auth/meta/callback', async (request, reply) => {
  1240. const { code, error: oauthError } = request.query;
  1241. if (oauthError) {
  1242. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  1243. }
  1244. if (!code) {
  1245. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  1246. }
  1247. try {
  1248. const appCred = await getCredentials('meta_app');
  1249. if (!appCred?.appId) throw new Error('App credentials not configured');
  1250. const appSecret = decryptToken(appCred.appSecret);
  1251. if (!appSecret) throw new Error('Failed to decrypt app secret');
  1252. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1253. // Exchange code for short-lived token
  1254. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1255. params: {
  1256. client_id: appCred.appId,
  1257. client_secret: appSecret,
  1258. redirect_uri: redirectUri,
  1259. code,
  1260. },
  1261. });
  1262. // Upgrade to long-lived user token (~60 days)
  1263. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1264. params: {
  1265. grant_type: 'fb_exchange_token',
  1266. client_id: appCred.appId,
  1267. client_secret: appSecret,
  1268. fb_exchange_token: shortRes.data.access_token,
  1269. },
  1270. });
  1271. const userToken = longRes.data.access_token;
  1272. // Fetch all managed Facebook Pages
  1273. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  1274. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  1275. });
  1276. const pages = [];
  1277. const igAccounts = [];
  1278. for (const page of pagesRes.data.data || []) {
  1279. pages.push({
  1280. id: page.id,
  1281. name: page.name,
  1282. accessToken: encryptToken(page.access_token),
  1283. picture: page.picture?.data?.url || null,
  1284. selected: false,
  1285. });
  1286. // Check for linked Instagram Business Account
  1287. try {
  1288. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  1289. params: {
  1290. fields: 'instagram_business_account',
  1291. access_token: page.access_token,
  1292. },
  1293. });
  1294. if (igRes.data.instagram_business_account?.id) {
  1295. const igId = igRes.data.instagram_business_account.id;
  1296. // Fetch IG account details
  1297. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1298. params: {
  1299. fields: 'id,username,name,profile_picture_url',
  1300. access_token: userToken,
  1301. },
  1302. });
  1303. igAccounts.push({
  1304. id: igId,
  1305. username: igProfile.data.username || igProfile.data.name,
  1306. name: igProfile.data.name,
  1307. avatar: igProfile.data.profile_picture_url || null,
  1308. accessToken: encryptToken(userToken),
  1309. pageId: page.id,
  1310. selected: false,
  1311. });
  1312. }
  1313. } catch (_) {
  1314. // Page has no linked Instagram account — skip
  1315. }
  1316. }
  1317. // Store discovery results for the UI to pick from
  1318. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1319. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1320. } catch (err) {
  1321. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1322. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1323. }
  1324. });
  1325. // Return pending discovery results so the UI can render the page picker
  1326. app.get('/auth/meta/discovered', async () => {
  1327. const discovery = await getCredentials('meta_discovery');
  1328. if (!discovery) return { pages: [], igAccounts: [] };
  1329. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1330. });
  1331. // User has chosen which pages/accounts to connect
  1332. app.post('/auth/meta/save', async (request, reply) => {
  1333. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1334. const discovery = await getCredentials('meta_discovery');
  1335. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1336. const fbPages = (discovery.pages || []).map((p) => ({
  1337. ...p,
  1338. selected: selectedPageIds.includes(p.id),
  1339. }));
  1340. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1341. ...a,
  1342. selected: selectedIgAccountIds.includes(a.id),
  1343. }));
  1344. await setCredentials('facebook', { pages: fbPages });
  1345. await setCredentials('instagram', { accounts: igAccounts });
  1346. await deleteCredentials('meta_discovery');
  1347. _tokenExpiryCache = null; // invalidate cache after reconnect
  1348. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1349. });
  1350. // Disconnect all Meta platforms
  1351. app.delete('/credentials/meta', async () => {
  1352. await deleteCredentials('facebook');
  1353. await deleteCredentials('instagram');
  1354. await deleteCredentials('meta_discovery');
  1355. return { success: true };
  1356. });
  1357. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1358. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1359. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1360. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1361. app.post('/credentials/pinterest-app', async (request, reply) => {
  1362. const { clientId, clientSecret } = request.body || {};
  1363. if (!clientId || !clientSecret) {
  1364. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1365. }
  1366. await setCredentials('pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1367. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1368. return { success: true };
  1369. });
  1370. app.get('/credentials/pinterest-app', async () => {
  1371. const cred = await getCredentials('pinterest_app');
  1372. if (!cred) return { configured: false };
  1373. const plain = decryptToken(cred.clientSecret) || '';
  1374. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1375. });
  1376. app.get('/auth/pinterest/init', async (request, reply) => {
  1377. const cred = await getCredentials('pinterest_app');
  1378. if (!cred?.clientId) {
  1379. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1380. }
  1381. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1382. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1383. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1384. return { url };
  1385. });
  1386. app.get('/auth/pinterest/callback', async (request, reply) => {
  1387. const { code, error: oauthError } = request.query;
  1388. if (oauthError) {
  1389. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1390. }
  1391. if (!code) {
  1392. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1393. }
  1394. try {
  1395. const appCred = await getCredentials('pinterest_app');
  1396. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1397. const clientSecret = decryptToken(appCred.clientSecret);
  1398. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1399. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1400. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1401. const tokenRes = await axios.post(
  1402. PINTEREST_TOKEN_URL,
  1403. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1404. {
  1405. headers: {
  1406. Authorization: `Basic ${basicAuth}`,
  1407. 'Content-Type': 'application/x-www-form-urlencoded',
  1408. },
  1409. timeout: 15000,
  1410. }
  1411. );
  1412. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1413. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1414. const [userRes, boardsRes] = await Promise.all([
  1415. axios.get(`${PINTEREST_API}/user_account`, {
  1416. headers: { Authorization: `Bearer ${access_token}` },
  1417. timeout: 10000,
  1418. }),
  1419. axios.get(`${PINTEREST_API}/boards`, {
  1420. headers: { Authorization: `Bearer ${access_token}` },
  1421. params: { page_size: 100 },
  1422. timeout: 15000,
  1423. }),
  1424. ]);
  1425. const boards = (boardsRes.data.items || []).map((b) => ({
  1426. id: b.id,
  1427. name: b.name,
  1428. privacy: b.privacy,
  1429. selected: false,
  1430. }));
  1431. await setCredentials('pinterest', {
  1432. userId: userRes.data.username,
  1433. username: userRes.data.username,
  1434. displayName: userRes.data.business_name || userRes.data.username,
  1435. avatar: userRes.data.profile_image,
  1436. accessToken: encryptToken(access_token),
  1437. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1438. tokenExpiry,
  1439. boards,
  1440. });
  1441. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1442. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1443. } catch (err) {
  1444. const msg = err.response?.data?.message || err.message;
  1445. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1446. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1447. }
  1448. });
  1449. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1450. const { selectedBoardIds = [] } = request.body || {};
  1451. const cred = await getCredentials('pinterest');
  1452. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1453. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1454. await setCredentials('pinterest', { ...cred, boards });
  1455. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1456. return { success: true, selected: boards.filter((b) => b.selected).length };
  1457. });
  1458. app.delete('/credentials/pinterest', async () => {
  1459. await deleteCredentials('pinterest');
  1460. return { success: true };
  1461. });
  1462. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1463. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1464. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1465. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1466. app.post('/credentials/tiktok-app', async (request, reply) => {
  1467. const { clientKey, clientSecret } = request.body || {};
  1468. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1469. await setCredentials('tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1470. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1471. return { success: true };
  1472. });
  1473. app.get('/credentials/tiktok-app', async () => {
  1474. const cred = await getCredentials('tiktok_app');
  1475. if (!cred?.clientKey) return { configured: false };
  1476. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1477. });
  1478. app.get('/auth/tiktok/init', async (request, reply) => {
  1479. const cred = await getCredentials('tiktok_app');
  1480. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1481. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1482. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1483. const state = crypto.randomBytes(16).toString('hex');
  1484. // Persist PKCE verifier for the callback
  1485. const db = await getDb();
  1486. await db.collection('platform_credentials').updateOne(
  1487. { _id: 'tiktok_pkce' },
  1488. { $set: { codeVerifier, state, createdAt: new Date() } },
  1489. { upsert: true }
  1490. );
  1491. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1492. const scopes = 'user.info.basic,video.list,video.publish';
  1493. const params = new URLSearchParams({
  1494. client_key: cred.clientKey,
  1495. scope: scopes,
  1496. response_type: 'code',
  1497. redirect_uri: redirectUri,
  1498. state,
  1499. code_challenge: codeChallenge,
  1500. code_challenge_method: 'S256',
  1501. });
  1502. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1503. });
  1504. app.get('/auth/tiktok/callback', async (request, reply) => {
  1505. const { code, state, error: oauthError, error_description } = request.query;
  1506. if (oauthError) {
  1507. const msg = error_description || oauthError;
  1508. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1509. }
  1510. if (!code) {
  1511. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1512. }
  1513. try {
  1514. const db = await getDb();
  1515. const pkce = await db.collection('platform_credentials').findOne({ _id: 'tiktok_pkce' });
  1516. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1517. if (state && pkce.state && state !== pkce.state) throw new Error('OAuth state mismatch');
  1518. const appCred = await getCredentials('tiktok_app');
  1519. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1520. const clientSecret = decryptToken(appCred.clientSecret);
  1521. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1522. const tokenRes = await axios.post(
  1523. TIKTOK_TOKEN_URL,
  1524. new URLSearchParams({
  1525. client_key: appCred.clientKey,
  1526. client_secret: clientSecret,
  1527. code,
  1528. grant_type: 'authorization_code',
  1529. redirect_uri: redirectUri,
  1530. code_verifier: pkce.codeVerifier,
  1531. }).toString(),
  1532. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1533. );
  1534. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1535. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1536. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1537. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1538. headers: { Authorization: `Bearer ${access_token}` },
  1539. params: { fields: 'open_id,display_name,avatar_url,username' },
  1540. timeout: 10000,
  1541. });
  1542. const user = userRes.data?.data?.user || {};
  1543. await setCredentials('tiktok', {
  1544. openId: open_id || user.open_id,
  1545. username: user.username || user.display_name,
  1546. displayName: user.display_name,
  1547. avatar: user.avatar_url || null,
  1548. accessToken: encryptToken(access_token),
  1549. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1550. tokenExpiry,
  1551. refreshExpiry,
  1552. });
  1553. // Clean up PKCE temp state
  1554. await db.collection('platform_credentials').deleteOne({ _id: 'tiktok_pkce' });
  1555. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1556. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1557. } catch (err) {
  1558. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1559. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1560. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1561. }
  1562. });
  1563. app.delete('/credentials/tiktok', async () => {
  1564. await deleteCredentials('tiktok');
  1565. return { success: true };
  1566. });
  1567. // ─── Credential Status ────────────────────────────────────────────────────────
  1568. // Aggregate connection status for all DB-managed platforms
  1569. app.get('/credentials', async () => {
  1570. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1571. getCredentials('meta_app'),
  1572. getCredentials('facebook'),
  1573. getCredentials('instagram'),
  1574. getCredentials('pinterest'),
  1575. getCredentials('tiktok'),
  1576. ]);
  1577. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1578. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1579. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1580. return {
  1581. metaApp: { configured: !!(metaApp?.appId) },
  1582. facebook: {
  1583. connected: fbPages.length > 0,
  1584. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1585. },
  1586. instagram: {
  1587. connected: igAccounts.length > 0,
  1588. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1589. },
  1590. pinterest: {
  1591. connected: pinterestBoards.length > 0,
  1592. username: pinterest?.username || null,
  1593. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1594. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1595. },
  1596. tiktok: {
  1597. connected: !!(tiktok?.accessToken),
  1598. username: tiktok?.username || null,
  1599. displayName: tiktok?.displayName || null,
  1600. avatar: tiktok?.avatar || null,
  1601. },
  1602. };
  1603. });
  1604. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1605. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1606. const INDUSTRY_DEFAULTS = {
  1607. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1608. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1609. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1610. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1611. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1612. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1613. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1614. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1615. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1616. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  1617. };
  1618. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  1619. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  1620. // at least `afterMs` milliseconds in the future.
  1621. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  1622. const candidate = new Date(afterMs);
  1623. candidate.setUTCHours(hourUTC, 0, 0, 0);
  1624. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  1625. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  1626. candidate.setUTCDate(candidate.getUTCDate() + 7);
  1627. } else {
  1628. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  1629. }
  1630. return candidate;
  1631. }
  1632. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  1633. app.get('/schedule/suggestions', async (request, reply) => {
  1634. const { platform, accountId } = request.query;
  1635. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  1636. const db = await getDb();
  1637. const query = { platform, ...(accountId && { accountId }) };
  1638. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  1639. let slots;
  1640. let source;
  1641. if (dataPoints >= 10) {
  1642. const agg = await db.collection('post_metrics').aggregate([
  1643. { $match: query },
  1644. { $group: {
  1645. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1646. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1647. count: { $sum: 1 },
  1648. }},
  1649. { $sort: { avgEngagement: -1 } },
  1650. { $limit: 5 },
  1651. ]).toArray();
  1652. slots = agg.map((r) => [r._id.day, r._id.hour]);
  1653. source = 'history';
  1654. } else {
  1655. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  1656. source = 'default';
  1657. }
  1658. // 30-minute lead time so the user has time to finish writing
  1659. const afterMs = Date.now() + 30 * 60 * 1000;
  1660. const suggestions = slots
  1661. .map(([day, hour]) => {
  1662. const dt = nextOccurrence(day, hour, afterMs);
  1663. const h12 = hour % 12 || 12;
  1664. const ampm = hour < 12 ? 'am' : 'pm';
  1665. return {
  1666. utc: dt.toISOString(),
  1667. dayOfWeek: day,
  1668. hour,
  1669. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  1670. };
  1671. })
  1672. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  1673. .slice(0, 4);
  1674. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  1675. return { source, suggestions };
  1676. });
  1677. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  1678. async function crawlFacebookMetrics(db) {
  1679. const fb = await getCredentials('facebook');
  1680. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  1681. if (!pages.length) return { count: 0 };
  1682. let count = 0;
  1683. for (const page of pages) {
  1684. const token = decryptToken(page.accessToken);
  1685. if (!token) continue;
  1686. try {
  1687. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  1688. params: {
  1689. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  1690. limit: 100,
  1691. access_token: token,
  1692. },
  1693. timeout: 30000,
  1694. });
  1695. for (const post of res.data.data || []) {
  1696. const likes = post.reactions?.summary?.total_count || 0;
  1697. const comments = post.comments?.summary?.total_count || 0;
  1698. const shares = post.shares?.count || 0;
  1699. const publishedAt = new Date(post.created_time);
  1700. await db.collection('post_metrics').updateOne(
  1701. { platform: 'facebook', postId: post.id },
  1702. {
  1703. $set: {
  1704. platform: 'facebook',
  1705. accountId: page.id,
  1706. accountName: page.name,
  1707. postId: post.id,
  1708. content: post.message || null,
  1709. publishedAt,
  1710. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  1711. hourOfDay: publishedAt.getUTCHours(),
  1712. dayOfWeek: publishedAt.getUTCDay(),
  1713. fetchedAt: new Date(),
  1714. },
  1715. },
  1716. { upsert: true }
  1717. );
  1718. count++;
  1719. }
  1720. } catch (err) {
  1721. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  1722. }
  1723. }
  1724. return { count };
  1725. }
  1726. async function crawlInstagramMetrics(db) {
  1727. const ig = await getCredentials('instagram');
  1728. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  1729. if (!accounts.length) return { count: 0 };
  1730. let count = 0;
  1731. for (const account of accounts) {
  1732. const token = decryptToken(account.accessToken);
  1733. if (!token) continue;
  1734. try {
  1735. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  1736. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  1737. timeout: 30000,
  1738. });
  1739. for (const media of mediaRes.data.data || []) {
  1740. const likes = media.like_count || 0;
  1741. const comments = media.comments_count || 0;
  1742. const publishedAt = new Date(media.timestamp);
  1743. let views = 0;
  1744. let saves = 0;
  1745. try {
  1746. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  1747. params: { metric: 'reach,saved', access_token: token },
  1748. timeout: 10000,
  1749. });
  1750. for (const ins of insRes.data.data || []) {
  1751. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  1752. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  1753. }
  1754. } catch (_) {}
  1755. await db.collection('post_metrics').updateOne(
  1756. { platform: 'instagram', postId: media.id },
  1757. {
  1758. $set: {
  1759. platform: 'instagram',
  1760. accountId: account.id,
  1761. accountName: account.username,
  1762. postId: media.id,
  1763. content: media.caption || null,
  1764. publishedAt,
  1765. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  1766. hourOfDay: publishedAt.getUTCHours(),
  1767. dayOfWeek: publishedAt.getUTCDay(),
  1768. fetchedAt: new Date(),
  1769. },
  1770. },
  1771. { upsert: true }
  1772. );
  1773. count++;
  1774. }
  1775. } catch (err) {
  1776. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  1777. }
  1778. }
  1779. return { count };
  1780. }
  1781. app.post('/analytics/crawl', async () => {
  1782. const db = await getDb();
  1783. const results = {};
  1784. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  1785. try {
  1786. results[platform] = await crawler(db);
  1787. } catch (err) {
  1788. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  1789. results[platform] = { count: 0, error: err.message };
  1790. }
  1791. }
  1792. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  1793. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  1794. return { success: true, total, byPlatform: results };
  1795. });
  1796. app.get('/analytics/insights', async (request) => {
  1797. const filter = parseAccountFilter(request.query.account);
  1798. const metricsMatch = filter
  1799. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1800. : {};
  1801. const db = await getDb();
  1802. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  1803. if (total === 0) return { empty: true };
  1804. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  1805. db.collection('post_metrics').aggregate([
  1806. { $match: metricsMatch },
  1807. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1808. { $sort: { _id: 1 } },
  1809. ]).toArray(),
  1810. db.collection('post_metrics').aggregate([
  1811. { $match: metricsMatch },
  1812. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1813. { $sort: { _id: 1 } },
  1814. ]).toArray(),
  1815. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  1816. db.collection('post_metrics').aggregate([
  1817. { $match: metricsMatch },
  1818. { $group: {
  1819. _id: '$platform',
  1820. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1821. avgLikes: { $avg: '$metrics.likes' },
  1822. avgComments: { $avg: '$metrics.comments' },
  1823. avgShares: { $avg: '$metrics.shares' },
  1824. totalPosts: { $sum: 1 },
  1825. }},
  1826. { $sort: { avgEngagement: -1 } },
  1827. ]).toArray(),
  1828. db.collection('post_metrics').aggregate([
  1829. { $match: metricsMatch },
  1830. { $group: {
  1831. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1832. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1833. count: { $sum: 1 },
  1834. }},
  1835. ]).toArray(),
  1836. ]);
  1837. const byHour = Array.from({ length: 24 }, (_, h) => {
  1838. const e = byHourRaw.find((r) => r._id === h);
  1839. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1840. });
  1841. const byDay = Array.from({ length: 7 }, (_, d) => {
  1842. const e = byDayRaw.find((r) => r._id === d);
  1843. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1844. });
  1845. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  1846. const day = Math.floor(i / 24);
  1847. const hour = i % 24;
  1848. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  1849. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1850. });
  1851. return {
  1852. empty: false,
  1853. total,
  1854. byHour,
  1855. byDay,
  1856. heatmap,
  1857. topPosts: topPosts.map((p) => ({
  1858. platform: p.platform, accountName: p.accountName, postId: p.postId,
  1859. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  1860. })),
  1861. platformComparison: platformComparison.map((p) => ({
  1862. platform: p._id,
  1863. avgEngagement: Math.round(p.avgEngagement),
  1864. avgLikes: Math.round(p.avgLikes),
  1865. avgComments: Math.round(p.avgComments),
  1866. avgShares: Math.round(p.avgShares),
  1867. totalPosts: p.totalPosts,
  1868. })),
  1869. };
  1870. });
  1871. // ─── Analytics ────────────────────────────────────────────────────────────────
  1872. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  1873. function parseAccountFilter(account) {
  1874. if (!account) return null;
  1875. const idx = account.indexOf(':');
  1876. if (idx === -1) return { platform: account };
  1877. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  1878. }
  1879. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  1880. function sjFilter(filter) {
  1881. if (!filter) return {};
  1882. return {
  1883. 'destinations.platform': filter.platform,
  1884. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1885. };
  1886. }
  1887. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  1888. function ipFilter(filter) {
  1889. if (!filter) return {};
  1890. return {
  1891. 'destinations.platform': filter.platform,
  1892. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1893. };
  1894. }
  1895. app.get('/analytics/summary', async (request) => {
  1896. const filter = parseAccountFilter(request.query.account);
  1897. const db = await getDb();
  1898. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1899. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1900. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  1901. // account filter after $unwind so a job targeting multiple platforms only
  1902. // counts the platform(s) that match the filter.
  1903. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  1904. const [
  1905. schedCompleted, schedFailed,
  1906. immPublished, immFailed,
  1907. recentSched, recentImm,
  1908. schedPlatformRaw, immPlatformRaw,
  1909. schedDayRaw, immDayRaw,
  1910. ] = await Promise.all([
  1911. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  1912. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  1913. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  1914. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  1915. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  1916. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  1917. // Platform breakdown from scheduled_jobs destinations
  1918. db.collection('scheduled_jobs').aggregate([
  1919. { $match: { status: 'completed', ...sjFilter(filter) } },
  1920. { $unwind: '$destinations' },
  1921. ...unwindFilter,
  1922. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  1923. { $sort: { count: -1 } },
  1924. ]).toArray(),
  1925. // Platform breakdown from immediate posts platformResults
  1926. db.collection('posts').aggregate([
  1927. { $match: { type: 'immediate', ...ipFilter(filter) } },
  1928. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  1929. { $unwind: '$results' },
  1930. { $match: { 'results.v.success': true } },
  1931. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  1932. { $group: { _id: '$platform', count: { $sum: 1 } } },
  1933. ]).toArray(),
  1934. // Activity by day from scheduled_jobs (using completedAt)
  1935. db.collection('scheduled_jobs').aggregate([
  1936. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  1937. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  1938. { $sort: { _id: 1 } },
  1939. ]).toArray(),
  1940. // Activity by day from immediate posts
  1941. db.collection('posts').aggregate([
  1942. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  1943. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  1944. { $sort: { _id: 1 } },
  1945. ]).toArray(),
  1946. ]);
  1947. const dayMap = {};
  1948. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1949. dayMap[_id] = (dayMap[_id] || 0) + count;
  1950. }
  1951. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1952. const platformMap = {};
  1953. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1954. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1955. }
  1956. const published = schedCompleted + immPublished;
  1957. const failed = schedFailed + immFailed;
  1958. const total = published + failed;
  1959. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1960. const recentCount = recentSched + recentImm;
  1961. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1962. });
  1963. app.get('/analytics/posts', async (request) => {
  1964. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1965. const skip = parseInt(request.query.skip || '0', 10);
  1966. const filter = parseAccountFilter(request.query.account);
  1967. const db = await getDb();
  1968. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1969. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1970. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1971. db.collection('scheduled_jobs')
  1972. .find(sjMatch)
  1973. .sort({ completedAt: -1, scheduledAt: -1 })
  1974. .skip(skip)
  1975. .limit(limit)
  1976. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1977. .toArray(),
  1978. db.collection('posts')
  1979. .find(ipMatch)
  1980. .sort({ publishedAt: -1 })
  1981. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1982. .toArray(),
  1983. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1984. db.collection('posts').countDocuments(ipMatch),
  1985. ]);
  1986. const normalised = [
  1987. ...scheduledJobs.map((j) => ({
  1988. _id: String(j._id),
  1989. type: 'scheduled',
  1990. content: j.content || null,
  1991. destinations: j.destinations || [],
  1992. platformResults: null,
  1993. status: j.status === 'completed' ? 'published' : 'failed',
  1994. publishedAt: j.completedAt || j.scheduledAt,
  1995. })),
  1996. ...immediatePosts.map((p) => ({
  1997. _id: String(p._id),
  1998. type: 'immediate',
  1999. content: p.content || null,
  2000. destinations: p.destinations || [],
  2001. platformResults: p.platformResults || null,
  2002. status: p.status,
  2003. publishedAt: p.publishedAt,
  2004. })),
  2005. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  2006. .slice(0, limit);
  2007. return { posts: normalised, total: schedTotal + immTotal };
  2008. });
  2009. // ─── Analytics Export ─────────────────────────────────────────────────────────
  2010. // GET /analytics/export?format=csv&account=&month=YYYY-MM
  2011. // Exports scheduled jobs + immediate posts as a downloadable CSV.
  2012. app.get('/analytics/export', async (request, reply) => {
  2013. const { format = 'csv', account, month } = request.query;
  2014. const filter = parseAccountFilter(account);
  2015. const db = await getDb();
  2016. let dateFilter = {};
  2017. if (month) {
  2018. const start = new Date(`${month}-01T00:00:00.000Z`);
  2019. const end = new Date(start);
  2020. end.setMonth(end.getMonth() + 1);
  2021. dateFilter = { $gte: start, $lt: end };
  2022. }
  2023. const sjMatch = {
  2024. status: { $in: ['completed', 'failed'] },
  2025. ...sjFilter(filter),
  2026. ...(month ? { completedAt: dateFilter } : {}),
  2027. };
  2028. const ipMatch = {
  2029. type: 'immediate',
  2030. ...ipFilter(filter),
  2031. ...(month ? { publishedAt: dateFilter } : {}),
  2032. };
  2033. const [scheduledJobs, immediatePosts] = await Promise.all([
  2034. db.collection('scheduled_jobs')
  2035. .find(sjMatch)
  2036. .sort({ completedAt: -1 })
  2037. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  2038. .toArray(),
  2039. db.collection('posts')
  2040. .find(ipMatch)
  2041. .sort({ publishedAt: -1 })
  2042. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  2043. .toArray(),
  2044. ]);
  2045. const rows = [
  2046. ...scheduledJobs.map((j) => ({
  2047. type: 'scheduled',
  2048. date: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(0, 10) ?? '',
  2049. time: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(11, 16) ?? '',
  2050. platforms: (j.destinations || []).map((d) => d.platform).join(' | '),
  2051. status: j.status === 'completed' ? 'published' : 'failed',
  2052. content: j.content || '',
  2053. })),
  2054. ...immediatePosts.map((p) => ({
  2055. type: 'immediate',
  2056. date: p.publishedAt?.toISOString()?.slice(0, 10) ?? '',
  2057. time: p.publishedAt?.toISOString()?.slice(11, 16) ?? '',
  2058. platforms: (p.destinations || []).map((d) => d.platform).join(' | '),
  2059. status: p.status,
  2060. content: p.content || '',
  2061. })),
  2062. ].sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time));
  2063. const escape = (v) => `"${String(v).replace(/"/g, '""')}"`;
  2064. const header = ['Date', 'Time (UTC)', 'Type', 'Platforms', 'Status', 'Content'];
  2065. const lines = [
  2066. header.join(','),
  2067. ...rows.map((r) => [r.date, r.time, r.type, r.platforms, r.status, escape(r.content)].join(',')),
  2068. ];
  2069. const filename = `posts-${month || 'all'}.csv`;
  2070. reply.header('Content-Type', 'text/csv; charset=utf-8');
  2071. reply.header('Content-Disposition', `attachment; filename="${filename}"`);
  2072. return reply.send('' + lines.join('\r\n'));
  2073. });
  2074. // ─── Brand / Account Audit ────────────────────────────────────────────────────
  2075. app.post('/analytics/audit', async (request, reply) => {
  2076. const filter = parseAccountFilter(request.query.account);
  2077. const db = await getDb();
  2078. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  2079. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  2080. const recentPosts = await db.collection('posts').find({
  2081. publishedAt: { $gte: thirtyDaysAgo },
  2082. ...ipFilter(filter),
  2083. }, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } }).toArray();
  2084. if (recentPosts.length < 3) {
  2085. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 3 posts first.' });
  2086. }
  2087. // Posting frequency
  2088. const postsLast30 = recentPosts.length;
  2089. const postsLast7 = recentPosts.filter((p) => new Date(p.publishedAt) >= sevenDaysAgo).length;
  2090. const postsPerWeek = Math.round((postsLast30 / 4) * 10) / 10;
  2091. // Platforms used
  2092. const platforms = [...new Set(recentPosts.flatMap((p) => (p.destinations || []).map((d) => d.platform)).filter(Boolean))];
  2093. // Success rate
  2094. const publishedCount = recentPosts.filter((p) => p.status === 'published').length;
  2095. const successRate = Math.round((publishedCount / postsLast30) * 100);
  2096. // Top hashtags from post content
  2097. const hashtagCounts = {};
  2098. for (const post of recentPosts) {
  2099. const re = /#([a-zA-Z]\w*)/g;
  2100. let m;
  2101. re.lastIndex = 0;
  2102. while ((m = re.exec(post.content || '')) !== null) {
  2103. const tag = `#${m[1].toLowerCase()}`;
  2104. hashtagCounts[tag] = (hashtagCounts[tag] || 0) + 1;
  2105. }
  2106. }
  2107. const topHashtags = Object.entries(hashtagCounts)
  2108. .sort((a, b) => b[1] - a[1])
  2109. .slice(0, 5)
  2110. .map(([tag, count]) => `${tag} (${count}x)`)
  2111. .join(', ');
  2112. // Posting hour distribution — identify peak hours
  2113. const hourCounts = {};
  2114. for (const post of recentPosts) {
  2115. if (post.publishedAt) {
  2116. const h = new Date(post.publishedAt).getUTCHours();
  2117. hourCounts[h] = (hourCounts[h] || 0) + 1;
  2118. }
  2119. }
  2120. const peakHours = Object.entries(hourCounts)
  2121. .sort((a, b) => b[1] - a[1])
  2122. .slice(0, 3)
  2123. .map(([h]) => `${h}:00 UTC`)
  2124. .join(', ');
  2125. // Engagement data from post_metrics
  2126. const metricsFilter = filter
  2127. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  2128. : {};
  2129. const metrics = await db.collection('post_metrics')
  2130. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  2131. .toArray();
  2132. const avgEngagement = metrics.length > 0
  2133. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  2134. : 0;
  2135. const statsBlock = [
  2136. `Publishing stats (last 30 days):`,
  2137. `- Total posts: ${postsLast30}`,
  2138. `- Posts this week: ${postsLast7}`,
  2139. `- Posts per week (avg): ${postsPerWeek}`,
  2140. `- Platforms used: ${platforms.join(', ') || 'unknown'}`,
  2141. `- Success rate: ${successRate}%`,
  2142. `- Average engagement per post: ${avgEngagement}`,
  2143. `- Current peak posting hours (UTC): ${peakHours || 'not enough data'}`,
  2144. `- Top hashtags in use: ${topHashtags || 'none detected'}`,
  2145. ].join('\n');
  2146. const system = 'You are a social media performance analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2147. const prompt = `Audit this social media account and return a structured report.
  2148. ${statsBlock}
  2149. Return a JSON object with exactly these fields:
  2150. {
  2151. "score": <overall health score 0-100>,
  2152. "summary": "<2-3 sentence assessment>",
  2153. "postingFrequency": { "score": <0-10>, "assessment": "<one sentence>" },
  2154. "engagement": { "score": <0-10>, "benchmark": "<Excellent|Good|Average|Below Average>", "assessment": "<one sentence>" },
  2155. "contentMix": { "score": <0-10>, "assessment": "<one sentence on variety and platform fit>" },
  2156. "recommendations": ["<specific action 1>", "<specific action 2>", "<specific action 3>"]
  2157. }
  2158. Scoring benchmarks: posting 5+x/week = 8-10, 3-4x = 6-7, 1-2x = 4-5, less = 1-3.
  2159. Engagement benchmarks: >5 avg = Excellent, 3-5 = Good, 1-3 = Average, <1 = Below Average.
  2160. Return ONLY the JSON object.`;
  2161. try {
  2162. const pconf = await getActiveProviderConfig();
  2163. const model = pconf.model;
  2164. let text = '';
  2165. if (pconf.provider === 'ollama') {
  2166. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2167. text = res.data.response;
  2168. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2169. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2170. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2171. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2172. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2173. text = res.data.choices[0]?.message?.content || '';
  2174. } else if (pconf.provider === 'gemini') {
  2175. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2176. const res = await axios.post(
  2177. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2178. { contents: buildGeminiContents(prompt, system) },
  2179. { timeout: 120000 },
  2180. );
  2181. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2182. } else {
  2183. return reply.code(400).send({ error: 'AI not configured' });
  2184. }
  2185. let audit = null;
  2186. try {
  2187. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2188. audit = JSON.parse(jsonStr);
  2189. if (typeof audit.score !== 'number') throw new Error();
  2190. } catch {
  2191. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  2192. }
  2193. log.info({ action: 'analytics_audit', account: request.query.account || 'all', outcome: 'success' });
  2194. return {
  2195. success: true,
  2196. ...audit,
  2197. stats: { postsLast30, postsLast7, postsPerWeek, platforms, successRate, avgEngagement },
  2198. generatedAt: new Date(),
  2199. };
  2200. } catch (err) {
  2201. return reply.code(503).send({ error: 'Audit failed', detail: err.message });
  2202. }
  2203. });
  2204. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  2205. app.get('/hashtag-groups', async () => {
  2206. const db = await getDb();
  2207. const groups = await db.collection('hashtag_groups').find({}).sort({ name: 1 }).toArray();
  2208. return { groups };
  2209. });
  2210. app.post('/hashtag-groups', async (request, reply) => {
  2211. const { name, hashtags } = request.body || {};
  2212. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  2213. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2214. const db = await getDb();
  2215. const result = await db.collection('hashtag_groups').insertOne({
  2216. name: name.trim(),
  2217. hashtags: [...new Set(tags)],
  2218. createdAt: new Date(),
  2219. updatedAt: new Date(),
  2220. });
  2221. return { success: true, _id: result.insertedId };
  2222. });
  2223. app.put('/hashtag-groups/:id', async (request, reply) => {
  2224. const { id } = request.params;
  2225. const { name, hashtags } = request.body || {};
  2226. const update = { updatedAt: new Date() };
  2227. if (name?.trim()) update.name = name.trim();
  2228. if (hashtags) {
  2229. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2230. update.hashtags = [...new Set(tags)];
  2231. }
  2232. const db = await getDb();
  2233. let oid;
  2234. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2235. await db.collection('hashtag_groups').updateOne({ _id: oid }, { $set: update });
  2236. return { success: true };
  2237. });
  2238. app.delete('/hashtag-groups/:id', async (request, reply) => {
  2239. const { id } = request.params;
  2240. const db = await getDb();
  2241. let oid;
  2242. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2243. await db.collection('hashtag_groups').deleteOne({ _id: oid });
  2244. return { success: true };
  2245. });
  2246. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  2247. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  2248. function extractHashtags(text) {
  2249. if (!text) return [];
  2250. const tags = [];
  2251. let m;
  2252. HASHTAG_RE.lastIndex = 0;
  2253. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  2254. return tags;
  2255. }
  2256. function gradeHashtag(count, avgEngagement) {
  2257. if (count >= 5 && avgEngagement >= 10) return 'A';
  2258. if (count >= 3 && avgEngagement >= 3) return 'B';
  2259. if (count >= 2) return 'C';
  2260. return 'D';
  2261. }
  2262. // POST /hashtags/scrape — scan YOUR published posts per-account.
  2263. // Body: { accountKey?: string } — omit to scan all accounts at once.
  2264. app.post('/hashtags/scrape', async (request) => {
  2265. const { accountKey: filterAccount } = request.body || {};
  2266. const db = await getDb();
  2267. // tagMap key: `${accountKey}||${hashtag}`
  2268. const tagMap = {};
  2269. function touch(tag, accountKey, platform, engagement) {
  2270. const key = `${accountKey}||${tag}`;
  2271. if (!tagMap[key]) tagMap[key] = { tag, accountKey, count: 0, totalEngagement: 0, platforms: new Set() };
  2272. tagMap[key].count++;
  2273. tagMap[key].totalEngagement += engagement;
  2274. tagMap[key].platforms.add(platform);
  2275. }
  2276. // Engagement lookup keyed by content fingerprint
  2277. const postMetrics = await db.collection('post_metrics').find({}).toArray();
  2278. const metricsByContent = {};
  2279. for (const m of postMetrics) {
  2280. if (m.content) {
  2281. const key = m.content.slice(0, 100).toLowerCase().trim();
  2282. metricsByContent[key] = (metricsByContent[key] || 0) + (m.metrics?.engagementTotal || 0);
  2283. }
  2284. }
  2285. // Scan YOUR published posts only — feeds are others' content, not your performance
  2286. const posts = await db.collection('posts').find({}, { projection: { content: 1, destinations: 1 } }).toArray();
  2287. for (const post of posts) {
  2288. const tags = extractHashtags(post.content || '');
  2289. if (!tags.length) continue;
  2290. const engagement = post.content
  2291. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  2292. : 0;
  2293. const destinations = post.destinations?.length ? post.destinations : [{ platform: 'unknown' }];
  2294. for (const dest of destinations) {
  2295. const acctKey = dest.accountId ? `${dest.platform}:${dest.accountId}` : dest.platform;
  2296. if (filterAccount && acctKey !== filterAccount) continue;
  2297. for (const tag of tags) {
  2298. touch(tag, acctKey, dest.platform, engagement / Math.max(tags.length, 1));
  2299. }
  2300. }
  2301. }
  2302. let scraped = 0;
  2303. for (const [compoundKey, data] of Object.entries(tagMap)) {
  2304. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  2305. await db.collection('hashtag_stats').updateOne(
  2306. { _id: compoundKey },
  2307. {
  2308. $set: {
  2309. hashtag: data.tag,
  2310. accountKey: data.accountKey,
  2311. count: data.count,
  2312. avgEngagement: Math.round(avgEngagement * 10) / 10,
  2313. grade: gradeHashtag(data.count, avgEngagement),
  2314. platforms: [...data.platforms],
  2315. lastScraped: new Date(),
  2316. },
  2317. },
  2318. { upsert: true }
  2319. );
  2320. scraped++;
  2321. }
  2322. log.info({ action: 'hashtag_scrape', accountKey: filterAccount || 'all', outcome: 'success', scraped });
  2323. return { success: true, scraped };
  2324. });
  2325. app.get('/hashtags/stats', async (request) => {
  2326. const { sort, accountKey } = request.query;
  2327. const db = await getDb();
  2328. const sortField = sort === 'engagement' ? 'avgEngagement' : 'count';
  2329. if (accountKey) {
  2330. // Per-account view
  2331. const stats = await db.collection('hashtag_stats')
  2332. .find({ accountKey })
  2333. .sort({ [sortField]: -1 })
  2334. .limit(200)
  2335. .toArray();
  2336. return { stats };
  2337. }
  2338. // Aggregate view: group by hashtag across all accounts
  2339. const allStats = await db.collection('hashtag_stats').find({ accountKey: { $exists: true } }).toArray();
  2340. const grouped = new Map();
  2341. for (const s of allStats) {
  2342. if (!s.hashtag) continue;
  2343. if (!grouped.has(s.hashtag)) {
  2344. grouped.set(s.hashtag, { count: 0, totalEngagement: 0, totalCount: 0, platforms: new Set(), lastScraped: null });
  2345. }
  2346. const g = grouped.get(s.hashtag);
  2347. g.count += s.count;
  2348. g.totalEngagement += s.avgEngagement * s.count;
  2349. g.totalCount += s.count;
  2350. for (const p of (s.platforms || [])) g.platforms.add(p);
  2351. if (!g.lastScraped || (s.lastScraped && new Date(s.lastScraped) > new Date(g.lastScraped))) g.lastScraped = s.lastScraped;
  2352. }
  2353. const stats = [...grouped.entries()]
  2354. .map(([tag, g]) => {
  2355. const avgEngagement = g.totalCount > 0 ? Math.round((g.totalEngagement / g.totalCount) * 10) / 10 : 0;
  2356. return {
  2357. _id: tag,
  2358. hashtag: tag,
  2359. accountKey: null,
  2360. count: g.count,
  2361. avgEngagement,
  2362. grade: gradeHashtag(g.count, avgEngagement),
  2363. platforms: [...g.platforms],
  2364. lastScraped: g.lastScraped,
  2365. };
  2366. })
  2367. .sort((a, b) => b[sortField] - a[sortField])
  2368. .slice(0, 200);
  2369. return { stats };
  2370. });
  2371. app.post('/hashtags/ai-suggest', async (request, reply) => {
  2372. const { accountKey, topTags = [], count = 20 } = request.body || {};
  2373. let profileCtx = '';
  2374. if (accountKey) {
  2375. try {
  2376. const db = await getDb();
  2377. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  2378. if (profile) {
  2379. const parts = [];
  2380. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  2381. if (profile.description) parts.push(`Description: ${profile.description}`);
  2382. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  2383. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  2384. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  2385. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  2386. profileCtx = parts.join('\n');
  2387. }
  2388. } catch (_) {}
  2389. }
  2390. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  2391. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  2392. const prompt = [
  2393. `Suggest ${count} high-performing hashtags for a social media account.`,
  2394. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  2395. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  2396. `\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`,
  2397. ].filter(Boolean).join('');
  2398. try {
  2399. const pconf = await getActiveProviderConfig();
  2400. const model = pconf.model;
  2401. let text = '';
  2402. if (pconf.provider === 'ollama') {
  2403. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  2404. text = res.data.response;
  2405. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2406. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2407. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2408. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2409. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  2410. text = res.data.choices[0]?.message?.content || '';
  2411. } else if (pconf.provider === 'gemini') {
  2412. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2413. const res = await axios.post(
  2414. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2415. { contents: buildGeminiContents(prompt, system) },
  2416. { timeout: 60000 },
  2417. );
  2418. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2419. } else {
  2420. return reply.code(400).send({ error: 'AI not configured' });
  2421. }
  2422. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  2423. return { success: true, hashtags: tags };
  2424. } catch (err) {
  2425. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  2426. }
  2427. });
  2428. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  2429. async function extractTextFromUrl(url) {
  2430. try {
  2431. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  2432. const html = res.data || '';
  2433. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  2434. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  2435. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  2436. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  2437. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  2438. } catch {
  2439. return '';
  2440. }
  2441. }
  2442. async function scrapeBluesky(profileUrl) {
  2443. try {
  2444. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  2445. if (!handle) return '';
  2446. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  2447. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  2448. return posts.join('\n').slice(0, 3000);
  2449. } catch {
  2450. return '';
  2451. }
  2452. }
  2453. async function scrapeMastodon(profileUrl) {
  2454. try {
  2455. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  2456. if (!m) return '';
  2457. const [, instance, username] = m;
  2458. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  2459. const accountId = lookupRes.data?.id;
  2460. if (!accountId) return '';
  2461. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  2462. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  2463. return posts.join('\n').slice(0, 3000);
  2464. } catch {
  2465. return '';
  2466. }
  2467. }
  2468. async function runCompetitorScrape(competitorId) {
  2469. const db = await getDb();
  2470. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  2471. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  2472. const newItems = [];
  2473. if (competitor.websiteUrl) {
  2474. const text = await extractTextFromUrl(competitor.websiteUrl);
  2475. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  2476. }
  2477. const socialEntries = Object.entries(competitor.socialUrls || {});
  2478. for (const [platform, url] of socialEntries) {
  2479. if (!url) continue;
  2480. let text = '';
  2481. if (platform === 'bluesky') text = await scrapeBluesky(url);
  2482. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  2483. else text = await extractTextFromUrl(url);
  2484. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  2485. }
  2486. const existing = competitor.scrapedContent || [];
  2487. // Detect whether any newly scraped content differs from what was previously stored
  2488. const existingFingerprints = new Set(existing.map((s) => s.url + '||' + s.text.slice(0, 200)));
  2489. const contentChanged = newItems.some((item) => !existingFingerprints.has(item.url + '||' + item.text.slice(0, 200)));
  2490. const combined = [...newItems, ...existing].slice(0, 20);
  2491. await db.collection('competitors').updateOne(
  2492. { _id: new ObjectId(competitorId) },
  2493. { $set: { scrapedContent: combined, contentChanged, lastScraped: new Date(), updatedAt: new Date() } },
  2494. );
  2495. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  2496. }
  2497. async function buildCompetitorSystemSuffix() {
  2498. try {
  2499. const db = await getDb();
  2500. const competitors = await db.collection('competitors').find({
  2501. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  2502. }).toArray();
  2503. if (!competitors.length) return '';
  2504. const lines = competitors.map((c) => {
  2505. if (c.aiAnalysis?.positioning) {
  2506. const a = c.aiAnalysis;
  2507. const parts = [`- ${c.name}:`];
  2508. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  2509. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  2510. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  2511. return parts.join('\n');
  2512. }
  2513. return `- ${c.name}: ${c.aiSummary}`;
  2514. }).join('\n');
  2515. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  2516. } catch {
  2517. return '';
  2518. }
  2519. }
  2520. // Save Google Places API key (used for local competitor discovery)
  2521. app.post('/credentials/google-places', async (request, reply) => {
  2522. const { apiKey } = request.body || {};
  2523. if (!apiKey?.trim()) return reply.code(400).send({ error: 'apiKey is required' });
  2524. const db = await getDb();
  2525. await db.collection('platform_credentials').updateOne(
  2526. { _id: 'google_places' },
  2527. { $set: { apiKey: apiKey.trim(), updatedAt: new Date() } },
  2528. { upsert: true },
  2529. );
  2530. return { success: true };
  2531. });
  2532. app.get('/credentials/google-places', async () => {
  2533. const db = await getDb();
  2534. const cred = await db.collection('platform_credentials').findOne({ _id: 'google_places' });
  2535. return { configured: !!cred?.apiKey, keyHint: cred?.apiKey ? `****${cred.apiKey.slice(-4)}` : null };
  2536. });
  2537. app.delete('/credentials/google-places', async () => {
  2538. const db = await getDb();
  2539. await db.collection('platform_credentials').deleteOne({ _id: 'google_places' });
  2540. return { success: true };
  2541. });
  2542. // Discover local competitors via Google Places API
  2543. app.post('/competitors/discover-local', async (request, reply) => {
  2544. const { location, businessType, radiusMeters = 5000 } = request.body || {};
  2545. if (!location) return reply.code(400).send({ error: 'location is required' });
  2546. const db = await getDb();
  2547. const cred = await db.collection('platform_credentials').findOne({ _id: 'google_places' });
  2548. if (!cred?.apiKey) return reply.code(400).send({ error: 'Google Places API key not configured — add it in Settings.' });
  2549. // Step 1: Geocode the location string to coordinates
  2550. let lat, lng;
  2551. try {
  2552. const geoRes = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
  2553. params: { address: location, key: cred.apiKey },
  2554. timeout: 10000,
  2555. });
  2556. const loc = geoRes.data.results?.[0]?.geometry?.location;
  2557. if (!loc) return reply.code(400).send({ error: `Could not geocode location: "${location}"` });
  2558. lat = loc.lat;
  2559. lng = loc.lng;
  2560. } catch (err) {
  2561. return reply.code(503).send({ error: 'Geocoding failed', detail: err.message });
  2562. }
  2563. // Step 2: Text Search for nearby businesses of the given type
  2564. try {
  2565. const query = businessType ? `${businessType} near ${location}` : location;
  2566. const searchRes = await axios.get('https://maps.googleapis.com/maps/api/place/textsearch/json', {
  2567. params: {
  2568. query,
  2569. location: `${lat},${lng}`,
  2570. radius: Math.min(radiusMeters, 50000),
  2571. key: cred.apiKey,
  2572. },
  2573. timeout: 10000,
  2574. });
  2575. const places = (searchRes.data.results || []).slice(0, 10);
  2576. if (!places.length) return { success: true, suggestions: [] };
  2577. // Step 3: Fetch website URLs for places that have them
  2578. const suggestions = [];
  2579. for (const place of places.slice(0, 8)) {
  2580. try {
  2581. const detailRes = await axios.get('https://maps.googleapis.com/maps/api/place/details/json', {
  2582. params: { place_id: place.place_id, fields: 'name,website,formatted_address,rating', key: cred.apiKey },
  2583. timeout: 8000,
  2584. });
  2585. const detail = detailRes.data.result || {};
  2586. suggestions.push({
  2587. name: detail.name || place.name,
  2588. websiteUrl: detail.website || null,
  2589. address: detail.formatted_address || '',
  2590. rating: detail.rating || null,
  2591. reason: `Local ${businessType || 'business'} near ${location}${detail.rating ? ` · ${detail.rating}★` : ''}`,
  2592. });
  2593. } catch {
  2594. suggestions.push({ name: place.name, websiteUrl: null, address: '', rating: null, reason: `Local ${businessType || 'business'} near ${location}` });
  2595. }
  2596. }
  2597. log.info({ action: 'discover_local_competitors', location, count: suggestions.length, outcome: 'success' });
  2598. return { success: true, suggestions };
  2599. } catch (err) {
  2600. return reply.code(503).send({ error: 'Google Places search failed', detail: err.message });
  2601. }
  2602. });
  2603. // Discover competitors automatically using AI + account profile context
  2604. app.post('/competitors/discover', async (request, reply) => {
  2605. const db = await getDb();
  2606. // Use the first account profile for business context
  2607. const profile = await db.collection('account_profiles').findOne({});
  2608. const contextParts = [];
  2609. if (profile) {
  2610. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  2611. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  2612. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  2613. if (profile.websiteUrl) contextParts.push(`Website: ${profile.websiteUrl}`);
  2614. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  2615. }
  2616. if (!contextParts.length) {
  2617. return reply.code(400).send({ error: 'Set up at least one Account Profile in Settings before discovering competitors.' });
  2618. }
  2619. const system = 'You are a market research analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2620. const prompt = `Based on the following business profile, identify the top 5 direct competitors.
  2621. ${contextParts.join('\n')}
  2622. Return ONLY a JSON array of objects, e.g.:
  2623. [{"name":"Competitor Name","websiteUrl":"https://example.com","reason":"One sentence on why they compete directly"}]
  2624. Rules:
  2625. - Return real, existing businesses only.
  2626. - Include only direct competitors (same product/service category, same target audience).
  2627. - websiteUrl must be a valid https URL to the competitor's main website.
  2628. - No explanation outside the JSON array.`;
  2629. try {
  2630. const pconf = await getActiveProviderConfig();
  2631. const model = pconf.model;
  2632. let text = '';
  2633. if (pconf.provider === 'ollama') {
  2634. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2635. text = res.data.response;
  2636. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2637. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2638. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2639. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2640. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2641. text = res.data.choices[0]?.message?.content || '';
  2642. } else if (pconf.provider === 'gemini') {
  2643. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2644. const res = await axios.post(
  2645. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2646. { contents: buildGeminiContents(prompt, system) },
  2647. { timeout: 120000 },
  2648. );
  2649. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2650. } else {
  2651. return reply.code(400).send({ error: 'AI not configured' });
  2652. }
  2653. let suggestions = [];
  2654. try {
  2655. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2656. const parsed = JSON.parse(jsonStr);
  2657. if (!Array.isArray(parsed)) throw new Error();
  2658. suggestions = parsed
  2659. .filter((s) => s && typeof s.name === 'string' && typeof s.websiteUrl === 'string')
  2660. .slice(0, 5)
  2661. .map((s) => ({
  2662. name: s.name.trim(),
  2663. websiteUrl: s.websiteUrl.trim(),
  2664. reason: typeof s.reason === 'string' ? s.reason.trim() : '',
  2665. }));
  2666. } catch {
  2667. return reply.code(503).send({ error: 'AI returned invalid format — try again' });
  2668. }
  2669. log.info({ action: 'competitor_discover', count: suggestions.length, outcome: 'success' });
  2670. return { success: true, suggestions };
  2671. } catch (err) {
  2672. return reply.code(503).send({ error: 'Discovery failed', detail: err.message });
  2673. }
  2674. });
  2675. // List competitors
  2676. app.get('/competitors', async (request, reply) => {
  2677. const db = await getDb();
  2678. const list = await db.collection('competitors').find({}).sort({ createdAt: 1 }).toArray();
  2679. return list;
  2680. });
  2681. // Add competitor (max 2)
  2682. app.post('/competitors', async (request, reply) => {
  2683. const db = await getDb();
  2684. const count = await db.collection('competitors').countDocuments();
  2685. if (count >= 5) return reply.code(400).send({ error: 'Maximum 5 competitors allowed' });
  2686. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  2687. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  2688. const now = new Date();
  2689. const result = await db.collection('competitors').insertOne({
  2690. name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  2691. });
  2692. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  2693. return doc;
  2694. });
  2695. // Update competitor
  2696. app.put('/competitors/:id', async (request, reply) => {
  2697. const db = await getDb();
  2698. const { name, websiteUrl, socialUrls } = request.body || {};
  2699. const updates = { updatedAt: new Date() };
  2700. if (name !== undefined) updates.name = name;
  2701. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  2702. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  2703. await db.collection('competitors').updateOne({ _id: new ObjectId(request.params.id) }, { $set: updates });
  2704. const doc = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2705. return doc;
  2706. });
  2707. // Delete competitor
  2708. app.delete('/competitors/:id', async (request, reply) => {
  2709. const db = await getDb();
  2710. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id) });
  2711. return { success: true };
  2712. });
  2713. // Scrape one competitor — returns jobId immediately, runs in background
  2714. app.post('/competitors/:id/scrape', async (request, reply) => {
  2715. const jobId = new ObjectId().toString();
  2716. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  2717. (async () => {
  2718. try {
  2719. const result = await runCompetitorScrape(request.params.id);
  2720. activeScrapeJobs.set(jobId, {
  2721. status: result.ok ? 'done' : 'failed',
  2722. sources: result.sources,
  2723. message: result.message,
  2724. });
  2725. } catch (err) {
  2726. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  2727. }
  2728. })();
  2729. return reply.code(202).send({ jobId });
  2730. });
  2731. // Poll scrape job status
  2732. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  2733. const job = activeScrapeJobs.get(request.params.jobId);
  2734. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  2735. return job;
  2736. });
  2737. // Scrape all competitors (called by scheduler)
  2738. app.post('/competitors/scrape-all', async (request, reply) => {
  2739. const db = await getDb();
  2740. const all = await db.collection('competitors').find({}).toArray();
  2741. const results = [];
  2742. for (const c of all) {
  2743. const r = await runCompetitorScrape(c._id.toString());
  2744. results.push({ id: c._id.toString(), name: c.name, ...r });
  2745. }
  2746. return { success: true, results };
  2747. });
  2748. // Summarize competitor content with AI — returns structured analysis
  2749. app.post('/competitors/:id/summarize', async (request, reply) => {
  2750. const db = await getDb();
  2751. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2752. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2753. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  2754. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  2755. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2756. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  2757. {
  2758. "themes": ["3-5 main content topics or pillars they focus on"],
  2759. "tone": "one sentence describing their voice and communication style",
  2760. "positioning": "one sentence on how they position themselves in the market",
  2761. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  2762. "moves": ["3 specific content angles you could use to stand out against them"],
  2763. "profile": {
  2764. "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)",
  2765. "keyFeatures": ["3-5 core product or service features they emphasise"],
  2766. "marketingChannels": ["2-4 social/marketing channels they actively use based on content"],
  2767. "targetCustomer": "one sentence describing their apparent ideal customer"
  2768. },
  2769. "prediction": {
  2770. "satisfiedWithPosition": <true if they appear content with their current position, false if they seem to be pushing for growth>,
  2771. "likelyNextMoves": ["2-3 strategic moves they will probably make based on current trajectory"],
  2772. "vulnerabilities": ["2-3 specific weaknesses or blind spots visible in their content"],
  2773. "retaliationTriggers": ["1-2 moves by a competitor that would most likely provoke a strong response from them"]
  2774. }
  2775. }
  2776. Content:
  2777. ${content}
  2778. Return ONLY the JSON object. No explanation, no markdown.`;
  2779. try {
  2780. const pconf = await getActiveProviderConfig();
  2781. const model = pconf.model;
  2782. let text = '';
  2783. if (pconf.provider === 'ollama') {
  2784. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2785. text = res.data.response;
  2786. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2787. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2788. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2789. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2790. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2791. text = res.data.choices[0]?.message?.content || '';
  2792. } else if (pconf.provider === 'gemini') {
  2793. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2794. const res = await axios.post(
  2795. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2796. { contents: buildGeminiContents(prompt, system) },
  2797. { timeout: 180000 },
  2798. );
  2799. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2800. } else {
  2801. return reply.code(400).send({ error: 'AI not configured' });
  2802. }
  2803. let aiAnalysis = null;
  2804. try {
  2805. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2806. aiAnalysis = JSON.parse(jsonStr);
  2807. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  2808. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  2809. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  2810. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  2811. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  2812. // Validate profile block
  2813. if (!aiAnalysis.profile || typeof aiAnalysis.profile !== 'object') aiAnalysis.profile = {};
  2814. if (typeof aiAnalysis.profile.pricing !== 'string') aiAnalysis.profile.pricing = '';
  2815. if (!Array.isArray(aiAnalysis.profile.keyFeatures)) aiAnalysis.profile.keyFeatures = [];
  2816. if (!Array.isArray(aiAnalysis.profile.marketingChannels)) aiAnalysis.profile.marketingChannels = [];
  2817. if (typeof aiAnalysis.profile.targetCustomer !== 'string') aiAnalysis.profile.targetCustomer = '';
  2818. // Validate prediction block
  2819. if (!aiAnalysis.prediction || typeof aiAnalysis.prediction !== 'object') aiAnalysis.prediction = {};
  2820. if (typeof aiAnalysis.prediction.satisfiedWithPosition !== 'boolean') aiAnalysis.prediction.satisfiedWithPosition = true;
  2821. if (!Array.isArray(aiAnalysis.prediction.likelyNextMoves)) aiAnalysis.prediction.likelyNextMoves = [];
  2822. if (!Array.isArray(aiAnalysis.prediction.vulnerabilities)) aiAnalysis.prediction.vulnerabilities = [];
  2823. if (!Array.isArray(aiAnalysis.prediction.retaliationTriggers)) aiAnalysis.prediction.retaliationTriggers = [];
  2824. } catch {
  2825. aiAnalysis = null;
  2826. }
  2827. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  2828. await db.collection('competitors').updateOne(
  2829. { _id: new ObjectId(request.params.id) },
  2830. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  2831. );
  2832. return { success: true, aiAnalysis };
  2833. } catch (err) {
  2834. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  2835. }
  2836. });
  2837. // Extract keywords from scraped content using AI (item 34)
  2838. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  2839. const db = await getDb();
  2840. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2841. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2842. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  2843. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  2844. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2845. 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:
  2846. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  2847. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  2848. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  2849. - navigational: user is searching for a specific brand or tool by name
  2850. Content:
  2851. ${content}
  2852. Return ONLY a JSON array, e.g.:
  2853. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  2854. No explanation, no markdown.`;
  2855. try {
  2856. const pconf = await getActiveProviderConfig();
  2857. const model = pconf.model;
  2858. let text = '';
  2859. if (pconf.provider === 'ollama') {
  2860. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2861. text = res.data.response;
  2862. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2863. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2864. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2865. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2866. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2867. text = res.data.choices[0]?.message?.content || '';
  2868. } else if (pconf.provider === 'gemini') {
  2869. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2870. const res = await axios.post(
  2871. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2872. { contents: buildGeminiContents(prompt, system) },
  2873. { timeout: 120000 },
  2874. );
  2875. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2876. } else {
  2877. return reply.code(400).send({ error: 'AI not configured' });
  2878. }
  2879. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  2880. let keywords = [];
  2881. try {
  2882. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2883. const parsed = JSON.parse(jsonStr);
  2884. if (!Array.isArray(parsed)) throw new Error();
  2885. const now = new Date();
  2886. keywords = parsed
  2887. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  2888. .slice(0, 20)
  2889. .map((k) => ({
  2890. term: k.term.trim(),
  2891. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  2892. extractedAt: now,
  2893. }));
  2894. } catch {
  2895. keywords = [];
  2896. }
  2897. await db.collection('competitors').updateOne(
  2898. { _id: new ObjectId(request.params.id) },
  2899. { $set: { keywords, updatedAt: new Date() } },
  2900. );
  2901. return { success: true, keywords };
  2902. } catch (err) {
  2903. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  2904. }
  2905. });
  2906. // Analyse content gaps — compare competitor keywords against user's hashtag_stats
  2907. app.post('/competitors/:id/analyze-gaps', async (request, reply) => {
  2908. const db = await getDb();
  2909. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2910. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2911. const keywords = (competitor.keywords || []);
  2912. if (!keywords.length) return reply.code(400).send({ error: 'Extract keywords first before analysing gaps' });
  2913. const hashtagDocs = await db.collection('hashtag_stats')
  2914. .find({ accountKey: { $exists: true } }, { projection: { _id: 0, hashtag: 1 } })
  2915. .toArray();
  2916. const hashtagStatsEmpty = hashtagDocs.length === 0;
  2917. // Deduplicate across accounts — same hashtag used by any account counts as covered
  2918. const uniqueTags = [...new Set(hashtagDocs.map((h) => h.hashtag).filter(Boolean))];
  2919. const hashtagTexts = uniqueTags.map((tag) => ({ id: tag, text: tag.replace(/^#/, '').toLowerCase() }));
  2920. const INTENT_ORDER = { transactional: 0, commercial: 1, informational: 2, navigational: 3 };
  2921. function findMatchingHashtags(term) {
  2922. const words = term.toLowerCase().split(/\s+/).filter((w) => w.length >= 4);
  2923. return hashtagTexts
  2924. .filter(({ text }) => words.some((w) => text.includes(w)))
  2925. .map(({ id }) => id);
  2926. }
  2927. const gaps = [];
  2928. const covered = [];
  2929. for (const kw of keywords) {
  2930. const term = typeof kw === 'string' ? kw : kw.term;
  2931. const intent = typeof kw === 'string' ? 'informational' : (kw.intent || 'informational');
  2932. const matched = findMatchingHashtags(term);
  2933. if (matched.length) {
  2934. covered.push({ term, intent, matchedHashtags: matched.slice(0, 4) });
  2935. } else {
  2936. gaps.push({ term, intent });
  2937. }
  2938. }
  2939. gaps.sort((a, b) => (INTENT_ORDER[a.intent] ?? 99) - (INTENT_ORDER[b.intent] ?? 99));
  2940. const gapAnalysis = { gaps, covered, totalKeywords: keywords.length, hashtagStatsEmpty, lastAnalyzed: new Date() };
  2941. await db.collection('competitors').updateOne(
  2942. { _id: new ObjectId(request.params.id) },
  2943. { $set: { gapAnalysis, updatedAt: new Date() } },
  2944. );
  2945. return { success: true, ...gapAnalysis };
  2946. });
  2947. // Detect and classify market signals from latest scraped content
  2948. app.post('/competitors/:id/detect-signals', async (request, reply) => {
  2949. const db = await getDb();
  2950. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2951. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2952. const recentContent = (competitor.scrapedContent || []).slice(0, 10);
  2953. if (!recentContent.length) return reply.code(400).send({ error: 'Scrape first before detecting signals' });
  2954. const contentText = recentContent.map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 4000);
  2955. const baseline = competitor.aiAnalysis
  2956. ? `Previous profile — Themes: ${(competitor.aiAnalysis.themes || []).join(', ')}. Tone: ${competitor.aiAnalysis.tone || 'unknown'}.`
  2957. : 'No prior analysis available.';
  2958. const system = 'You are a competitive intelligence analyst specialising in market signal detection. Return only valid JSON with no explanation, no markdown.';
  2959. const prompt = `Analyse the latest content from competitor "${competitor.name}" and detect any notable changes or strategic signals.
  2960. Baseline context:
  2961. ${baseline}
  2962. Latest scraped content:
  2963. ${contentText}
  2964. Classify any changes you detect. Use these signal types:
  2965. - topic_expansion: new content themes or topics not previously seen
  2966. - tone_shift: measurable change in communication style or voice
  2967. - campaign_launch: evidence of a new marketing campaign or product promotion
  2968. - pricing_change: any mention of new pricing, offers, or discounts
  2969. - market_entry: signs of entering a new platform, audience, or geography
  2970. - competitive_aggression: direct competitor comparisons, attack marketing, or poaching language
  2971. - frequency_change: evidence of significantly more or less content activity
  2972. Return ONLY a JSON array (empty array [] if no significant signals):
  2973. [{"type":"<type>","description":"<one sentence describing the specific change>","severity":"<low|medium|high>"}]
  2974. Severity guide: high = major strategic shift, medium = notable change worth monitoring, low = minor or uncertain change.`;
  2975. try {
  2976. const pconf = await getActiveProviderConfig();
  2977. const model = pconf.model;
  2978. let text = '';
  2979. if (pconf.provider === 'ollama') {
  2980. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2981. text = res.data.response;
  2982. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2983. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2984. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2985. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2986. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2987. text = res.data.choices[0]?.message?.content || '';
  2988. } else if (pconf.provider === 'gemini') {
  2989. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2990. const res = await axios.post(
  2991. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2992. { contents: buildGeminiContents(prompt, system) },
  2993. { timeout: 120000 },
  2994. );
  2995. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2996. } else {
  2997. return reply.code(400).send({ error: 'AI not configured' });
  2998. }
  2999. const VALID_TYPES = new Set(['topic_expansion', 'tone_shift', 'campaign_launch', 'pricing_change', 'market_entry', 'competitive_aggression', 'frequency_change']);
  3000. const VALID_SEVERITIES = new Set(['low', 'medium', 'high']);
  3001. let signals = [];
  3002. try {
  3003. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3004. const parsed = JSON.parse(jsonStr);
  3005. if (!Array.isArray(parsed)) throw new Error();
  3006. const now = new Date();
  3007. signals = parsed
  3008. .filter((s) => s && VALID_TYPES.has(s.type) && typeof s.description === 'string')
  3009. .slice(0, 8)
  3010. .map((s) => ({
  3011. type: s.type,
  3012. description: s.description.trim(),
  3013. severity: VALID_SEVERITIES.has(s.severity) ? s.severity : 'medium',
  3014. detectedAt: now,
  3015. }));
  3016. } catch {
  3017. signals = [];
  3018. }
  3019. await db.collection('competitors').updateOne(
  3020. { _id: new ObjectId(request.params.id) },
  3021. { $set: { signals, contentChanged: false, updatedAt: new Date() } },
  3022. );
  3023. log.info({ action: 'detect_signals', competitorId: request.params.id, count: signals.length, outcome: 'success' });
  3024. return { success: true, signals };
  3025. } catch (err) {
  3026. return reply.code(503).send({ error: 'Signal detection failed', detail: err.message });
  3027. }
  3028. });
  3029. // Generate a 5-post content roadmap from competitor keywords and gaps
  3030. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  3031. const db = await getDb();
  3032. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  3033. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3034. const keywords = (competitor.keywords || []);
  3035. const hasKeywords = keywords.length > 0;
  3036. const hasContent = (competitor.scrapedContent || []).length > 0;
  3037. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  3038. const kwList = hasKeywords
  3039. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  3040. : '';
  3041. const gaps = competitor.aiAnalysis?.gaps || [];
  3042. const moves = competitor.aiAnalysis?.moves || [];
  3043. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  3044. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  3045. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  3046. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  3047. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  3048. ${kwSection}${gapsSection}${movesSection}
  3049. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  3050. - topic: short topic name, max 8 words
  3051. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  3052. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  3053. - rationale: one sentence on why this post wins against ${competitor.name}
  3054. Return ONLY a JSON array:
  3055. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  3056. No explanation, no markdown.`;
  3057. try {
  3058. const pconf = await getActiveProviderConfig();
  3059. const model = pconf.model;
  3060. let text = '';
  3061. if (pconf.provider === 'ollama') {
  3062. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  3063. text = res.data.response;
  3064. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3065. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3066. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3067. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3068. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  3069. text = res.data.choices[0]?.message?.content || '';
  3070. } else if (pconf.provider === 'gemini') {
  3071. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3072. const res = await axios.post(
  3073. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3074. { contents: buildGeminiContents(prompt, system) },
  3075. { timeout: 180000 },
  3076. );
  3077. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3078. } else {
  3079. return reply.code(400).send({ error: 'AI not configured' });
  3080. }
  3081. let roadmap = [];
  3082. try {
  3083. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3084. const parsed = JSON.parse(jsonStr);
  3085. if (!Array.isArray(parsed)) throw new Error();
  3086. roadmap = parsed
  3087. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  3088. .slice(0, 5)
  3089. .map((p) => ({
  3090. topic: p.topic.trim(),
  3091. headline: p.headline.trim(),
  3092. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  3093. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  3094. }));
  3095. } catch {
  3096. roadmap = [];
  3097. }
  3098. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  3099. await db.collection('competitors').updateOne(
  3100. { _id: new ObjectId(request.params.id) },
  3101. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  3102. );
  3103. return { success: true, contentRoadmap: roadmap };
  3104. } catch (err) {
  3105. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  3106. }
  3107. });
  3108. module.exports = app;