server.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 RabbitMQProducer = require('./utils/RabbitMQProducer');
  14. const UPLOAD_DIR = process.env.UPLOAD_DIR || '/uploads';
  15. const ALLOWED_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.mp4', '.mov', '.avi']);
  16. const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
  17. fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  18. app.register(multipart, { limits: { fileSize: MAX_FILE_SIZE } });
  19. const GRAPH_API = 'https://graph.facebook.com/v22.0';
  20. // The public base URL of this app (used for OAuth redirect_uri)
  21. const APP_BASE_URL = process.env.APP_BASE_URL || 'http://localhost:8081';
  22. // ─── CORS ────────────────────────────────────────────────────────────────────
  23. app.addHook('onSend', async (request, reply) => {
  24. reply.header('Access-Control-Allow-Origin', '*');
  25. reply.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  26. reply.header('Access-Control-Allow-Headers', 'Content-Type');
  27. });
  28. app.options('*', async (request, reply) => {
  29. reply.code(204).send();
  30. });
  31. // ─── Helpers ─────────────────────────────────────────────────────────────────
  32. async function getCredentials(id) {
  33. const db = await getDb();
  34. return db.collection('platform_credentials').findOne({ _id: id });
  35. }
  36. async function setCredentials(id, data) {
  37. const db = await getDb();
  38. await db.collection('platform_credentials').updateOne(
  39. { _id: id },
  40. { $set: { _id: id, ...data, updatedAt: new Date() } },
  41. { upsert: true }
  42. );
  43. }
  44. async function deleteCredentials(id) {
  45. const db = await getDb();
  46. await db.collection('platform_credentials').deleteOne({ _id: id });
  47. }
  48. // ─── Media Upload & Library ───────────────────────────────────────────────────
  49. app.post('/upload', async (request, reply) => {
  50. const data = await request.file();
  51. if (!data) return reply.code(400).send({ error: 'No file provided' });
  52. const ext = path.extname(data.filename).toLowerCase();
  53. if (!ALLOWED_EXTENSIONS.has(ext)) {
  54. data.file.resume();
  55. return reply.code(400).send({ error: `File type "${ext}" is not allowed. Allowed: jpg, jpeg, png, gif, webp, mp4, mov, avi` });
  56. }
  57. const filename = `${crypto.randomUUID()}${ext}`;
  58. const filepath = path.join(UPLOAD_DIR, filename);
  59. try {
  60. await pipeline(data.file, fs.createWriteStream(filepath));
  61. } catch (err) {
  62. app.log.error({ action: 'media_upload', outcome: 'failure', err: err.message });
  63. return reply.code(500).send({ error: 'Failed to save file' });
  64. }
  65. const stat = fs.statSync(filepath);
  66. const record = {
  67. filename,
  68. originalName: data.filename,
  69. url: `/media/${filename}`,
  70. mimetype: data.mimetype,
  71. size: stat.size,
  72. uploadedAt: new Date(),
  73. };
  74. try {
  75. const db = await getDb();
  76. await db.collection('media_files').insertOne(record);
  77. } catch (err) {
  78. app.log.error({ action: 'media_metadata_save', outcome: 'failure', err: err.message });
  79. }
  80. return { url: record.url, filename, originalName: data.filename, mimetype: data.mimetype, size: stat.size };
  81. });
  82. // List all uploaded media files, newest first
  83. app.get('/media-library', async () => {
  84. const db = await getDb();
  85. const files = await db.collection('media_files').find({}).sort({ uploadedAt: -1 }).toArray();
  86. return { files };
  87. });
  88. // Delete a media file from disk and database
  89. app.delete('/media/:filename', async (request, reply) => {
  90. const { filename } = request.params;
  91. // Prevent path traversal
  92. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  93. return reply.code(400).send({ error: 'Invalid filename' });
  94. }
  95. const filepath = path.join(UPLOAD_DIR, filename);
  96. try {
  97. fs.unlinkSync(filepath);
  98. } catch (err) {
  99. if (err.code !== 'ENOENT') {
  100. app.log.error({ action: 'media_delete', outcome: 'failure', err: err.message });
  101. return reply.code(500).send({ error: 'Failed to delete file' });
  102. }
  103. // Already gone from disk — still clean up DB record
  104. }
  105. const db = await getDb();
  106. await db.collection('media_files').deleteOne({ filename });
  107. return { success: true };
  108. });
  109. // ─── Drafts ──────────────────────────────────────────────────────────────────
  110. app.post('/drafts', async (request, reply) => {
  111. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  112. const db = await getDb();
  113. const now = new Date();
  114. const result = await db.collection('drafts').insertOne({
  115. content, mediaUrl, scheduledAt, destinations, createdAt: now, updatedAt: now,
  116. });
  117. const draft = await db.collection('drafts').findOne({ _id: result.insertedId });
  118. return reply.code(201).send(draft);
  119. });
  120. app.get('/drafts', async () => {
  121. const db = await getDb();
  122. const drafts = await db.collection('drafts').find({}).sort({ updatedAt: -1 }).toArray();
  123. return { drafts };
  124. });
  125. app.get('/drafts/:id', async (request, reply) => {
  126. const { id } = request.params;
  127. let oid;
  128. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  129. const db = await getDb();
  130. const draft = await db.collection('drafts').findOne({ _id: oid });
  131. if (!draft) return reply.code(404).send({ error: 'Draft not found' });
  132. return draft;
  133. });
  134. app.put('/drafts/:id', async (request, reply) => {
  135. const { id } = request.params;
  136. let oid;
  137. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  138. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  139. const db = await getDb();
  140. const result = await db.collection('drafts').updateOne(
  141. { _id: oid },
  142. { $set: { content, mediaUrl, scheduledAt, destinations, updatedAt: new Date() } }
  143. );
  144. if (!result.matchedCount) return reply.code(404).send({ error: 'Draft not found' });
  145. return { success: true };
  146. });
  147. app.delete('/drafts/:id', async (request, reply) => {
  148. const { id } = request.params;
  149. let oid;
  150. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  151. const db = await getDb();
  152. await db.collection('drafts').deleteOne({ _id: oid });
  153. return { success: true };
  154. });
  155. // ─── Meta Token Expiry ───────────────────────────────────────────────────────
  156. let _tokenExpiryCache = null;
  157. let _tokenExpiryCacheAt = 0;
  158. const TOKEN_EXPIRY_TTL = 60 * 60 * 1000; // 1 hour
  159. app.get('/meta/token-expiry', async (request, reply) => {
  160. if (_tokenExpiryCache && Date.now() - _tokenExpiryCacheAt < TOKEN_EXPIRY_TTL) {
  161. return _tokenExpiryCache;
  162. }
  163. const appCred = await getCredentials('meta_app');
  164. if (!appCred?.appId || !appCred?.appSecret) return { accounts: [] };
  165. const ig = await getCredentials('instagram');
  166. const selectedAccounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  167. if (!selectedAccounts.length) return { accounts: [] };
  168. const appToken = `${appCred.appId}|${appCred.appSecret}`;
  169. const accounts = [];
  170. for (const account of selectedAccounts) {
  171. try {
  172. const res = await axios.get(`${GRAPH_API}/debug_token`, {
  173. params: { input_token: account.accessToken, access_token: appToken },
  174. timeout: 10000,
  175. });
  176. const data = res.data.data;
  177. const expiresAt = data.expires_at ? new Date(data.expires_at * 1000).toISOString() : null;
  178. const daysLeft = expiresAt
  179. ? Math.ceil((new Date(expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
  180. : null;
  181. accounts.push({ id: account.id, username: account.username, expiresAt, daysLeft, isValid: !!data.is_valid });
  182. } catch (err) {
  183. app.log.warn({ action: 'token_expiry_check', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  184. }
  185. }
  186. _tokenExpiryCache = { accounts, checkedAt: new Date().toISOString() };
  187. _tokenExpiryCacheAt = Date.now();
  188. return _tokenExpiryCache;
  189. });
  190. // ─── Account Profiles ────────────────────────────────────────────────────────
  191. app.get('/profiles', async () => {
  192. const db = await getDb();
  193. const profiles = await db.collection('account_profiles').find({}).toArray();
  194. return { profiles };
  195. });
  196. app.get('/profiles/:accountKey', async (request, reply) => {
  197. const { accountKey } = request.params;
  198. const db = await getDb();
  199. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  200. return profile ?? { _id: accountKey };
  201. });
  202. app.put('/profiles/:accountKey', async (request, reply) => {
  203. const { accountKey } = request.params;
  204. const {
  205. businessName = '', description = '', websiteUrl = '', industry = '',
  206. targetAudience = '', toneOfVoice = '', keywords = '', hashtags = '',
  207. postingGuidelines = '',
  208. } = request.body || {};
  209. const db = await getDb();
  210. await db.collection('account_profiles').updateOne(
  211. { _id: accountKey },
  212. { $set: { businessName, description, websiteUrl, industry, targetAudience, toneOfVoice, keywords, hashtags, postingGuidelines, updatedAt: new Date() } },
  213. { upsert: true }
  214. );
  215. return { success: true };
  216. });
  217. // ─── AI / Ollama ──────────────────────────────────────────────────────────────
  218. const DEFAULT_OLLAMA_ENDPOINT = process.env.OLLAMA_ENDPOINT || 'http://ollama:11434';
  219. const DEFAULT_OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2';
  220. app.get('/ai/config', async () => {
  221. const config = await getCredentials('ai_config');
  222. return {
  223. provider: config?.provider || 'ollama',
  224. endpoint: config?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  225. model: config?.model || DEFAULT_OLLAMA_MODEL,
  226. visionModel: config?.visionModel || 'llava',
  227. enabled: config?.enabled ?? true,
  228. };
  229. });
  230. app.put('/ai/config', async (request, reply) => {
  231. const { provider = 'ollama', endpoint, model, visionModel = 'llava', enabled = true } = request.body || {};
  232. if (!endpoint) return reply.code(400).send({ error: 'endpoint is required' });
  233. await setCredentials('ai_config', { provider, endpoint, model, visionModel, enabled });
  234. return { success: true };
  235. });
  236. app.get('/ai/models', async (request, reply) => {
  237. const config = await getCredentials('ai_config');
  238. // Allow caller to override endpoint for test-without-save UX
  239. const endpoint = request.query.endpoint || config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  240. try {
  241. const res = await axios.get(`${endpoint}/api/tags`, { timeout: 5000 });
  242. const models = (res.data.models || []).map((m) => m.name);
  243. return { models, endpoint };
  244. } catch (err) {
  245. return reply.code(503).send({ error: 'Could not reach Ollama — check the endpoint', detail: err.message });
  246. }
  247. });
  248. app.post('/ai/generate', async (request, reply) => {
  249. const { prompt, system, model: reqModel } = request.body || {};
  250. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  251. const config = await getCredentials('ai_config');
  252. const endpoint = config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  253. const model = reqModel || config?.model || DEFAULT_OLLAMA_MODEL;
  254. try {
  255. const res = await axios.post(`${endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  256. return { text: res.data.response, model, done: res.data.done };
  257. } catch (err) {
  258. const status = err.response?.status || 503;
  259. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  260. }
  261. });
  262. // Vision caption — fetches image, passes base64 to Ollama vision model
  263. app.post('/ai/caption', async (request, reply) => {
  264. const { imageUrl, model: reqModel } = request.body || {};
  265. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  266. const config = await getCredentials('ai_config');
  267. const endpoint = config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  268. const model = reqModel || config?.visionModel || 'llava';
  269. // Fetch image → base64
  270. let imageBase64;
  271. try {
  272. let imageBuffer;
  273. if (imageUrl.startsWith('/media/')) {
  274. const filename = path.basename(imageUrl);
  275. const filepath = path.join(UPLOAD_DIR, filename);
  276. imageBuffer = fs.readFileSync(filepath);
  277. } else {
  278. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  279. imageBuffer = Buffer.from(imgRes.data);
  280. }
  281. imageBase64 = imageBuffer.toString('base64');
  282. } catch (err) {
  283. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  284. }
  285. try {
  286. const res = await axios.post(`${endpoint}/api/generate`, {
  287. model,
  288. prompt: 'Generate an engaging, concise social media caption for this image. Write only the caption text with relevant hashtags. No explanations or preamble.',
  289. images: [imageBase64],
  290. stream: false,
  291. }, { timeout: 90000 });
  292. return { caption: res.data.response, model };
  293. } catch (err) {
  294. const status = err.response?.status || 503;
  295. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  296. }
  297. });
  298. // SSE streaming endpoint — sends token-by-token as text/event-stream
  299. app.post('/ai/stream', async (request, reply) => {
  300. const { prompt, system, model: reqModel } = request.body || {};
  301. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  302. const config = await getCredentials('ai_config');
  303. const endpoint = config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  304. const model = reqModel || config?.model || DEFAULT_OLLAMA_MODEL;
  305. reply.raw.setHeader('Content-Type', 'text/event-stream');
  306. reply.raw.setHeader('Cache-Control', 'no-cache');
  307. reply.raw.setHeader('X-Accel-Buffering', 'no');
  308. reply.raw.setHeader('Connection', 'keep-alive');
  309. reply.raw.flushHeaders();
  310. try {
  311. const ollamaRes = await axios.post(`${endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  312. ollamaRes.data.on('data', (chunk) => {
  313. try {
  314. const lines = chunk.toString().split('\n').filter(Boolean);
  315. for (const line of lines) {
  316. const data = JSON.parse(line);
  317. reply.raw.write(`data: ${JSON.stringify({ token: data.response || '', done: !!data.done })}\n\n`);
  318. }
  319. } catch (_) {}
  320. });
  321. ollamaRes.data.on('end', () => { reply.raw.end(); });
  322. ollamaRes.data.on('error', (err) => {
  323. reply.raw.write(`data: ${JSON.stringify({ error: err.message, done: true })}\n\n`);
  324. reply.raw.end();
  325. });
  326. } catch (err) {
  327. reply.raw.write(`data: ${JSON.stringify({ error: err.message, done: true })}\n\n`);
  328. reply.raw.end();
  329. }
  330. });
  331. // ─── Platform service URLs ────────────────────────────────────────────────────
  332. const PLATFORM_SERVICES = {
  333. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  334. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  335. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  336. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  337. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  338. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  339. };
  340. // Direct multi-platform post endpoint.
  341. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  342. app.post('/post', async (request, reply) => {
  343. const { content, destinations = [] } = request.body || {};
  344. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  345. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  346. const results = await Promise.allSettled(
  347. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  348. const serviceUrl = PLATFORM_SERVICES[platform];
  349. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  350. const res = await axios.post(`${serviceUrl}/post`, { content, accountId, imageUrl, videoUrl, link }, { timeout: 30000 });
  351. return { platform, accountId, ...res.data };
  352. })
  353. );
  354. const output = results.map((r, i) =>
  355. r.status === 'fulfilled'
  356. ? r.value
  357. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  358. );
  359. const anyFailed = output.some((r) => !r.success);
  360. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  361. });
  362. // ─── Legacy post route ────────────────────────────────────────────────────────
  363. let rabbitMQProducer = new RabbitMQProducer();
  364. app.post('/', async (request, reply) => {
  365. try {
  366. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  367. reply.send({ status: 'ok' });
  368. } catch (error) {
  369. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  370. reply.status(500).send({ error: 'Internal Server Error' });
  371. }
  372. });
  373. // ─── Meta App Credentials ────────────────────────────────────────────────────
  374. // Save Facebook App ID + Secret (entered by user in Settings UI)
  375. app.post('/credentials/meta-app', async (request, reply) => {
  376. const { appId, appSecret } = request.body || {};
  377. if (!appId || !appSecret) {
  378. return reply.code(400).send({ error: 'appId and appSecret are required' });
  379. }
  380. await setCredentials('meta_app', { appId, appSecret });
  381. return { success: true };
  382. });
  383. // Get Meta App config (secret is masked for UI display)
  384. app.get('/credentials/meta-app', async () => {
  385. const cred = await getCredentials('meta_app');
  386. if (!cred) return { configured: false };
  387. return { configured: true, appId: cred.appId, appSecretHint: `****${cred.appSecret.slice(-4)}` };
  388. });
  389. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  390. // Return the Facebook OAuth URL to redirect the user to
  391. app.get('/auth/meta/init', async (request, reply) => {
  392. const cred = await getCredentials('meta_app');
  393. if (!cred?.appId) {
  394. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  395. }
  396. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  397. const scopes = [
  398. 'pages_manage_posts',
  399. 'pages_read_engagement',
  400. 'instagram_basic',
  401. 'instagram_content_publish',
  402. 'instagram_manage_insights',
  403. ].join(',');
  404. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  405. return { url };
  406. });
  407. // OAuth callback — Facebook redirects here after user authorises
  408. app.get('/auth/meta/callback', async (request, reply) => {
  409. const { code, error: oauthError } = request.query;
  410. if (oauthError) {
  411. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  412. }
  413. if (!code) {
  414. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  415. }
  416. try {
  417. const appCred = await getCredentials('meta_app');
  418. if (!appCred?.appId) throw new Error('App credentials not configured');
  419. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  420. // Exchange code for short-lived token
  421. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  422. params: {
  423. client_id: appCred.appId,
  424. client_secret: appCred.appSecret,
  425. redirect_uri: redirectUri,
  426. code,
  427. },
  428. });
  429. // Upgrade to long-lived user token (~60 days)
  430. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  431. params: {
  432. grant_type: 'fb_exchange_token',
  433. client_id: appCred.appId,
  434. client_secret: appCred.appSecret,
  435. fb_exchange_token: shortRes.data.access_token,
  436. },
  437. });
  438. const userToken = longRes.data.access_token;
  439. // Fetch all managed Facebook Pages
  440. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  441. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  442. });
  443. const pages = [];
  444. const igAccounts = [];
  445. for (const page of pagesRes.data.data || []) {
  446. pages.push({
  447. id: page.id,
  448. name: page.name,
  449. accessToken: page.access_token,
  450. picture: page.picture?.data?.url || null,
  451. selected: false,
  452. });
  453. // Check for linked Instagram Business Account
  454. try {
  455. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  456. params: {
  457. fields: 'instagram_business_account',
  458. access_token: page.access_token,
  459. },
  460. });
  461. if (igRes.data.instagram_business_account?.id) {
  462. const igId = igRes.data.instagram_business_account.id;
  463. // Fetch IG account details
  464. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  465. params: {
  466. fields: 'id,username,name,profile_picture_url',
  467. access_token: userToken,
  468. },
  469. });
  470. igAccounts.push({
  471. id: igId,
  472. username: igProfile.data.username || igProfile.data.name,
  473. name: igProfile.data.name,
  474. avatar: igProfile.data.profile_picture_url || null,
  475. accessToken: userToken,
  476. pageId: page.id,
  477. selected: false,
  478. });
  479. }
  480. } catch (_) {
  481. // Page has no linked Instagram account — skip
  482. }
  483. }
  484. // Store discovery results for the UI to pick from
  485. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  486. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  487. } catch (err) {
  488. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  489. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  490. }
  491. });
  492. // Return pending discovery results so the UI can render the page picker
  493. app.get('/auth/meta/discovered', async () => {
  494. const discovery = await getCredentials('meta_discovery');
  495. if (!discovery) return { pages: [], igAccounts: [] };
  496. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  497. });
  498. // User has chosen which pages/accounts to connect
  499. app.post('/auth/meta/save', async (request, reply) => {
  500. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  501. const discovery = await getCredentials('meta_discovery');
  502. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  503. const fbPages = (discovery.pages || []).map((p) => ({
  504. ...p,
  505. selected: selectedPageIds.includes(p.id),
  506. }));
  507. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  508. ...a,
  509. selected: selectedIgAccountIds.includes(a.id),
  510. }));
  511. await setCredentials('facebook', { pages: fbPages });
  512. await setCredentials('instagram', { accounts: igAccounts });
  513. await deleteCredentials('meta_discovery');
  514. _tokenExpiryCache = null; // invalidate cache after reconnect
  515. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  516. });
  517. // Disconnect all Meta platforms
  518. app.delete('/credentials/meta', async () => {
  519. await deleteCredentials('facebook');
  520. await deleteCredentials('instagram');
  521. await deleteCredentials('meta_discovery');
  522. return { success: true };
  523. });
  524. // ─── Credential Status ────────────────────────────────────────────────────────
  525. // Aggregate connection status for all DB-managed platforms
  526. app.get('/credentials', async () => {
  527. const [metaApp, fb, ig] = await Promise.all([
  528. getCredentials('meta_app'),
  529. getCredentials('facebook'),
  530. getCredentials('instagram'),
  531. ]);
  532. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  533. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  534. return {
  535. metaApp: { configured: !!(metaApp?.appId) },
  536. facebook: {
  537. connected: fbPages.length > 0,
  538. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  539. },
  540. instagram: {
  541. connected: igAccounts.length > 0,
  542. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  543. },
  544. };
  545. });
  546. module.exports = app;