-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
95 lines (76 loc) · 2.49 KB
/
server.js
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
const getAiText = require("./ai.js");
const cors = require("cors");
const sgMail = require("@sendgrid/mail");
const express = require("express");
const app = express();
app.use(
cors({
origin: "https://syllasync-frontend-email.onrender.com",
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type"],
})
);
const PORT = 3000;
app.use(express.json());
app.post("/aiResponse", async (req, res) => {
console.log("Getting as response");
try {
const pdfText = req.body.text;
if (!pdfText) {
res.status(400).json({ error: "Please provide text." });
}
const joke = await getAiText(pdfText);
res.json({ joke });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const generateCombinedICS = (events) => {
const formatDate = (date) => {
return date.toISOString().replace(/[-:]/g, "").split(".")[0];
};
let icsContent = `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//YourCompany//NONSGML v1.0//EN`;
events.forEach((event, index) => {
const { subject, start, end, description } = event;
const startDate = new Date(start);
const endDate = new Date(end);
icsContent += `\r\nBEGIN:VEVENT\r\nUID:${new Date().getTime()}-${index}@yourdomain.com\r\nDTSTAMP:${formatDate(
new Date()
)}\r\nDTSTART:${formatDate(startDate)}\r\nDTEND:${formatDate(
endDate
)}\r\nSUMMARY:${subject}\r\nDESCRIPTION:${
description || ""
}\r\nLOCATION:Online\r\nEND:VEVENT`;
});
icsContent += `\r\nEND:VCALENDAR`;
return icsContent;
};
app.post("/send-events", async (req, res) => {
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const { events, recipientEmail } = req.body;
try {
const icsContent = generateCombinedICS(events);
const msg = {
to: recipientEmail,
from: "quinnwebster@uvic.ca",
subject: "Your Syllabus Events - Add to Calendar",
text: "We have your syllabus events! Click the attachment to add them all to your calendar.",
attachments: [
{
content: Buffer.from(icsContent).toString("base64"),
filename: "events.ics",
type: "text/calendar",
disposition: "attachment",
},
],
};
await sgMail.send(msg);
res.status(200).json({ message: "Events sent successfully!" });
} catch (error) {
console.error("Error sending email:", error);
res.status(500).json({ error: "Failed to send events" });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});