server.js 172 KB

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