index.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. require('dotenv').config();
  2. const axios = require('axios');
  3. const BasePlatformService = require('./utils/BasePlatformService');
  4. const { getDb } = require('./utils/MongoDBConnector');
  5. const { decryptToken, warnIfNoKey } = require('./utils/crypto');
  6. const { getWorkspaceCredential } = require('./utils/credentials');
  7. const GRAPH_API = 'https://graph.facebook.com/v22.0';
  8. // Instagram's Container API requires a publicly accessible image URL.
  9. // If APP_BASE_URL is set to a public domain, relative /media/ paths are resolved against it.
  10. const APP_BASE_URL = (process.env.APP_BASE_URL || '').replace(/\/$/, '');
  11. function resolveInstagramMediaUrl(url) {
  12. if (!url) return url;
  13. if (url.startsWith('/')) {
  14. if (!APP_BASE_URL) {
  15. throw new Error('Instagram requires a publicly accessible image URL. Set APP_BASE_URL to your public domain (e.g. https://social.example.com) to post images from the media library.');
  16. }
  17. const full = `${APP_BASE_URL}${url}`;
  18. if (/https?:\/\/(localhost|127\.0\.0\.1)/.test(full)) {
  19. throw new Error(`Instagram requires a publicly accessible image URL. The app (${APP_BASE_URL}) is not reachable from the internet. Use an external image URL or deploy to a public server.`);
  20. }
  21. return full;
  22. }
  23. // Already a full URL — warn if it looks local but still try
  24. if (/https?:\/\/(localhost|127\.0\.0\.1)/.test(url)) {
  25. throw new Error(`Instagram requires a publicly accessible image URL. "${url}" is not reachable from the internet. Use an external image URL or deploy to a public server.`);
  26. }
  27. return url;
  28. }
  29. class InstagramService extends BasePlatformService {
  30. constructor() {
  31. super('instagram');
  32. }
  33. // Read selected Instagram Business Accounts from MongoDB.
  34. // Falls back to env vars for backwards compatibility.
  35. async _getAccounts(workspaceId = 'default') {
  36. try {
  37. const db = await getDb();
  38. const cred = await getWorkspaceCredential(db, 'instagram', workspaceId);
  39. const dbAccounts = (cred?.accounts || []).filter((a) => a.selected);
  40. if (dbAccounts.length > 0) {
  41. return dbAccounts.map((a) => ({ ...a, accessToken: decryptToken(a.accessToken) })).filter((a) => a.accessToken);
  42. }
  43. } catch (_) { /* fall through */ }
  44. // Env var fallback (legacy single-account mode)
  45. const { INSTAGRAM_ACCESS_TOKEN, INSTAGRAM_BUSINESS_ACCOUNT_ID } = process.env;
  46. if (INSTAGRAM_ACCESS_TOKEN && INSTAGRAM_BUSINESS_ACCOUNT_ID) {
  47. return [{ id: INSTAGRAM_BUSINESS_ACCOUNT_ID, accessToken: INSTAGRAM_ACCESS_TOKEN }];
  48. }
  49. return [];
  50. }
  51. async getStatus(workspaceId = 'default') {
  52. const accounts = await this._getAccounts(workspaceId);
  53. if (accounts.length === 0) {
  54. return { connected: false, platform: 'instagram', error: 'No Instagram accounts connected — use Settings to connect via Facebook OAuth' };
  55. }
  56. try {
  57. const first = accounts[0];
  58. const res = await axios.get(`${GRAPH_API}/${first.id}`, {
  59. params: {
  60. fields: 'id,name,username,profile_picture_url',
  61. access_token: first.accessToken,
  62. },
  63. });
  64. return {
  65. connected: true,
  66. platform: 'instagram',
  67. username: res.data.username || res.data.name,
  68. displayName: res.data.name,
  69. avatar: res.data.profile_picture_url,
  70. accountCount: accounts.length,
  71. };
  72. } catch (err) {
  73. return { connected: false, platform: 'instagram', error: err.response?.data?.error?.message || err.message };
  74. }
  75. }
  76. async fetchFeed({ limit = 20, workspaceId = 'default' } = {}) {
  77. const accounts = await this._getAccounts(workspaceId);
  78. if (accounts.length === 0) throw new Error('No Instagram accounts connected');
  79. const allItems = [];
  80. for (const account of accounts) {
  81. const res = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  82. params: {
  83. fields: 'id,caption,media_type,media_url,thumbnail_url,permalink,timestamp,like_count,comments_count,username',
  84. limit: Math.min(Number(limit), 100),
  85. access_token: account.accessToken,
  86. },
  87. });
  88. const items = (res.data.data || []).map((post) =>
  89. this.normalizeFeedItem({
  90. originalId: post.id,
  91. author: {
  92. name: post.username || account.username || '',
  93. username: post.username || account.username || '',
  94. profileUrl: `https://www.instagram.com/${post.username || account.username || ''}/`,
  95. },
  96. content: post.caption || '',
  97. media: post.media_url
  98. ? [{
  99. url: post.media_url,
  100. type: (post.media_type || 'IMAGE').toLowerCase(),
  101. thumbnail: post.thumbnail_url || post.media_url,
  102. }]
  103. : [],
  104. metrics: {
  105. likes: post.like_count || 0,
  106. comments: post.comments_count || 0,
  107. },
  108. url: post.permalink,
  109. createdAt: post.timestamp,
  110. })
  111. );
  112. allItems.push(...items);
  113. }
  114. try {
  115. const db = await getDb();
  116. const col = db.collection('feeds');
  117. for (const item of allItems) {
  118. await col.updateOne(
  119. { platform: 'instagram', originalId: item.originalId, workspaceId },
  120. { $set: { ...item, workspaceId } },
  121. { upsert: true }
  122. );
  123. }
  124. } catch (err) {
  125. this.app.log.error({ action: 'feed_write', platform: 'instagram', outcome: 'failure', err: err.message });
  126. }
  127. return allItems;
  128. }
  129. // Instagram requires media (image_url or video_url) — text-only posts are not supported.
  130. async publishPost({ content, imageUrl, videoUrl, accountId, firstComment, workspaceId = 'default' } = {}) {
  131. const allAccounts = await this._getAccounts(workspaceId);
  132. if (allAccounts.length === 0) throw new Error('No Instagram accounts connected');
  133. if (!imageUrl && !videoUrl) {
  134. throw new Error('Instagram requires imageUrl or videoUrl — text-only posts are not supported by the Graph API');
  135. }
  136. // If a specific account is requested, target only that account
  137. const accounts = accountId ? allAccounts.filter((a) => a.id === accountId) : allAccounts;
  138. if (accounts.length === 0) throw new Error(`Instagram account ${accountId} not found or not connected`);
  139. const results = [];
  140. for (const account of accounts) {
  141. const containerParams = {
  142. caption: content,
  143. access_token: account.accessToken,
  144. };
  145. if (videoUrl) {
  146. containerParams.media_type = 'REELS';
  147. containerParams.video_url = resolveInstagramMediaUrl(videoUrl);
  148. } else {
  149. containerParams.image_url = resolveInstagramMediaUrl(imageUrl);
  150. }
  151. const containerRes = await axios.post(
  152. `${GRAPH_API}/${account.id}/media`,
  153. null,
  154. { params: containerParams }
  155. );
  156. const publishRes = await axios.post(
  157. `${GRAPH_API}/${account.id}/media_publish`,
  158. null,
  159. { params: { creation_id: containerRes.data.id, access_token: account.accessToken } }
  160. );
  161. const postId = publishRes.data.id;
  162. if (firstComment?.trim()) {
  163. try {
  164. await axios.post(`${GRAPH_API}/${postId}/comments`, null, {
  165. params: { message: firstComment.trim(), access_token: account.accessToken },
  166. timeout: 10000,
  167. });
  168. this.app.log.info({ action: 'first_comment', platform: 'instagram', postId, outcome: 'success' });
  169. } catch (err) {
  170. this.app.log.warn({ action: 'first_comment', platform: 'instagram', postId, outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  171. }
  172. }
  173. results.push({ accountId: account.id, username: account.username, postId });
  174. }
  175. return results;
  176. }
  177. }
  178. const service = new InstagramService();
  179. warnIfNoKey('instagram');
  180. service.start(process.env.PORT || 3005);