server.js 141 KB

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