server.js 30 KB

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