server.js 23 KB

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