server.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. // ─── Account Profiles ────────────────────────────────────────────────────────
  154. app.get('/profiles', async () => {
  155. const db = await getDb();
  156. const profiles = await db.collection('account_profiles').find({}).toArray();
  157. return { profiles };
  158. });
  159. app.get('/profiles/:accountKey', async (request, reply) => {
  160. const { accountKey } = request.params;
  161. const db = await getDb();
  162. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  163. return profile ?? { _id: accountKey };
  164. });
  165. app.put('/profiles/:accountKey', async (request, reply) => {
  166. const { accountKey } = request.params;
  167. const {
  168. businessName = '', description = '', websiteUrl = '', industry = '',
  169. targetAudience = '', toneOfVoice = '', keywords = '', hashtags = '',
  170. postingGuidelines = '',
  171. } = request.body || {};
  172. const db = await getDb();
  173. await db.collection('account_profiles').updateOne(
  174. { _id: accountKey },
  175. { $set: { businessName, description, websiteUrl, industry, targetAudience, toneOfVoice, keywords, hashtags, postingGuidelines, updatedAt: new Date() } },
  176. { upsert: true }
  177. );
  178. return { success: true };
  179. });
  180. // ─── Platform service URLs ────────────────────────────────────────────────────
  181. const PLATFORM_SERVICES = {
  182. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  183. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  184. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  185. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  186. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  187. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  188. };
  189. // Direct multi-platform post endpoint.
  190. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  191. app.post('/post', async (request, reply) => {
  192. const { content, destinations = [] } = request.body || {};
  193. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  194. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  195. const results = await Promise.allSettled(
  196. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  197. const serviceUrl = PLATFORM_SERVICES[platform];
  198. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  199. const res = await axios.post(`${serviceUrl}/post`, { content, accountId, imageUrl, videoUrl, link }, { timeout: 30000 });
  200. return { platform, accountId, ...res.data };
  201. })
  202. );
  203. const output = results.map((r, i) =>
  204. r.status === 'fulfilled'
  205. ? r.value
  206. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  207. );
  208. const anyFailed = output.some((r) => !r.success);
  209. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  210. });
  211. // ─── Legacy post route ────────────────────────────────────────────────────────
  212. let rabbitMQProducer = new RabbitMQProducer();
  213. app.post('/', async (request, reply) => {
  214. try {
  215. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  216. reply.send({ status: 'ok' });
  217. } catch (error) {
  218. console.error('Error handling POST request:', error);
  219. reply.status(500).send({ error: 'Internal Server Error' });
  220. }
  221. });
  222. // ─── Meta App Credentials ────────────────────────────────────────────────────
  223. // Save Facebook App ID + Secret (entered by user in Settings UI)
  224. app.post('/credentials/meta-app', async (request, reply) => {
  225. const { appId, appSecret } = request.body || {};
  226. if (!appId || !appSecret) {
  227. return reply.code(400).send({ error: 'appId and appSecret are required' });
  228. }
  229. await setCredentials('meta_app', { appId, appSecret });
  230. return { success: true };
  231. });
  232. // Get Meta App config (secret is masked for UI display)
  233. app.get('/credentials/meta-app', async () => {
  234. const cred = await getCredentials('meta_app');
  235. if (!cred) return { configured: false };
  236. return { configured: true, appId: cred.appId, appSecretHint: `****${cred.appSecret.slice(-4)}` };
  237. });
  238. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  239. // Return the Facebook OAuth URL to redirect the user to
  240. app.get('/auth/meta/init', async (request, reply) => {
  241. const cred = await getCredentials('meta_app');
  242. if (!cred?.appId) {
  243. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  244. }
  245. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  246. const scopes = [
  247. 'pages_manage_posts',
  248. 'pages_read_engagement',
  249. 'instagram_basic',
  250. 'instagram_content_publish',
  251. 'instagram_manage_insights',
  252. ].join(',');
  253. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  254. return { url };
  255. });
  256. // OAuth callback — Facebook redirects here after user authorises
  257. app.get('/auth/meta/callback', async (request, reply) => {
  258. const { code, error: oauthError } = request.query;
  259. if (oauthError) {
  260. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  261. }
  262. if (!code) {
  263. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  264. }
  265. try {
  266. const appCred = await getCredentials('meta_app');
  267. if (!appCred?.appId) throw new Error('App credentials not configured');
  268. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  269. // Exchange code for short-lived token
  270. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  271. params: {
  272. client_id: appCred.appId,
  273. client_secret: appCred.appSecret,
  274. redirect_uri: redirectUri,
  275. code,
  276. },
  277. });
  278. // Upgrade to long-lived user token (~60 days)
  279. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  280. params: {
  281. grant_type: 'fb_exchange_token',
  282. client_id: appCred.appId,
  283. client_secret: appCred.appSecret,
  284. fb_exchange_token: shortRes.data.access_token,
  285. },
  286. });
  287. const userToken = longRes.data.access_token;
  288. // Fetch all managed Facebook Pages
  289. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  290. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  291. });
  292. const pages = [];
  293. const igAccounts = [];
  294. for (const page of pagesRes.data.data || []) {
  295. pages.push({
  296. id: page.id,
  297. name: page.name,
  298. accessToken: page.access_token,
  299. picture: page.picture?.data?.url || null,
  300. selected: false,
  301. });
  302. // Check for linked Instagram Business Account
  303. try {
  304. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  305. params: {
  306. fields: 'instagram_business_account',
  307. access_token: page.access_token,
  308. },
  309. });
  310. if (igRes.data.instagram_business_account?.id) {
  311. const igId = igRes.data.instagram_business_account.id;
  312. // Fetch IG account details
  313. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  314. params: {
  315. fields: 'id,username,name,profile_picture_url',
  316. access_token: userToken,
  317. },
  318. });
  319. igAccounts.push({
  320. id: igId,
  321. username: igProfile.data.username || igProfile.data.name,
  322. name: igProfile.data.name,
  323. avatar: igProfile.data.profile_picture_url || null,
  324. accessToken: userToken,
  325. pageId: page.id,
  326. selected: false,
  327. });
  328. }
  329. } catch (_) {
  330. // Page has no linked Instagram account — skip
  331. }
  332. }
  333. // Store discovery results for the UI to pick from
  334. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  335. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  336. } catch (err) {
  337. console.error('[Gateway] Meta OAuth error:', err.response?.data || err.message);
  338. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  339. }
  340. });
  341. // Return pending discovery results so the UI can render the page picker
  342. app.get('/auth/meta/discovered', async () => {
  343. const discovery = await getCredentials('meta_discovery');
  344. if (!discovery) return { pages: [], igAccounts: [] };
  345. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  346. });
  347. // User has chosen which pages/accounts to connect
  348. app.post('/auth/meta/save', async (request, reply) => {
  349. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  350. const discovery = await getCredentials('meta_discovery');
  351. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  352. const fbPages = (discovery.pages || []).map((p) => ({
  353. ...p,
  354. selected: selectedPageIds.includes(p.id),
  355. }));
  356. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  357. ...a,
  358. selected: selectedIgAccountIds.includes(a.id),
  359. }));
  360. await setCredentials('facebook', { pages: fbPages });
  361. await setCredentials('instagram', { accounts: igAccounts });
  362. await deleteCredentials('meta_discovery');
  363. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  364. });
  365. // Disconnect all Meta platforms
  366. app.delete('/credentials/meta', async () => {
  367. await deleteCredentials('facebook');
  368. await deleteCredentials('instagram');
  369. await deleteCredentials('meta_discovery');
  370. return { success: true };
  371. });
  372. // ─── Credential Status ────────────────────────────────────────────────────────
  373. // Aggregate connection status for all DB-managed platforms
  374. app.get('/credentials', async () => {
  375. const [metaApp, fb, ig] = await Promise.all([
  376. getCredentials('meta_app'),
  377. getCredentials('facebook'),
  378. getCredentials('instagram'),
  379. ]);
  380. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  381. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  382. return {
  383. metaApp: { configured: !!(metaApp?.appId) },
  384. facebook: {
  385. connected: fbPages.length > 0,
  386. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  387. },
  388. instagram: {
  389. connected: igAccounts.length > 0,
  390. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  391. },
  392. };
  393. });
  394. module.exports = app;