-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
512 lines (409 loc) · 17.8 KB
/
Copy pathmain.js
File metadata and controls
512 lines (409 loc) · 17.8 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
// IMPORTS & SETUP
const express = require("express");
const app = express();
const crypto = require("crypto");
const fs = require("fs").promises;
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const { encrypt, decrypt } = require("./utils/crypto");
require("dotenv").config();
app.use(express.json());
app.use("/node_modules", express.static("node_modules"));
app.use(express.static("frontend"));
// HELPERS
function genId() {
return crypto.randomBytes(4).toString("hex");
}
function requireAuth(req, res, next) {
if (process.env.NODE_ENV === "development") {
req.userEmail = process.env.DEV_USER_EMAIL || "jake@example.com";
return next();
}
const userEmail = req.headers["x-forwarded-email"];
if (!userEmail) return res.status(401).json({ error: "Unauthorized" });
req.userEmail = userEmail;
next();
}
async function getUser(userEmail) {
const indexPath = path.join(__dirname, "userdata", "index.json");
let index = {};
try {
const data = await fs.readFile(indexPath, "utf8");
index = JSON.parse(data);
} catch (err) {
index = {};
}
if (!index[userEmail]) {
await initUser(userEmail);
const data = await fs.readFile(indexPath, "utf8");
index = JSON.parse(data);
}
return index[userEmail];
}
async function initUser(userEmail) {
const indexPath = path.join(__dirname, "userdata", "index.json");
let index = {};
try {
const data = await fs.readFile(indexPath, "utf8");
index = JSON.parse(data);
} catch (err) {
index = {};
}
const userId = uuidv4();
index[userEmail] = userId;
await fs.writeFile(indexPath, JSON.stringify(index, null, 2), "utf8");
const userFolder = path.join(__dirname, "userdata", userId);
await fs.mkdir(userFolder, { recursive: true });
const integrationsFolder = path.join(userFolder, "integrations");
await fs.mkdir(integrationsFolder, { recursive: true });
await fs.writeFile(path.join(integrationsFolder, "canvas.json"), JSON.stringify({}, null, 2), "utf8");
await fs.writeFile(path.join(userFolder, "tasks.json"), JSON.stringify([], null, 2), "utf8");
await fs.writeFile(path.join(userFolder, "guides.json"), JSON.stringify([], null, 2), "utf8");
await fs.writeFile(
path.join(userFolder, "settings.json"),
JSON.stringify(
{
email: userEmail,
nickname: "Clutter User",
theme: "light",
defaultFilters: {
undone: true,
done: false,
canvas: true,
clutter: true,
},
canvas: {
url: "",
apiKey: "",
iv: "",
},
},
null,
2,
),
"utf8",
);
return userId;
}
app.use("/api/userdata", requireAuth);
// SETTINGS API
app.post("/api/userdata/getUserId", async (req, res) => {
const userId = await getUser(req.userEmail);
res.json({ userId });
});
app.get("/api/userdata/settings", async (req, res) => {
try {
const userId = await getUser(req.userEmail);
const settingsPath = path.join(__dirname, "userdata", userId, "settings.json");
const prefs = JSON.parse(await fs.readFile(settingsPath, "utf8"));
const key = Buffer.from(process.env.ENCRYPTION_KEY, "hex");
let canvasAPIKey = "";
if (prefs.canvas.apiKey) {
canvasAPIKey = decrypt(prefs.canvas.apiKey, prefs.canvas.iv, key);
}
const canvasURL = prefs.canvas.url;
res.json({ ...prefs, canvas: { url: canvasURL, apiKey: canvasAPIKey } });
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
});
app.patch("/api/userdata/settings", async (req, res) => {
try {
const userId = await getUser(req.userEmail);
const settingsPath = path.join(__dirname, "userdata", userId, "settings.json");
const prefs = JSON.parse(await fs.readFile(settingsPath, "utf8"));
if (req.body.canvas?.apiKey) {
const key = Buffer.from(process.env.ENCRYPTION_KEY, "hex");
const { encrypted, iv } = encrypt(req.body.canvas.apiKey, key);
req.body.canvas.apiKey = encrypted;
req.body.canvas.iv = iv;
}
const newPrefs = {
...prefs,
...req.body,
canvas: { ...prefs.canvas, ...req.body.canvas },
defaultFilters: { ...prefs.defaultFilters, ...req.body.defaultFilters },
};
await fs.writeFile(settingsPath, JSON.stringify(newPrefs, null, 2), "utf8");
res.json({ status: "ok" });
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
});
// TASKS API
app.get("/api/userdata/tasks", async (req, res) => {
const userId = await getUser(req.userEmail);
const tasksPath = path.join(__dirname, "userdata", userId, "tasks.json");
const tasks = JSON.parse(await fs.readFile(tasksPath, "utf8"));
res.json(tasks);
});
app.post("/api/userdata/tasks", async (req, res) => {
const userId = await getUser(req.userEmail);
const tasksPath = path.join(__dirname, "userdata", userId, "tasks.json");
const tasks = JSON.parse(await fs.readFile(tasksPath, "utf8"));
const newTask = {
id: genId(),
title: req.body.title || "",
done: req.body.done || false,
due: req.body.due || null,
partial: false,
partialCurrent: 0,
partialTotal: 0,
};
tasks.push(newTask);
await fs.writeFile(tasksPath, JSON.stringify(tasks, null, 2), "utf8");
res.json({ status: "ok", id: newTask.id });
});
app.patch("/api/userdata/tasks/:id", async (req, res) => {
const userId = await getUser(req.userEmail);
const tasksPath = path.join(__dirname, "userdata", userId, "tasks.json");
const tasks = JSON.parse(await fs.readFile(tasksPath, "utf8"));
const taskIndex = tasks.findIndex((t) => t.id === req.params.id);
if (taskIndex === -1) return res.status(404).json({ error: "Task not found" });
tasks[taskIndex] = { ...tasks[taskIndex], ...req.body };
await fs.writeFile(tasksPath, JSON.stringify(tasks, null, 2), "utf8");
res.json({ status: "ok" });
});
app.delete("/api/userdata/tasks/:id", async (req, res) => {
const userId = await getUser(req.userEmail);
const tasksPath = path.join(__dirname, "userdata", userId, "tasks.json");
const tasks = JSON.parse(await fs.readFile(tasksPath, "utf8"));
const taskIndex = tasks.findIndex((t) => t.id === req.params.id);
if (taskIndex === -1) return res.status(404).json({ error: "Task not found" });
const updatedTasks = tasks.filter((t) => t.id !== req.params.id);
await fs.writeFile(tasksPath, JSON.stringify(updatedTasks, null, 2), "utf8");
res.json({ status: "ok" });
});
// GUIDES API
app.patch("/api/userdata/guides/reorder", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const reordered = req.body.map((id) => guides.find((g) => g.id === id));
await fs.writeFile(guidesPath, JSON.stringify(reordered, null, 2), "utf8");
res.json({ status: "ok" });
});
app.get("/api/userdata/guides", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
res.json(guides);
});
app.post("/api/userdata/guides", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const newGuide = {
id: genId(),
title: "",
archived: false,
milestones: [],
};
guides.push(newGuide);
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok", id: newGuide.id });
});
app.patch("/api/userdata/guides/:id", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((t) => t.id === req.params.id);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const allowedFields = ["title", "archived"];
const hasInvalidFields = Object.keys(req.body).some((key) => !allowedFields.includes(key));
if (hasInvalidFields) return res.status(400).json({ error: "Invalid fields" });
guides[guideIndex] = { ...guides[guideIndex], ...req.body };
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
app.delete("/api/userdata/guides/:id", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((t) => t.id === req.params.id);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const updatedGuides = guides.filter((t) => t.id !== req.params.id);
await fs.writeFile(guidesPath, JSON.stringify(updatedGuides, null, 2), "utf8");
res.json({ status: "ok" });
});
// guide milestone apis
app.patch("/api/userdata/guides/:gid/milestones/reorder", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((g) => g.id === req.params.gid);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const guide = guides[guideIndex];
const reordered = req.body.map((id) => guide.milestones.find((g) => g.id === id));
guide.milestones = reordered;
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
app.post("/api/userdata/guides/:id/milestones", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((t) => t.id === req.params.id);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const newMS = {
id: genId(),
title: "",
tasks: [],
};
guides[guideIndex].milestones.push(newMS);
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok", id: newMS.id });
});
app.patch("/api/userdata/guides/:gid/milestones/:msid", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((g) => g.id === req.params.gid);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const guide = guides[guideIndex];
const msIndex = guide.milestones.findIndex((m) => m.id === req.params.msid);
if (msIndex === -1) return res.status(404).json({ error: "Milestone not found" });
const newMS = { ...guide.milestones[msIndex], ...req.body };
guides[guideIndex].milestones[msIndex] = newMS;
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
app.delete("/api/userdata/guides/:gid/milestones/:msid", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((g) => g.id === req.params.gid);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const guide = guides[guideIndex];
const msIndex = guide.milestones.findIndex((m) => m.id === req.params.msid);
if (msIndex === -1) return res.status(404).json({ error: "Milestone not found" });
guide.milestones = guide.milestones.filter((m) => m.id !== req.params.msid);
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
// guide task apis
app.patch("/api/userdata/guides/:gid/milestones/:msid/tasks/reorder", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((g) => g.id === req.params.gid);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const guide = guides[guideIndex];
const msIndex = guide.milestones.findIndex((m) => m.id === req.params.msid);
if (msIndex === -1) return res.status(404).json({ error: "Milestone not found" });
const ms = guide.milestones[msIndex];
const reordered = req.body.map((id) => ms.tasks.find((g) => g.id === id));
guide.milestones[msIndex].tasks = reordered;
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
app.post("/api/userdata/guides/:gid/milestones/:msid/tasks", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((g) => g.id === req.params.gid);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const guide = guides[guideIndex];
const msIndex = guide.milestones.findIndex((m) => m.id === req.params.msid);
if (msIndex === -1) return res.status(404).json({ error: "Milestone not found" });
const ms = guide.milestones[msIndex];
const newTask = {
id: genId(),
title: req.body.title || "",
done: req.body.done || false,
due: req.body.due || null,
partial: false,
partialCurrent: 0,
partialTotal: 0,
};
guides[guideIndex].milestones[msIndex].tasks.push(newTask);
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
app.patch("/api/userdata/guides/:gid/milestones/:msid/tasks/:tid", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((g) => g.id === req.params.gid);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const guide = guides[guideIndex];
const msIndex = guide.milestones.findIndex((m) => m.id === req.params.msid);
if (msIndex === -1) return res.status(404).json({ error: "Milestone not found" });
const ms = guide.milestones[msIndex];
const taskIndex = ms.tasks.findIndex((s) => s.id === req.params.tid);
if (taskIndex === -1) return res.status(404).json({ error: "Task not found" });
const newTask = { ...guide.milestones[msIndex].tasks[taskIndex], ...req.body };
guides[guideIndex].milestones[msIndex].tasks[taskIndex] = newTask;
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
app.delete("/api/userdata/guides/:gid/milestones/:msid/tasks/:tid", async (req, res) => {
const userId = await getUser(req.userEmail);
const guidesPath = path.join(__dirname, "userdata", userId, "guides.json");
const guides = JSON.parse(await fs.readFile(guidesPath, "utf8"));
const guideIndex = guides.findIndex((g) => g.id === req.params.gid);
if (guideIndex === -1) return res.status(404).json({ error: "Guide not found" });
const guide = guides[guideIndex];
const msIndex = guide.milestones.findIndex((m) => m.id === req.params.msid);
if (msIndex === -1) return res.status(404).json({ error: "Milestone not found" });
const ms = guide.milestones[msIndex];
const taskIndex = ms.tasks.findIndex((s) => s.id === req.params.tid);
if (taskIndex === -1) return res.status(404).json({ error: "Task not found" });
guide.milestones[msIndex].tasks = guide.milestones[msIndex].tasks.filter((t) => t.id !== req.params.tid);
await fs.writeFile(guidesPath, JSON.stringify(guides, null, 2), "utf8");
res.json({ status: "ok" });
});
// canvas integration
app.post("/api/integrations/canvas/sync", requireAuth, async (req, res) => {
console.log("Canvas Sync Request initiated");
const userId = await getUser(req.userEmail);
const settingsPath = path.join(__dirname, "userdata", userId, "settings.json");
const prefs = JSON.parse(await fs.readFile(settingsPath, "utf8"));
const key = Buffer.from(process.env.ENCRYPTION_KEY, "hex");
const canvasUrl = prefs.canvas.url;
let canvasAPIKey = "";
if (prefs.canvas.apiKey) {
canvasAPIKey = await decrypt(prefs.canvas.apiKey, prefs.canvas.iv, key);
} else {
console.log("no canvas api key found in user prefs");
return res.status(401).json({ error: "No valid Canvas API Key found in user settings. Please set an API Key." });
}
console.log("Got Canvas URL:", canvasUrl);
const courseData = await fetch(`${canvasUrl}/api/v1/courses`, {
method: "GET",
headers: {
Authorization: `Bearer ${canvasAPIKey}`,
},
});
const courseList = await courseData.json();
const allTasks = [];
for (let course of courseList) {
if (!course.id) continue;
const courseTaskDat = await fetch(`${canvasUrl}/api/v1/courses/${course.id}/assignments`, {
method: "GET",
headers: {
Authorization: `Bearer ${canvasAPIKey}`,
},
});
const assignments = await courseTaskDat.json();
if (Array.isArray(assignments)) {
for (let assignment of assignments) {
allTasks.push({
name: assignment.name,
id: assignment.id,
due: assignment.due_at,
done: assignment.has_submitted_submissions,
link: assignment.html_url,
courseName: course.name,
});
}
}
}
return res.json(allTasks);
});
// START
app.listen(4000, () => {
console.log("Server running on port 4000");
});