-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgmailService.js
More file actions
212 lines (187 loc) · 6.62 KB
/
Copy pathgmailService.js
File metadata and controls
212 lines (187 loc) · 6.62 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
const axios = require('axios');
// Configure Google OAuth 2.0 Credentials from Env vars (Never hardcoded)
const CLIENT_ID = process.env.GOOGLE_CLIENT_ID || process.env.GMAIL_CLIENT_ID || 'dummy_google_client_id';
const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET || process.env.GMAIL_CLIENT_SECRET || 'dummy_google_client_secret';
const REDIRECT_URI = process.env.GOOGLE_REDIRECT_URI || process.env.GMAIL_REDIRECT_URI || 'http://localhost:3000/api/integrations/email/callback';
const SCOPES = [
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'
];
/**
* Robust retry wrapper for network operations
*/
async function runWithRetry(fn, retries = 2, delay = 1000) {
for (let i = 0; i <= retries; i++) {
try {
return await fn();
} catch (err) {
const errorMsg = err.response?.data ? JSON.stringify(err.response.data) : err.message;
console.warn(`[Gmail API Attempt ${i + 1} Failed]: ${errorMsg}`);
if (i === retries) {
throw new Error(`Gmail service execution failed after ${retries + 1} attempts: ${errorMsg}`);
}
await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i))); // Exponential backoff
}
}
}
/**
* Generates official Google OAuth login URL
*/
function getGoogleAuthUrl(state, customRedirectUri) {
const stateParam = encodeURIComponent(state);
const scopesParam = encodeURIComponent(SCOPES.join(' '));
const redirectParam = encodeURIComponent(customRedirectUri || REDIRECT_URI);
return `https://accounts.google.com/o/oauth2/v2/auth` +
`?client_id=${CLIENT_ID}` +
`&redirect_uri=${redirectParam}` +
`&response_type=code` +
`&scope=${scopesParam}` +
`&state=${stateParam}` +
`&access_type=offline` +
`&prompt=consent`;
}
/**
* Exchanges auth code for access & refresh tokens
*/
async function exchangeAuthCode(code, customRedirectUri) {
return runWithRetry(async () => {
const params = new URLSearchParams();
params.append('code', code);
params.append('client_id', CLIENT_ID);
params.append('client_secret', CLIENT_SECRET);
params.append('redirect_uri', customRedirectUri || REDIRECT_URI);
params.append('grant_type', 'authorization_code');
console.log('[Gmail Service] Exchanging authorization code...');
const response = await axios.post('https://oauth2.googleapis.com/token', params, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
return {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expiresIn: response.data.expires_in
};
});
}
/**
* Refreshes access token using refresh token
*/
async function refreshAccessToken(refreshToken) {
return runWithRetry(async () => {
const params = new URLSearchParams();
params.append('client_id', CLIENT_ID);
params.append('client_secret', CLIENT_SECRET);
params.append('refresh_token', refreshToken);
params.append('grant_type', 'refresh_token');
console.log('[Gmail Service] Refreshing access token...');
const response = await axios.post('https://oauth2.googleapis.com/token', params, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
return {
accessToken: response.data.access_token,
expiresIn: response.data.expires_in
};
});
}
/**
* Fetch Google profile info
*/
async function fetchUserProfile(accessToken) {
return runWithRetry(async () => {
console.log('[Gmail Service] Loading user profile details...');
const response = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { 'Authorization': `Bearer ${accessToken}` }
});
return {
email: response.data.email,
name: response.data.name,
picture: response.data.picture
};
});
}
/**
* Formats and sends mime mail via Gmail endpoint
*/
async function sendRawEmail(accessToken, to, subject, htmlBody) {
return runWithRetry(async () => {
console.log(`[Gmail Service] Sending MIME email to ${to}...`);
// Construct simple compliant MIME body
const emailContent = [
`To: ${to}`,
`Subject: ${subject}`,
'MIME-Version: 1.0',
'Content-Type: text/html; charset=utf-8',
'Content-Transfer-Encoding: base64',
'',
Buffer.from(htmlBody).toString('base64')
].join('\r\n');
// Base64URL encode the raw content
const safeRaw = Buffer.from(emailContent)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
const response = await axios.post('https://gmail.googleapis.com/gmail/v1/users/me/messages/send',
{ raw: safeRaw },
{
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
}
);
return response.data;
});
}
/**
* Fetch list of recently sent emails
*/
async function listSentEmails(accessToken, maxResults = 10) {
return runWithRetry(async () => {
console.log('[Gmail Service] Retrieving list of sent messages...');
const listResponse = await axios.get('https://gmail.googleapis.com/gmail/v1/users/me/messages', {
headers: { 'Authorization': `Bearer ${accessToken}` },
params: {
q: 'from:me',
maxResults
}
});
if (!listResponse.data.messages || listResponse.data.messages.length === 0) {
return [];
}
const messages = [];
// Hydrate message detail headers in parallel
await Promise.all(listResponse.data.messages.map(async (msg) => {
try {
const msgDetail = await axios.get(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${msg.id}`, {
headers: { 'Authorization': `Bearer ${accessToken}` }
});
const headers = msgDetail.data.payload.headers;
const to = headers.find(h => h.name.toLowerCase() === 'to')?.value || '';
const subject = headers.find(h => h.name.toLowerCase() === 'subject')?.value || '';
const date = headers.find(h => h.name.toLowerCase() === 'date')?.value || '';
messages.push({
id: msg.id,
to,
subject,
date,
snippet: msgDetail.data.snippet
});
} catch (e) {
console.warn(`[Gmail Service Warning] Skip hydrating message ${msg.id}: ${e.message}`);
}
}));
return messages.sort((a, b) => new Date(b.date) - new Date(a.date));
});
}
module.exports = {
CLIENT_ID,
CLIENT_SECRET,
getGoogleAuthUrl,
exchangeAuthCode,
refreshAccessToken,
fetchUserProfile,
sendRawEmail,
listSentEmails
};