-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathindex.js
More file actions
535 lines (447 loc) Β· 17.6 KB
/
index.js
File metadata and controls
535 lines (447 loc) Β· 17.6 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import express from "express";
import nodemailer from "nodemailer";
import cors from "cors";
import { createClient } from "@supabase/supabase-js";
import dotenv from "dotenv";
import { Client, Receiver } from "@upstash/qstash";
// Load environment variables from .env file
dotenv.config();
const app = express();
// Middleware
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// Supabase client - reads from your .env file
const supabaseUrl = process.env.VITE_SUPABASE_URL;
const supabaseKey = process.env.VITE_SUPABASE_ANON_KEY;
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
if (!supabaseUrl || !supabaseKey) {
console.error("ERROR: Missing VITE_SUPABASE_URL or VITE_SUPABASE_ANON_KEY in .env file");
process.exit(1);
}
console.log("Supabase URL:", supabaseUrl);
const supabase = createClient(supabaseUrl, supabaseKey);
// QStash client for publishing messages
const qstashClient = new Client({
token: process.env.QSTASH_TOKEN,
baseUrl: process.env.QSTASH_URL, // For local dev: http://127.0.0.1:8080
});
// QStash receiver for verifying webhook signatures
const qstashReceiver = new Receiver({
currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY,
nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY,
});
// Email transporter configuration
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
// Generate HTML email template for blog
const generateBlogEmailHTML = (blog, unsubscribeLink = "#") => {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${blog.title}</title>
</head>
<body style="margin: 0; padding: 0; background-color: #f4f4f5; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
<table role="presentation" style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 40px 20px;">
<table role="presentation" style="max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
<!-- Header -->
<tr>
<td style="background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%); padding: 30px 40px; text-align: center;">
<h1 style="margin: 0; color: #ffffff; font-size: 24px; font-weight: 600;">CodeSapiens Blog</h1>
</td>
</tr>
<!-- Cover Image -->
${blog.cover_image ? `
<tr>
<td style="padding: 0;">
<img src="${blog.cover_image}" alt="${blog.title}" style="width: 100%; height: auto; display: block;">
</td>
</tr>
` : ''}
<!-- Content -->
<tr>
<td style="padding: 40px;">
<h2 style="margin: 0 0 16px 0; color: #1f2937; font-size: 28px; font-weight: 700; line-height: 1.3;">
${blog.title}
</h2>
${blog.excerpt ? `
<p style="margin: 0 0 24px 0; color: #6b7280; font-size: 16px; line-height: 1.6; font-style: italic;">
${blog.excerpt}
</p>
` : ''}
<div style="color: #374151; font-size: 16px; line-height: 1.8;">
${blog.content}
</div>
<!-- CTA Button -->
<table role="presentation" style="margin: 32px 0;">
<tr>
<td style="background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%); border-radius: 8px;">
<a href="https://codesapiens.in/blog/${blog.slug || ''}" style="display: inline-block; padding: 14px 32px; color: #ffffff; text-decoration: none; font-weight: 600; font-size: 16px;">
Read Full Article β
</a>
</td>
</tr>
</table>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="background-color: #f9fafb; padding: 24px 40px; text-align: center; border-top: 1px solid #e5e7eb;">
<p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;">
You're receiving this because you're a member of CodeSapiens.
</p>
<p style="margin: 0; color: #9ca3af; font-size: 12px;">
Β© ${new Date().getFullYear()} CodeSapiens. All rights reserved.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
`;
};
// ============================================
// API ENDPOINTS
// ============================================
// Health check
app.get("/", (req, res) => {
res.json({ status: "ok", message: "CodeSapiens Email API is running" });
});
// Gemini Wrapper Endpoint
app.post("/api/analyze-resume", async (req, res) => {
try {
const { resumeText, jobDescription, analysisMode } = req.body;
if (!GEMINI_API_KEY) {
console.error("GEMINI_API_KEY is not set in environment variables");
return res.status(500).json({ error: "Server configuration error: Gemini API key missing" });
}
if (!resumeText) {
return res.status(400).json({ error: "Missing resume text" });
}
let prompt = '';
if (analysisMode === 'jd') {
prompt = `
You are an expert ATS (Applicant Tracking System) and Career Coach.
Compare the following Resume text against the Job Description (JD).
Resume Text:
${resumeText}
Job Description:
${jobDescription}
Provide a detailed analysis in strictly raw JSON format (no markdown code blocks, no explanation text).
Ensure all strings are properly escaped.
The JSON structure must be:
{
"matchPercentage": number (0-100),
"summary": "string (brief overview of fit)",
"strengths": "markdown string (bullet points)",
"weaknesses": "markdown string (missing skills/experience)",
"improvements": "markdown string (concrete suggestions to improve the resume for this JD)"
}
`;
} else {
prompt = `
You are an expert Career Coach and Resume Reviewer.
Analyze the following Resume text to provide general feedback on how to improve it for a professional career.
Resume Text:
${resumeText}
Provide a detailed analysis in strictly raw JSON format (no markdown code blocks, no explanation text).
Ensure all strings are properly escaped.
The JSON structure must be:
{
"matchPercentage": number (0-100, representing overall resume quality score),
"summary": "string (brief summary of the candidate's profile)",
"strengths": "markdown string (strong points of the resume)",
"weaknesses": "markdown string (formatting issues, missing sections, unclear descriptions)",
"improvements": "markdown string (actionable tips to make the resume stand out generally)"
}
`;
}
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
const response = await fetch(`${GEMINI_API_URL}?key=${GEMINI_API_KEY}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
});
if (!response.ok) {
throw new Error(`AI Analysis failed: ${response.statusText}`);
}
const result = await response.json();
return res.json(result);
} catch (error) {
console.error("Error in /api/analyze-resume:", error);
res.status(500).json({ error: error.message || "Internal Server Error" });
}
});
// Legacy email endpoint (keep for backward compatibility)
app.get("/send-email", async (req, res) => {
try {
await transporter.sendMail({
from: "suryasunrise261@gmail.com",
to: "suryasuperman261@gmail.com",
subject: "Hello!",
text: "This is a test message.",
});
res.send("Email sent!");
} catch (error) {
res.send("Error: " + error.message);
}
});
// Get all students
app.get("/api/students", async (req, res) => {
try {
const { data, error } = await supabase
.from("users")
.select("uid, display_name, email, college, role, avatar")
.eq("role", "student")
.order("display_name", { ascending: true });
if (error) throw error;
res.json({ success: true, students: data || [] });
} catch (error) {
console.error("Error fetching students:", error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get all users (including non-students)
app.get("/api/users", async (req, res) => {
try {
const { data, error } = await supabase
.from("users")
.select("uid, display_name, email, college, role, avatar")
.order("display_name", { ascending: true });
if (error) throw error;
res.json({ success: true, users: data || [] });
} catch (error) {
console.error("Error fetching users:", error);
res.status(500).json({ success: false, error: error.message });
}
});
// Send blog email to selected recipients (via QStash in production, direct in dev)
app.post("/api/send-blog-email", async (req, res) => {
try {
const { emails, blog } = req.body;
if (!emails || !Array.isArray(emails) || emails.length === 0) {
return res.status(400).json({ success: false, error: "No recipients provided" });
}
if (!blog || !blog.title || !blog.content) {
return res.status(400).json({ success: false, error: "Invalid blog data" });
}
const isLocalDev = !process.env.VERCEL_URL && !process.env.BASE_URL;
if (isLocalDev) {
// LOCAL DEV: Send emails directly (QStash can't reach localhost)
const htmlContent = generateBlogEmailHTML(blog);
let successCount = 0;
let failedEmails = [];
for (const email of emails) {
try {
await transporter.sendMail({
from: '"CodeSapiens Blog" <suryasunrise261@gmail.com>',
to: email,
subject: `π New Blog: ${blog.title}`,
html: htmlContent,
});
successCount++;
console.log(`β
Email sent to ${email}`);
} catch (emailError) {
console.error(`Failed to send to ${email}:`, emailError.message);
failedEmails.push(email);
}
}
return res.json({
success: true,
message: `Email sent to ${successCount} of ${emails.length} recipients (local mode)`,
successCount,
failedCount: failedEmails.length,
});
}
// PRODUCTION: Queue to QStash
const baseUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: process.env.BASE_URL;
// Debug: log blog object to see available fields
console.log("π Blog object received:", JSON.stringify({ id: blog.id, title: blog.title, keys: Object.keys(blog) }));
// Since we already have the full blog, send it directly (it's small enough per email)
const queuePromises = emails.map(email =>
qstashClient.publishJSON({
url: `${baseUrl}/api/qstash-send-email`,
body: { email, blog: { id: blog.id, title: blog.title, content: blog.content, excerpt: blog.excerpt, cover_image: blog.cover_image, slug: blog.slug } },
retries: 3,
})
);
await Promise.all(queuePromises);
res.json({
success: true,
message: `Queued ${emails.length} emails for delivery`,
queuedCount: emails.length,
});
} catch (error) {
console.error("Error sending blog emails:", error);
res.status(500).json({ success: false, error: error.message });
}
});
// Send blog email to all students (via QStash in production, direct in dev)
app.post("/api/send-blog-email-all", async (req, res) => {
try {
const { blog } = req.body;
if (!blog || !blog.title || !blog.content) {
return res.status(400).json({ success: false, error: "Invalid blog data" });
}
// Fetch all student emails
const { data: students, error: fetchError } = await supabase
.from("users")
.select("email")
.eq("role", "student");
if (fetchError) throw fetchError;
if (!students || students.length === 0) {
return res.status(400).json({ success: false, error: "No students found" });
}
const emails = students.map(s => s.email).filter(Boolean);
const isLocalDev = !process.env.VERCEL_URL && !process.env.BASE_URL;
if (isLocalDev) {
// LOCAL DEV: Send emails directly (QStash can't reach localhost)
const htmlContent = generateBlogEmailHTML(blog);
let successCount = 0;
let failedEmails = [];
for (const email of emails) {
try {
await transporter.sendMail({
from: '"CodeSapiens Blog" <suryasunrise261@gmail.com>',
to: email,
subject: `π New Blog: ${blog.title}`,
html: htmlContent,
});
successCount++;
console.log(`β
Email sent to ${email}`);
} catch (emailError) {
console.error(`Failed to send to ${email}:`, emailError.message);
failedEmails.push(email);
}
}
return res.json({
success: true,
message: `Email sent to ${successCount} of ${emails.length} students (local mode)`,
successCount,
totalStudents: students.length,
failedCount: failedEmails.length,
});
}
// PRODUCTION: Queue to QStash
const baseUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: process.env.BASE_URL;
const queuePromises = emails.map(email =>
qstashClient.publishJSON({
url: `${baseUrl}/api/qstash-send-email`,
body: { email, blog: { id: blog.id, title: blog.title, content: blog.content, excerpt: blog.excerpt, cover_image: blog.cover_image, slug: blog.slug } },
retries: 3,
})
);
await Promise.all(queuePromises);
res.json({
success: true,
message: `Queued ${emails.length} emails for delivery to all students`,
queuedCount: emails.length,
totalStudents: students.length,
});
} catch (error) {
console.error("Error sending blog email to all:", error);
res.status(500).json({ success: false, error: error.message });
}
});
// Test email endpoint
app.post("/api/test-email", async (req, res) => {
try {
const { email } = req.body;
if (!email) {
return res.status(400).json({ success: false, error: "Email is required" });
}
await transporter.sendMail({
from: '"CodeSapiens" <suryasunrise261@gmail.com>',
to: email,
subject: "Test Email from CodeSapiens",
html: `
<div style="font-family: Arial, sans-serif; padding: 20px;">
<h2>π Email Configuration Working!</h2>
<p>This is a test email from the CodeSapiens Blog Email System.</p>
<p>If you received this, the email system is configured correctly.</p>
</div>
`,
});
res.json({ success: true, message: `Test email sent to ${email}` });
} catch (error) {
console.error("Test email error:", error);
res.status(500).json({ success: false, error: error.message });
}
});
// ============================================
// QSTASH WEBHOOK - Called by Upstash to send emails
// ============================================
app.post("/api/qstash-send-email", async (req, res) => {
try {
// Verify the request is from QStash (signature verification)
const signature = req.headers["upstash-signature"];
const body = JSON.stringify(req.body);
if (process.env.NODE_ENV === "production" && signature) {
const isValid = await qstashReceiver.verify({
signature,
body,
});
if (!isValid) {
console.error("Invalid QStash signature");
return res.status(401).json({ error: "Invalid signature" });
}
}
const { email, blogId, blog: blogFromBody } = req.body;
// Debug: log what we received
console.log("π¨ QStash webhook received:", JSON.stringify(req.body, null, 2));
if (!email) {
console.log("β Missing email");
return res.status(400).json({ error: "Missing email" });
}
let blog = blogFromBody;
// If blog not provided directly, fetch from Supabase using blogId
if (!blog && blogId) {
const { data: fetchedBlog, error: blogError } = await supabase
.from("blogs")
.select("*")
.eq("id", blogId)
.single();
if (blogError || !fetchedBlog) {
console.error("Failed to fetch blog:", blogError?.message);
return res.status(404).json({ error: "Blog not found" });
}
blog = fetchedBlog;
}
if (!blog || !blog.title) {
console.log("β Missing blog data");
return res.status(400).json({ error: "Missing blog data" });
}
const htmlContent = generateBlogEmailHTML(blog);
await transporter.sendMail({
from: '"CodeSapiens Blog" <suryasunrise261@gmail.com>',
to: email,
subject: `π New Blog: ${blog.title}`,
html: htmlContent,
});
console.log(`β
Email sent to ${email}`);
res.json({ success: true, message: `Email sent to ${email}` });
} catch (error) {
console.error(`β Failed to send email:`, error.message);
// Return 500 so QStash will retry
res.status(500).json({ success: false, error: error.message });
}
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));