-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegrations.js
More file actions
377 lines (324 loc) · 13 KB
/
Copy pathintegrations.js
File metadata and controls
377 lines (324 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
const axios = require('axios');
const database = require('./database');
// Client Credentials
const REDDIT_CLIENT_ID = process.env.REDDIT_CLIENT_ID || 'dummy_reddit_client_id';
const REDDIT_CLIENT_SECRET = process.env.REDDIT_CLIENT_SECRET || 'dummy_reddit_client_secret';
const REDDIT_REDIRECT_URI = process.env.REDDIT_REDIRECT_URI || 'http://localhost:3000/api/integrations/reddit/callback';
const GMAIL_CLIENT_ID = process.env.GMAIL_CLIENT_ID || 'dummy_gmail_client_id';
const GMAIL_CLIENT_SECRET = process.env.GMAIL_CLIENT_SECRET || 'dummy_gmail_client_secret';
const GMAIL_REDIRECT_URI = process.env.GMAIL_REDIRECT_URI || 'http://localhost:3000/api/integrations/email/callback';
// --- REDDIT API INTEGRATIONS ---
/**
* Generate Reddit OAuth redirect link
*/
function getRedditAuthUrl(userId, customRedirectUri) {
const state = encodeURIComponent(userId);
const redirect = customRedirectUri || REDDIT_REDIRECT_URI;
return `https://www.reddit.com/api/v1/authorize?client_id=${REDDIT_CLIENT_ID}&response_type=code&state=${state}&redirect_uri=${encodeURIComponent(redirect)}&duration=permanent&scope=identity submit read`;
}
/**
* Handle Reddit Authorization code callback
*/
async function handleRedditCallback(code, state, customRedirectUri) {
try {
const tokenUrl = 'https://www.reddit.com/api/v1/access_token';
const credentials = Buffer.from(`${REDDIT_CLIENT_ID}:${REDDIT_CLIENT_SECRET}`).toString('base64');
const params = new URLSearchParams();
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', customRedirectUri || REDDIT_REDIRECT_URI);
let access_token, refresh_token, expires_in;
let username = 'MockRedditUser';
let profileData = {};
if (REDDIT_CLIENT_ID !== 'dummy_reddit_client_id') {
const response = await axios.post(tokenUrl, params, {
headers: {
'Authorization': `Basic ${credentials}`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'LeadForgeAI/1.0.0'
}
});
access_token = response.data.access_token;
refresh_token = response.data.refresh_token;
expires_in = response.data.expires_in;
// Fetch user identity profile details
const meResponse = await axios.get('https://oauth.reddit.com/api/v1/me', {
headers: {
'Authorization': `Bearer ${access_token}`,
'User-Agent': 'LeadForgeAI/1.0.0'
}
});
username = meResponse.data.name;
profileData = meResponse.data;
} else {
// Mock exchange for development/testing
access_token = 'mock_reddit_access_token_' + Math.random().toString(36).substr(2, 9);
refresh_token = 'mock_reddit_refresh_token_' + Math.random().toString(36).substr(2, 9);
expires_in = 3600;
}
const userId = state; // decode matched user state
const account = database.saveConnectedAccount(userId, 'reddit', {
username,
accessToken: access_token,
refreshToken: refresh_token || '',
expiresAt: Date.now() + (expires_in * 1000),
profile: profileData
});
database.writeAuditLog(userId, 'REDDIT_OAUTH_CONNECT', 'success', { username });
return { success: true, account };
} catch (err) {
console.error('[Reddit Auth Callback Error]:', err.message);
database.writeAuditLog(state, 'REDDIT_OAUTH_CONNECT', 'failure', { error: err.message });
return { success: false, error: err.message };
}
}
/**
* Automatically refresh Reddit token if expired
*/
async function refreshRedditToken(account) {
if (Date.now() < account.expiresAt - 60000) {
return account.accessToken;
}
if (account.accessToken.startsWith('mock_')) {
account.expiresAt = Date.now() + 3600 * 1000;
database.saveConnectedAccount(account.userId, 'reddit', account);
return account.accessToken;
}
try {
const credentials = Buffer.from(`${REDDIT_CLIENT_ID}:${REDDIT_CLIENT_SECRET}`).toString('base64');
const params = new URLSearchParams();
params.append('grant_type', 'refresh_token');
params.append('refresh_token', account.refreshToken);
const response = await axios.post('https://www.reddit.com/api/v1/access_token', params, {
headers: {
'Authorization': `Basic ${credentials}`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'LeadForgeAI/1.0.0'
}
});
const { access_token, expires_in, refresh_token } = response.data;
account.accessToken = access_token;
if (refresh_token) {
account.refreshToken = refresh_token;
}
account.expiresAt = Date.now() + (expires_in * 1000);
database.saveConnectedAccount(account.userId, 'reddit', account);
return access_token;
} catch (err) {
console.error('[Reddit Token Refresh Error]:', err.message);
return null;
}
}
/**
* Fetch Reddit submissions
*/
async function fetchRedditPosts(account) {
try {
const token = await refreshRedditToken(account);
if (!token) throw new Error('Reddit auth failed.');
if (token.startsWith('mock_')) {
return {
success: true,
posts: [
{ title: 'Launched my SaaS project on Reddit!', score: 24, subreddit: 'saas', id: 'p_1' },
{ title: 'Best tips to get 10 outreach leads daily?', score: 12, subreddit: 'freelance', id: 'p_2' }
]
};
}
const response = await axios.get(`https://oauth.reddit.com/user/${account.username}/submitted`, {
headers: {
'Authorization': `Bearer ${token}`,
'User-Agent': 'LeadForgeAI/1.0.0'
}
});
return { success: true, posts: response.data.data.children.map(c => c.data) };
} catch (err) {
console.error('[Reddit Posts Read Error]:', err.message);
return { success: false, error: err.message };
}
}
/**
* Submit Reddit post (Requires explicit user trigger, never auto-posted)
*/
async function submitRedditPost(account, title, text, subreddit) {
try {
const token = await refreshRedditToken(account);
if (!token) throw new Error('Reddit verification failed.');
database.writeAuditLog(account.userId, 'REDDIT_POST_SUBMIT', 'success', { subreddit, title });
if (token.startsWith('mock_')) {
return { success: true, mock: true, url: `https://reddit.com/r/${subreddit}/mock_post` };
}
const params = new URLSearchParams();
params.append('sr', subreddit);
params.append('title', title);
params.append('kind', 'self');
params.append('text', text);
const response = await axios.post('https://oauth.reddit.com/api/submit', params, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'LeadForgeAI/1.0.0'
}
});
return { success: true, data: response.data };
} catch (err) {
console.error('[Reddit Post Submit Error]:', err.message);
database.writeAuditLog(account.userId, 'REDDIT_POST_SUBMIT', 'failure', { error: err.message });
return { success: false, error: err.message };
}
}
// --- EMAIL OUTREACH OAUTH & SERVICES ---
/**
* Generate Google Email OAuth redirect link
*/
function getEmailAuthUrl(userId, customRedirectUri) {
const gmailService = require('./gmailService');
return gmailService.getGoogleAuthUrl(userId, customRedirectUri);
}
/**
* Handle Google Email redirect callback
*/
async function handleEmailCallback(code, state, customRedirectUri) {
try {
const userId = state;
let access_token, refresh_token, expires_in;
let email = 'outreach@leadforge.ai';
let profileData = { platform: 'gmail' };
const gmailService = require('./gmailService');
if (gmailService.CLIENT_ID !== 'dummy_google_client_id') {
const response = await gmailService.exchangeAuthCode(code, customRedirectUri);
access_token = response.accessToken;
refresh_token = response.refreshToken;
expires_in = response.expiresIn;
const profile = await gmailService.fetchUserProfile(access_token);
email = profile.email;
profileData = profile;
} else {
// Mock exchange for development/testing
access_token = 'mock_google_access_token_' + Math.random().toString(36).substr(2, 9);
refresh_token = 'mock_google_refresh_token_' + Math.random().toString(36).substr(2, 9);
expires_in = 3600;
}
const account = database.saveConnectedAccount(userId, 'email', {
username: email,
email,
accessToken: access_token,
refreshToken: refresh_token || '',
expiresAt: Date.now() + (expires_in * 1000),
profile: profileData
});
database.writeAuditLog(userId, 'EMAIL_OAUTH_CONNECT', 'success', { email });
return { success: true, account };
} catch (err) {
console.error('[Email OAuth Callback Error]:', err.message);
database.writeAuditLog(state, 'EMAIL_OAUTH_CONNECT', 'failure', { error: err.message });
return { success: false, error: err.message };
}
}
/**
* Automatically refresh Google Email OAuth token if expired
*/
async function refreshEmailToken(account) {
if (Date.now() < account.expiresAt - 60000) {
return account.accessToken;
}
if (account.accessToken.startsWith('mock_')) {
account.expiresAt = Date.now() + 3600 * 1000;
database.saveConnectedAccount(account.userId, 'email', account);
return account.accessToken;
}
try {
const gmailService = require('./gmailService');
console.log(`[Email Integration] Token expired. Fetching fresh access token for: ${account.username}`);
const response = await gmailService.refreshAccessToken(account.refreshToken);
account.accessToken = response.accessToken;
account.expiresAt = Date.now() + (response.expiresIn * 1000);
database.saveConnectedAccount(account.userId, 'email', account);
return response.accessToken;
} catch (err) {
console.error('[Google Token Refresh Error]:', err.message);
return null;
}
}
/**
* Fetch recently sent email messages
*/
async function fetchSentEmails(account) {
try {
const token = await refreshEmailToken(account);
if (!token) throw new Error('Gmail verification credentials failed.');
if (token.startsWith('mock_')) {
return {
success: true,
emails: [
{ id: 'm_1', to: 'lead1@company.com', subject: 'Website audit feedback', snippet: 'Hi John, I noticed a viewport bug...', date: new Date().toUTCString() },
{ id: 'm_2', to: 'lead2@company.com', subject: 'Fixing SSL bottleneck', snippet: 'Hi Sarah, your private connection warning...', date: new Date().toUTCString() }
]
};
}
const gmailService = require('./gmailService');
const emails = await gmailService.listSentEmails(token);
return { success: true, emails };
} catch (err) {
console.error('[Gmail Fetch Sent Error]:', err.message);
return { success: false, error: err.message };
}
}
/**
* Send outreach email (Requires manual review verification, adds unsubscribe hook)
*/
async function sendOutreachEmail(account, to, subject, body) {
try {
const token = await refreshEmailToken(account);
if (!token) throw new Error('Gmail authentication failed.');
// Inject unsubscribe footer for anti-spam compliance
const unsubscribeLink = `${process.env.APP_URL || 'http://localhost:3000'}/api/outreach/unsubscribe?email=${encodeURIComponent(to)}`;
const compliantBody = `${body}\n\n---\nTo opt-out of these communications, click here: ${unsubscribeLink}`;
database.writeAuditLog(account.userId, 'EMAIL_OUTREACH_SEND', 'success', { recipient: to });
if (token.startsWith('mock_')) {
return {
success: true,
mode: 'mock_outreach',
message: 'Mock email sent successfully with unsubscribe nodes.',
body: compliantBody
};
}
const gmailService = require('./gmailService');
await gmailService.sendRawEmail(token, to, subject, compliantBody);
return { success: true };
} catch (err) {
console.error('[Email Compose Error]:', err.message);
database.writeAuditLog(account.userId, 'EMAIL_OUTREACH_SEND', 'failure', { error: err.message, recipient: to });
return { success: false, error: err.message };
}
}
// --- INDIE HACKERS MODULAR CONNECTOR ---
/**
* Modular wrapper to track product launch plans (No unsupported scraping)
*/
async function publishIndieHackersDraft(userId, draft) {
try {
database.writeAuditLog(userId, 'IH_LAUNCH_QUEUE', 'success', { title: draft.title });
// Direct manual-compliance mode copy template
return {
success: true,
mode: 'manual_compliance',
message: 'Direct API publish currently pending official IH endpoint support. Copy-paste launch details generated.',
draft
};
} catch (err) {
console.error('[IH Publish Error]:', err.message);
database.writeAuditLog(userId, 'IH_LAUNCH_QUEUE', 'failure', { error: err.message });
return { success: false, error: err.message };
}
}
module.exports = {
getRedditAuthUrl,
handleRedditCallback,
fetchRedditPosts,
submitRedditPost,
getEmailAuthUrl,
handleEmailCallback,
sendOutreachEmail,
publishIndieHackersDraft
};