server.js 17 KB

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