-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcron.js
More file actions
258 lines (202 loc) · 7.69 KB
/
cron.js
File metadata and controls
258 lines (202 loc) · 7.69 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
// import cron from "node-cron";
// import { google } from "googleapis";
// import { connectToDatabase } from './src/lib/mongodb.js';
// import {decryptToken} from "./src/utils/crypto.js";
// async function getUserTokensByEmail(email) {
// const db = await connectToDatabase();
// const user = await db.collection("users").findOne({ email });
// if (!user || !user.access_token || !user.refresh_token) {
// throw new Error(`User tokens not found for email: ${email}`);
// }
// // Decrypt tokens
// const accessToken = decryptToken(user.access_token);
// const refreshToken = decryptToken(user.refresh_token);
// return { access_token: accessToken, refresh_token: refreshToken };
// }
// async function sendScheduledEmails() {
// const db = await connectToDatabase();
// // Fetch scheduled emails
// const scheduledEmails = await db.collection('ScheduledEmails').find({
// scheduledTime: { $lte: new Date() },
// status: 'scheduled',
// }).toArray();
// for (const email of scheduledEmails) {
// console.log(`Processing email for user email: ${email.email}`);
// try {
// // Fetch tokens using the user's email
// const userTokens = await getUserTokensByEmail(email.email);
// console.log(`Fetched tokens for email ${email.email}:`, userTokens);
// const oauth2Client = new google.auth.OAuth2(
// process.env.GOOGLE_CLIENT_ID,
// process.env.GOOGLE_CLIENT_SECRET
// );
// oauth2Client.setCredentials({
// access_token: userTokens.access_token,
// refresh_token: userTokens.refresh_token,
// });
// const gmail = google.gmail({ version: "v1", auth: oauth2Client });
// try {
// // Construct raw email with proper formatting
// const rawMessage = [
// `From: Your App Name <${email.from || "youremail@gmail.com"}>`,
// `To: ${email.to}`,
// email.cc ? `Cc: ${email.cc}` : "",
// email.bcc ? `Bcc: ${email.bcc}` : "",
// `Subject: ${email.subject}`,
// "",
// email.body,
// ].filter(Boolean).join("\r\n");
// const base64EncodedEmail = Buffer.from(rawMessage)
// .toString("base64")
// .replace(/\+/g, "-")
// .replace(/\//g, "_")
// .replace(/=+$/, "");
// await gmail.users.messages.send({
// userId: "me",
// requestBody: {
// raw: base64EncodedEmail,
// },
// });
// // Mark as sent
// await db.collection('ScheduledEmails').updateOne(
// { _id: email._id },
// { $set: { status: 'sent', sentAt: new Date() } }
// );
// console.log(`Email sent successfully to ${email.to}`);
// } catch (sendError) {
// console.error(`Failed to send email to ${email.to}:`, sendError.message);
// await db.collection('ScheduledEmails').updateOne(
// { _id: email._id },
// { $set: { status: 'failed', error: sendError.message } }
// );
// }
// } catch (tokenError) {
// console.error(`Error fetching tokens for email ${email.email}:`, tokenError.message);
// await db.collection('ScheduledEmails').updateOne(
// { _id: email._id },
// { $set: { status: 'failed', error: tokenError.message } }
// );
// }
// }
// }
// // Schedule the cron job
// cron.schedule("* * * * *", sendScheduledEmails);
import cron from "node-cron";
import { google } from "googleapis";
import { connectToDatabase } from './src/lib/mongodb.js';
import { decryptToken } from "./src/utils/crypto.js";
const constructRawEmail = (email) => {
const boundary = "----=_Part_0_1234567890";
const isHtml = email.body && email.body.trim().startsWith("<");
const contentType = isHtml
? "Content-Type: text/html; charset=UTF-8"
: "Content-Type: text/plain; charset=UTF-8";
// Start the MIME message
const messageParts = [
"MIME-Version: 1.0",
`Content-Type: multipart/mixed; boundary="${boundary}"`,
"",
`--${boundary}`,
contentType,
"",
email.body || "(No content provided)",
];
// Add attachments if present
if (email.attachments && email.attachments.length > 0) {
email.attachments.forEach((file) => {
messageParts.push(
`--${boundary}`,
`Content-Type: ${file.type}; name="${file.name}"`,
"Content-Transfer-Encoding: base64",
`Content-Disposition: attachment; filename="${file.name}"`,
"",
file.content // Assume this is already base64 encoded
);
});
}
// End the MIME message
messageParts.push(`--${boundary}--`);
const rawMessage = messageParts.join("\r\n");
// Debugging: Log the constructed message
console.log("Constructed MIME Message:");
console.log(rawMessage);
const base64EncodedEmail = Buffer.from(rawMessage)
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
return base64EncodedEmail;
};
async function getUserTokensByEmail(email) {
const db = await connectToDatabase();
const user = await db.collection("users").findOne({ email });
if (!user || !user.access_token || !user.refresh_token) {
throw new Error(`User tokens not found for email: ${email}`);
}
// Decrypt tokens
const accessToken = decryptToken(user.access_token);
const refreshToken = decryptToken(user.refresh_token);
return { access_token: accessToken, refresh_token: refreshToken };
}
async function sendScheduledEmails() {
const db = await connectToDatabase();
// Fetch scheduled emails
const scheduledEmails = await db.collection("ScheduledEmails").find({
scheduledTime: { $lte: new Date() },
status: "scheduled",
}).toArray();
for (const email of scheduledEmails) {
console.log(`Processing email for user email: ${email.email}`);
try {
// Fetch tokens using the user's email
const userTokens = await getUserTokensByEmail(email.email);
console.log(`Fetched tokens for email ${email.email}:`, userTokens);
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET
);
oauth2Client.setCredentials({
access_token: userTokens.access_token,
refresh_token: userTokens.refresh_token,
});
const gmail = google.gmail({ version: "v1", auth: oauth2Client });
try {
// Construct and send the raw email
const base64EncodedEmail = constructRawEmail(email);
await gmail.users.messages.send({
userId: "me",
requestBody: {
raw: base64EncodedEmail, // Base64 encoded raw email
},
});
// Debugging
console.log("Payload sent to Gmail API:", {
userId: "me",
requestBody: {
raw: base64EncodedEmail,
},
});
// Mark as sent
await db.collection("ScheduledEmails").updateOne(
{ _id: email._id },
{ $set: { status: "sent", sentAt: new Date() } }
);
console.log(`Email sent successfully to ${email.to}`);
} catch (sendError) {
console.error(`Failed to send email to ${email.to}:`, sendError.message);
await db.collection("ScheduledEmails").updateOne(
{ _id: email._id },
{ $set: { status: "failed", error: sendError.message } }
);
}
} catch (tokenError) {
console.error(`Error fetching tokens for email ${email.email}:`, tokenError.message);
await db.collection("ScheduledEmails").updateOne(
{ _id: email._id },
{ $set: { status: "failed", error: tokenError.message } }
);
}
}
}
// Schedule the cron job
cron.schedule("* * * * *", sendScheduledEmails);