-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
999 lines (852 loc) · 46.5 KB
/
app.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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
'use strict';
require('dotenv').config();
const pkg = require('./package.json');
const i18n = require('./src/lang/i18n.config');
const bodyParser = require('body-parser');
const express = require('express');
const session = require('express-session');
const log = require('./src/logging/');
const pg = require('pg');
const fileStore = require('session-file-store')(session);
const pgSessionStore = require('connect-pg-simple')(session);
const helmet = require('helmet');
const cors = require('cors');
const canvasApi = require('./src/api/canvas');
const db = require('./src/db');
const utils = require('./src/utilities');
const cache = require('./src/cache');
const routes = require('./src/routes');
const morgan = require('morgan');
const rfs = require('rotating-file-stream');
const path = require('path');
const ical = require('./src/ical');
const crypto = require('crypto');
const port = process.env.PORT || 3000;
const cookieMaxAge = 3600000 * 24 * 30 * 4; // 4 months
const fileStoreOptions = { ttl: 3600 * 12, retries: 3 };
const DB_PER_PAGE = 50;
// PostgreSQL Session store
const sessionOptions = {
store: new pgSessionStore({
pool: db,
tableName: "user_session",
createTableIfMissing: true
}),
name: process.env.SESSION_NAME ? process.env.SESSION_NAME : "LTI_TEST_SID",
secret: process.env.SESSION_SECRET ? process.env.SESSION_SECRET : "keyboard cat dog mouse",
resave: false,
saveUninitialized: false,
rolling: true,
cookie: { maxAge: cookieMaxAge }
};
const app = express();
app.disable('X-Powered-By');
app.set('json spaces', 2);
app.use("/assets",
express.static(__dirname + '/public/assets')
);
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(helmet({
frameguard: false
}));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Create a rotating write stream for request access logging
var accessLogStream = rfs.createStream('access.log', {
interval: '1d', // rotate daily
maxFiles: 180, // keep about six months
path: path.join(__dirname, 'logs')
});
// Setup special Morgan tokens
morgan.token('course-id', function getCourseId (req, res) {
return res.locals?.courseId ? res.locals.courseId : "-";
});
morgan.token('user-id', function getUserId (req) {
return req.session?.user?.id ? req.session.user.id : "-";
});
morgan.token('user-groups', function getUserGroups (req) {
return req.session?.user?.groups_human_readable ? req.session.user.groups_human_readable : "-";
});
// Setup https request logging
app.use(morgan(':remote-addr [:date[clf]] ":method :url" :status :res[content-length] - :course-id :user-id ":user-groups" ":response-time ms" ":referrer" ":user-agent"', { stream: accessLogStream }))
// Content Security Policy
app.use(function (req, res, next) {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' cdn.jsdelivr.net unpkg.com; style-src 'self' 'unsafe-inline' cdn.jsdelivr.net fonts.googleapis.com; font-src 'self' cdn.jsdelivr.net fonts.gstatic.com; img-src 'self' data:; frame-src 'self'" + (process.env.CSP_FRAME_SRC_ALLOW ? " " + process.env.CSP_FRAME_SRC_ALLOW : "")
);
next();
});
if (process.env.NODE_ENV === "production") {
app.set('trust proxy', 1);
sessionOptions.cookie.secure = true;
sessionOptions.cookie.sameSite = 'none';
}
// Session options
app.use(session(sessionOptions));
// set the view engine to ejs
app.set('view engine', 'ejs');
// Language with i18n
// Default: using 'accept-language' header to guess language settings
app.use(i18n.init);
// Check database version
db.checkDatabaseVersion();
// Setup all routes
app.use('/', routes);
// Debug route that will dump session, should only be possible in development
app.get('/debug', async (req, res, next) => {
if (process.env.NODE_ENV !== "production") {
return res.send({
session: req.session
});
}
else {
return res.sendStatus(404);
}
});
// Main page with available slots for user to reserve */
app.get('/', async (req, res, next) => {
try {
let availableSlots;
const per_page = DB_PER_PAGE ? DB_PER_PAGE : 25;
const offset = req.query.page ? Math.max(parseInt(req.query.page) - 1, 0) * per_page : 0;
/* Date and time handling */
const dateOptions = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };
const timeOptions = { hour: '2-digit', minute: '2-digit' };
/* Available slots, with filters applied, paginated */
availableSlots = await db.getAllSlotsPaginated(res, offset, per_page, res.locals.courseId, parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
/* Difference between valid courses to use in slots and courses used for filtering */
const filter_segments = utils.linkify(res, 'segment', await db.getSegments(res.locals.courseId), parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
const filter_courses = utils.linkify(res, 'course', await db.getValidCourses(res.locals.courseId), parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
const filter_instructors = utils.linkify(res, 'instructor', await db.getValidInstructors(res.locals.courseId), parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
const filter_locations = utils.linkify(res, 'location', await db.getValidLocations(res.locals.courseId), parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
const filter_availability = utils.linkify(res, 'availability', [ { id: 1, name: res.__('SlotListingFilterAvailabilityAll') } ], parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
const filter_date = utils.linkify(res, 'date', '', parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
let this_navigation = utils.paginate(availableSlots.records_total, per_page, req.query.page ? Math.max(parseInt(req.query.page), 1) : 1, parseInt(req.query.segment), parseInt(req.query.course), parseInt(req.query.instructor), parseInt(req.query.location), parseInt(req.query.availability), req.query.start_date, req.query.end_date);
this_navigation.filters = {
segment: filter_segments,
course: filter_courses,
instructor: filter_instructors,
location: filter_locations,
availability: filter_availability,
date: filter_date
};
this_navigation.filters_active = 0;
if (this_navigation.filters.segment.some(x => x.active == true && x.id != null)) {
this_navigation.filters_active++;
}
if (this_navigation.filters.course.some(x => x.active == true && x.id != null)) {
this_navigation.filters_active++;
}
if (this_navigation.filters.instructor.some(x => x.active == true && x.id != null)) {
this_navigation.filters_active++;
}
if (this_navigation.filters.location.some(x => x.active == true && x.id != null)) {
this_navigation.filters_active++;
}
if (this_navigation.filters.availability.some(x => x.active == true && x.id != null)) {
this_navigation.filters_active++;
}
if (this_navigation.filters.date.start_date !== undefined || this_navigation.filters.date.end_date !== undefined) {
this_navigation.filters_active++;
}
if (req.session.user.db_id != null && !isNaN(parseInt(req.query.instructor)) && parseInt(req.query.instructor) == req.session.user.db_id) {
this_navigation.current_page_is_instructor_slots = true;
}
else {
this_navigation.current_page_is_instructor_slots = false;
}
let this_start_date_string = res.__('DatePhraseToday');
let this_end_date_string = res.__('DatePhraseAndForward');
if (Date.parse(req.query.start_date)) {
if (new Date().toLocaleDateString('sv-SE', { year: 'numeric', month: 'numeric', day: 'numeric' }) != new Date(req.query.start_date).toLocaleDateString('sv-SE', { year: 'numeric', month: 'numeric', day: 'numeric' })) {
this_start_date_string = new Date(req.query.start_date).toLocaleDateString('sv-SE', { year: 'numeric', month: 'numeric', day: 'numeric' });
}
}
if (Date.parse(req.query.end_date)) {
if (new Date().toLocaleDateString('sv-SE', { year: 'numeric', month: 'numeric', day: 'numeric' }) != new Date(req.query.end_date).toLocaleDateString('sv-SE', { year: 'numeric', month: 'numeric', day: 'numeric' })) {
this_end_date_string = res.__('DatePhraseUntil') + " " + new Date(req.query.end_date).toLocaleDateString('sv-SE', { year: 'numeric', month: 'numeric', day: 'numeric' });
}
}
if (this_navigation.current_page_is_instructor_slots) {
this_navigation.title = res.__('SlotListingHeaderInstructor', { slots: this_navigation.records_total, from: this_start_date_string, to: this_end_date_string });
}
else {
this_navigation.title = res.__('SlotListingHeaderNormal', { slots: this_navigation.records_total, from: this_start_date_string, to: this_end_date_string });
}
/* Add contextual availability notice for each slot */
for (const slot of availableSlots.slots) {
if (slot.res_max == 1) {
if (slot.res_max == slot.res_now) {
if (slot.type == "group") {
slot.availability_notice = res.__('SlotAvailabilityPhraseOneGroupFull');
}
else {
slot.availability_notice = res.__('SlotAvailabilityPhraseOneIndividualFull');
}
}
else {
if (slot.type == "group") {
slot.availability_notice = res.__('SlotAvailabilityPhraseOneGroupAvailable');
}
else {
slot.availability_notice = res.__('SlotAvailabilityPhraseOneIndividualAvailable');
}
}
}
else {
if (slot.res_max == slot.res_now) {
if (slot.type == "group") {
slot.availability_notice = res.__('SlotAvailabilityPhraseGroupFull');
}
else {
slot.availability_notice = res.__('SlotAvailabilityPhraseIndividualFull');
}
}
else {
if (slot.type == "group") {
slot.availability_notice = res.__n('SlotAvailabilityPhraseGroupAvailable', (slot.res_max - slot.res_now), { reservations: slot.res_now, available: (slot.res_max - slot.res_now), slots: slot.res_max });
}
else {
slot.availability_notice = res.__n('SlotAvailabilityPhraseIndividualAvailable', (slot.res_max - slot.res_now), { reservations: slot.res_now, available: slot.res_max - slot.res_now, slots: slot.res_max });
}
}
}
}
/* Calculate if this slot is bookable, based on existing reservations */
/* TODO: make it more general in utilities or something! */
for (const slot of availableSlots.slots) {
slot.res_percent = Math.round((slot.res_now / slot.res_max) * 100);
if (req.session.user.isAdministrator) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationNoAdministrator');
}
else if (req.session.user.isInstructor) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationNoInstructor');
}
else {
slot.reservable_for_this_user = true;
if (slot.res_now >= slot.res_max) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationFull');
}
// DEBUG FOR AZURE AND UTC, should be removed
const t_time = new Date();
const t_time_now = t_time.getTime();
const t_time_slot = new Date(slot.time_start).getTime();
log.debug("t_time: " + t_time + " t_time_now: " + t_time_now + " slot.time_start: " + slot.time_start.toString() + " t_time_slot: " + t_time_slot + " reservable: " + !(t_time_slot <= t_time_now));
if (t_time_slot <= t_time_now) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationTimeInPast');
}
if (slot.type == "group") {
// Check if any of this user's groups are reserved on this slot
if (slot.res_group_ids && slot.res_group_ids.filter(id => req.session.user.groups_ids?.includes(id)).length) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationGroupIsReserved');
}
// Check how many times this user's groups are reserved on slots with the same course context
if (slot.res_course_group_ids && slot.reservable_for_this_user) {
if (slot.res_course_group_ids.filter(id => req.session.user.groups_ids?.includes(id)).length >= slot.course_max_per_type) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationGroupMaxReservations', { max: slot.course_max_per_type, name: slot.course_name });
}
}
}
else {
// Check if this user is reserved on this slot
if (slot.res_user_ids && slot.res_user_ids.includes(req.session.user.id)) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationIndividualIsReserved');
}
// Check how many times this user is reserved on slots with the same course context
if (slot.res_course_user_ids && slot.reservable_for_this_user) {
if (slot.res_course_user_ids.filter(id => req.session.user.id == id).length >= slot.course_max_per_type) {
slot.reservable_for_this_user = false;
slot.reservable_notice = res.__('SlotReservationIndividualMaxReservations', { max: slot.course_max_per_type, name: slot.course_name });
}
}
}
}
}
/* return res.send({
internal: req.session.internal,
session: req.session,
groups: req.session.user.groups,
navigation: this_navigation,
slots: availableSlots.slots,
segments: await db.getSegments(res.locals.courseId),
courses: await db.getValidCourses(res.locals.courseId),
instructors: await db.getValidInstructors(),
locations: await db.getValidLocations()
}); */
return res.render('pages/index', {
internal: req.session.internal,
session: req.session,
groups: req.session.user.groups,
navigation: this_navigation,
slots: availableSlots.slots,
configuration: res.locals.configuration,
segments: await db.getSegments(res.locals.courseId),
courses: await db.getValidCourses(res.locals.courseId),
instructors: await db.getValidInstructors(res.locals.courseId),
locations: await db.getValidLocations(res.locals.courseId)
});
}
catch (error) {
log.error(error);
return res.send({
success: false,
message: error.message
});
}
});
/**
* Show the user a list of reservations done, both for this user or a group the user is member of.
*/
app.get('/reservations', async (req, res, next) => {
const reservations = await db.getReservationsForUser(res, res.locals.courseId, req.session.user.id, req.session.user.groups_ids);
for (const reservation of reservations) {
// Get other reservations if this is a group and there are other groups reserved.
// For now, we store the information in database when a user for a group makes the reservation.
if (reservation.is_group == true && reservation.max_groups > 1) {
let other_reservations = await db.getSimpleSlotReservations(reservation.slot_id);
reservation.other_reservations = [];
for (const r of other_reservations) {
if (r.canvas_group_id != reservation.canvas_group_id) {
reservation.other_reservations.push(r);
}
}
}
if (reservation.id == req.query.reservationId && req.query.reservationDone == "true") {
reservation.just_created = true;
}
reservation.ics_file_name = crypto.createHash('md5').update(reservation.id.toString()).digest("hex") + ".ics";
}
/* return res.send({
status: 'up',
version: pkg.version,
session: req.session,
reservations: reservations
}); */
return res.render(res.locals.lang + '/pages/reservations/reservations', {
status: 'up',
internal: req.session.internal,
version: pkg.version,
session: req.session,
reservations: reservations,
reservationDeleted: req.query.reservationDeleted && req.query.reservationDeleted == "true",
reservationDone: req.query.reservationDone && req.query.reservationDone == "true",
reservationGroup: req.query.reservationGroup && req.query.reservationGroup == "true",
reservationTitle: req.query.reservationTitle ? req.query.reservationTitle : null
});
});
/**
* Privay Policy, linked from footer
*/
app.get('/privacy', async (req, res, next) => {
return res.render(res.locals.lang + '/pages/privacy/privacy', {
internal: req.session.internal,
session: req.session
});
});
/**
* Admin: start page
*/
app.get('/admin', async (req, res, next) => {
if (req.session.user.isAdministrator) {
return res.render('pages/admin/admin', {
status: 'up',
internal: req.session.internal,
version: pkg.version,
session: req.session
});
}
else {
next(new Error(res.__('GeneralErrorMessageMissingAdminAccess')));
}
});
/**
* Admin: Canvas connection
*/
app.get('/admin/canvas', async (req, res, next) => {
if (req.session.user.isAdministrator) {
try {
let canvas_group_categories = await canvasApi.getCourseGroupCategories(res.locals.courseId, res.locals.token);
const db_group_categories_filter = await db.getCourseGroupCategoryFilter(res.locals.courseId);
for (const c of canvas_group_categories) {
if (db_group_categories_filter.includes(c.id)) {
c.filtered_in_db = true;
}
else {
c.filtered_in_db = false;
}
}
const course_config = await db.getCanvasCourseConfiguration(res.locals.courseId);
const available_config_keys = [
{ key: 'FACETS_HIDE_SEGMENT' },
{ key: 'FACETS_HIDE_COURSE' },
{ key: 'FACETS_HIDE_INSTRUCTOR' },
{ key: 'FACETS_HIDE_LOCATION' },
{ key: 'FACETS_HIDE_AVAILABILITY' }
];
for (const k of available_config_keys) {
if (course_config.filter(c => c.key == k.key).map(c => c.value)[0] !== undefined) {
k.db_value = course_config.filter(c => c.key == k.key).map(c => c.value)[0];
}
else {
k.db_value = null;
}
}
/* return res.send({
status: 'up',
internal: req.session.internal,
version: pkg.version,
session: req.session,
data: {
canvas_course_id: res.locals.courseId,
canvas_course_name: req.session.lti.context_title,
canvas_group_categories: canvas_group_categories,
config_keys: available_config_keys,
}
}); */
return res.render('pages/admin/admin_canvas', {
status: 'up',
internal: req.session.internal,
version: pkg.version,
session: req.session,
data: {
canvas_course_id: res.locals.courseId,
canvas_course_name: req.session.lti.context_title,
canvas_group_categories: canvas_group_categories,
config_keys: available_config_keys,
}
});
}
catch (error) {
throw new Error(error);
}
}
else {
next(new Error(res.__('GeneralErrorMessageMissingAdminAccess')));
}
});
/**
* Admin: Courses (to create slots on)
*/
app.get('/admin/course', async (req, res, next) => {
if (req.session.user.isAdministrator) {
return res.render('pages/admin/admin_course', {
internal: req.session.internal,
session: req.session,
courses: await db.getAllCoursesWithStatistics(res.locals.courseId)
});
}
else {
next(new Error(res.__('GeneralErrorMessageMissingAdminAccess')));
}
});
/**
* Admin: Segments
*/
app.get('/admin/segment', async (req, res, next) => {
if (req.session.user.isAdministrator) {
return res.render('pages/admin/admin_segment', {
internal: req.session.internal,
session: req.session,
segments: await db.getSegmentsWithStatistics(res.locals.courseId)
});
}
else {
next(new Error(res.__('GeneralErrorMessageMissingAdminAccess')));
}
});
/**
* Admin: Instructors
*/
app.get('/admin/instructor', async (req, res, next) => {
if (req.session.user.isAdministrator) {
let course_instructors = await db.getInstructorsWithStatistics(res.locals.courseId);
return res.render('pages/admin/admin_instructor', {
internal: req.session.internal,
session: req.session,
instructors: course_instructors
});
}
else {
next(new Error(res.__('GeneralErrorMessageMissingAdminAccess')));
}
});
/**
* Admin: Locations
*/
app.get('/admin/location', async (req, res, next) => {
if (req.session.user.isAdministrator) {
return res.render('pages/admin/admin_location', {
internal: req.session.internal,
session: req.session,
locations: await db.getLocationsWithStatistics(res.locals.courseId)
});
}
else {
next(new Error(res.__('GeneralErrorMessageMissingAdminAccess')));
}
});
/**
* Admin: Exports (data exports)
*/
app.get('/admin/exports', async (req, res, next) => {
if (req.session.user.isAdministrator) {
return res.render('pages/admin/admin_exports', {
internal: req.session.internal,
session: req.session,
data: {
canvas_course_id: res.locals.courseId,
canvas_course_name: req.session.lti.context_title
}
});
}
else {
next(new Error(res.__('GeneralErrorMessageMissingAdminAccess')));
}
});
/* ===================== */
/* API Endpoints, public */
/* ===================== */
/* Get one slot */
app.get('/api/slot/:id', async (req, res, next) => {
try {
const slot = await db.getSlot(res, req.params.id)
// add info about reserved groups, needed for UI
// don't leak user information on individuals, not used
if (slot.type != 'individual') {
slot.reservations = await db.getSimpleSlotReservations(req.params.id);
}
else {
delete slot.res_user_ids;
delete slot.res_course_user_ids;
delete slot.res_group_ids;
delete slot.res_group_names;
delete slot.res_course_group_ids;
}
slot.shortcut = {
start_date: utils.getDatePart(slot.time_start),
end_date: utils.getDatePart(slot.time_end),
start_time: utils.getTimePart(slot.time_start),
end_time: utils.getTimePart(slot.time_end)
}
return res.send(slot);
}
catch (error) {
log.error(error);
return res.send({
success: false,
message: error.message
});
}
});
/**
* Reserve one slot.
* Includes logic that checks some things like max reservations, max of same type (course), already reserved.
* Sends messages to individuals, groups and cc to instructors with Conversations API and Conversations Robot.
*/
app.post('/api/reservation', async (req, res, next) => {
const { slot_id, group_id, user_id, message } = req.body;
try {
const slot = await db.getSlot(res, slot_id);
const t_time_now = new Date().getTime();
const t_time_slot = new Date(slot.time_start).getTime();
// TODO: Same code as in route for /, try to generalize
if (slot.res_now >= slot.res_max) {
throw new Error(res.__('SlotReservationFull'));
}
else if (t_time_slot <= t_time_now) {
throw new Error(res.__('SlotReservationTimeInPast'));
}
else {
if (slot.type == "group") {
// Check if any of this user's groups are reserved on this slot
if (slot.res_group_ids && slot.res_group_ids.filter(id => req.session.user.groups_ids?.includes(id)).length) {
throw new Error(res.__('SlotReservationGroupIsReserved'));
}
// Check how many times this user's groups are reserved on slots with the same course context
if (slot.res_course_group_ids && slot.reservable_for_this_user) {
if (slot.res_course_group_ids.filter(id => req.session.user.groups_ids?.includes(id)).length >= slot.course_max_per_type) {
throw new Error(res.__('SlotReservationIndividualMaxReservations', { max: slot.course_max_per_type, name: slot.course_name }));
}
}
}
else {
// Check if this user is reserved on this slot
if (slot.res_user_ids && slot.res_user_ids.includes(req.session.user.id)) {
throw new Error(res.__('SlotReservationIndividualIsReserved'));
}
// Check how many times this user is reserved on slots with the same course context
if (slot.res_course_user_ids && slot.reservable_for_this_user) {
if (slot.res_course_user_ids.filter(id => req.session.user.id == id).length >= slot.course_max_per_type) {
throw new Error(res.__('SlotReservationIndividualMaxReservations', { max: slot.course_max_per_type, name: slot.course_name }));
}
}
}
}
let group_name;
// In the form we get the group id, get the name from user's groups
if (slot.type == "group") {
for (const group of req.session.user.groups) {
if (group.id == group_id) {
group_name = group.name;
}
}
}
const reservation = await db.createSlotReservation(res, slot_id, req.session.user.id, req.session.user.name, group_id, group_name, message);
// Send confirmation messages with Canvas Conversation Robot to Inbox
log.debug("CONVERSATION_ROBOT_SEND_MESSAGES=" + process.env.CONVERSATION_ROBOT_SEND_MESSAGES);
if (process.env.CONVERSATION_ROBOT_API_TOKEN && process.env.CONVERSATION_ROBOT_SEND_MESSAGES == "true") {
try {
const course = await db.getCourse(slot.course_id);
const instructor = await db.getInstructor(slot.instructor_id);
if (slot.type == "group") {
const subject = res.__('ConversationRobotReservationSubjectPrefix') + group_name + ", " + course.name;
const subject_cc = res.__('ConversationRobotReservationCcSubjectPrefix') + group_name + ", " + course.name + " (" + req.session.user.name + ")";
const recipient = "group_" + group_id;
const template_type = "reservation_group_done";
let body = course.message_confirmation_body;
if (body === 'undefined' || body == '') {
body = utils.getTemplate(template_type);
}
if (body !== 'undefined' && body != '') {
body = utils.replaceMessageMagics(body, course.name, message, course.cancellation_policy_hours, req.session.user.name, slot.time_human_readable, slot.location_name, slot.location_url, slot.location_description, instructor.name, instructor.email, group_name, "", req.session.lti.context_title);
let conversation_result_group = await canvasApi.createConversation(recipient, subject, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id = await db.addCanvasConversationLog(slot_id, reservation.id, slot.canvas_course_id, recipient, subject, body);
log.info(`Sent confirmation message to [${recipient}] log id [${log_id.id}]`);
if (course.message_cc_instructor) {
let conversation_result_cc = await canvasApi.createConversation(instructor.canvas_user_id, subject_cc, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id_cc = await db.addCanvasConversationLog(slot_id, reservation.id, slot.canvas_course_id, instructor.canvas_user_id, subject_cc, body);
log.info(`Sent a copy of confirmation message to the instructor, log id [${log_id_cc.id}]`);
}
// Get the updated slot with all reservations
const slot_now = await db.getSlot(res, slot_id);
// Slot is full and there should be a message to all groups reserved
if (course.message_all_when_full && slot_now.res_now == slot_now.res_max) {
let recipients = new Array();
let body_all = course.message_full_body;
if (body_all === 'undefined' || body_all == '') {
body_all = utils.getTemplate("reservation_group_full");
}
if (body_all !== 'undefined' && body_all != '') {
body_all = utils.replaceMessageMagics(body_all, course.name, message, course.cancellation_policy_hours, req.session.user.name, slot_now.time_human_readable, slot_now.location_name, slot_now.location_url, slot_now.location_description, instructor.name, instructor.email, group_name, slot_now.res_group_names.join(", "), req.session.lti.context_title);
for (const id of slot_now.res_group_ids) {
recipients.push("group_" + id);
}
const subject_all = res.__('ConversationRobotReservationFullSubjectPrefix') + course.name;
const subject_all_cc = res.__('ConversationRobotReservationFullCcSubjectPrefix') + course.name + " (" + slot_now.res_group_names.join(", ") + ")";
let conversation_result_all = await canvasApi.createConversation(recipients, subject_all, body_all, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id_all = await db.addCanvasConversationLog(slot_id, null, slot_now.canvas_course_id, recipients, subject_all, body_all);
log.info(`Sent connection message to [${recipients.join(", ")}] log id [${log_id_all.id}]`);
if (course.message_cc_instructor) {
let conversation_result_all_cc = await canvasApi.createConversation(instructor.canvas_user_id, subject_all_cc, body_all, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id_all_cc = await db.addCanvasConversationLog(slot_id, null, slot.canvas_course_id, instructor.canvas_user_id, subject_all_cc, body_all);
log.info(`Sent a copy of connection message to the instructor, log id [${log_id_all_cc.id}]`);
}
}
else {
log.error("Flag 'message_all_when_full' is true, but could not find message body neither in template file 'reservation_group_full' or in db for courseId " + slot_now.course_id);
}
}
}
else {
log.error("Could not find message body neither in general template file '" + template_type + "' or in db for courseId " + slot.course_id);
}
}
else {
const subject = res.__('ConversationRobotReservationSubjectPrefix') + course.name;
const subject_cc = res.__('ConversationRobotReservationCcSubjectPrefix') + course.name + ", " + req.session.user.name;
const template_type = "reservation_individual_done";
let body = course.message_confirmation_body;
if (body === 'undefined' || body == '') {
body = utils.getTemplate(template_type);
}
if (body !== 'undefined' && body != '') {
body = utils.replaceMessageMagics(body, course.name, message, course.cancellation_policy_hours, req.session.user.name, slot.time_human_readable, slot.location_name, slot.location_url, slot.location_description, instructor.name, instructor.email, "", "", req.session.lti.context_title);
let conversation_result_user = await canvasApi.createConversation(req.session.user.id, subject, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id = await db.addCanvasConversationLog(slot_id, reservation.id, slot.canvas_course_id, req.session.user.id, subject, body);
log.info("Sent confirmation message to the user, id " + log_id.id);
if (course.message_cc_instructor) {
let conversation_result_cc = await canvasApi.createConversation(instructor.canvas_user_id, subject_cc, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id_cc = await db.addCanvasConversationLog(slot_id, reservation.id, slot.canvas_course_id, instructor.canvas_user_id, subject_cc, body);
log.info("Sent a copy of confirmation message to the instructor, id " + log_id_cc.id);
}
}
else {
log.error("Could not find message body neither in general template file '" + template_type + "' or in db for courseId " + slot.course_id);
}
}
}
catch (error) {
log.error("When sending confirmation message: " + error);
}
}
log.info("Reservation done, id " + reservation.id);
return res.send({
success: true,
message: "Tiden har bokats.",
reservation_id: reservation.id
});
}
catch (error) {
log.error(error);
return res.send({
success: false,
message: error.message
});
}
});
/* Get one reservation */
app.get('/api/reservation/:id', async (req, res, next) => {
try {
let reservation = await db.getReservation(res, req.session.user.id, req.session.user.groups_ids, req.params.id);
reservation.ics_file_name = crypto.createHash('md5').update(reservation.id.toString()).digest("hex") + ".ics";
return res.send(reservation);
}
catch (error) {
log.error(error);
return res.send({
success: false,
error: error
});
}
});
/**
* Get iCalendar entry for one specific slot reservation
*/
app.get('/api/reservation/:id/entry.ics', async (req, res, next) => {
try {
const reservation = await db.getReservation(res, req.session.user.id, req.session.user.groups_ids, req.params.id);
const ics = await ical.iCalendarEventFromReservation(reservation);
return res.contentType('text/calendar').send(ics);
}
catch (error) {
log.error(error);
return res.send({
success: false,
error: error.toString()
});
}
});
/* Delete a reservation */
app.delete('/api/reservation/:id', async (req, res) => {
try {
// Load reservation first to get attributes like is_cancelable
const reservation = await db.getReservation(res, req.session.user.id, req.session.user.groups_ids, req.params.id);
if (reservation.is_cancelable == false) {
throw new Error(res.__('CancelSlotReservationApiResponseNotCancellable'));
}
await db.deleteReservation(req.session.user.id, req.session.user.groups_ids, req.params.id);
// Send confirmation messages with Canvas Conversation Robot to Inbox
log.debug("CONVERSATION_ROBOT_SEND_MESSAGES=" + process.env.CONVERSATION_ROBOT_SEND_MESSAGES);
if (process.env.CONVERSATION_ROBOT_API_TOKEN && process.env.CONVERSATION_ROBOT_SEND_MESSAGES == "true") {
try {
const course = await db.getCourse(reservation.course_id);
const instructor = await db.getInstructor(reservation.instructor_id);
if (reservation.type == "group") {
const subject = res.__('ConversationRobotCancelReservationSubjectPrefix') + reservation.canvas_group_name + ", " + course.name;
const subject_cc = res.__('ConversationRobotCancelReservationCcSubjectPrefix') + reservation.canvas_group_name + ", " + course.name + " (" + req.session.user.name + ")";
const recipient = "group_" + reservation.canvas_group_id;
const template_type = "reservation_group_canceled";
let body = course.message_cancelled_body;
if (body === 'undefined' || body == '') {
body = utils.getTemplate(template_type);
}
if (body !== 'undefined' && body != '') {
body = utils.replaceMessageMagics(body, course.name, "", course.cancellation_policy_hours, req.session.user.name, reservation.time_human_readable, reservation.location_name, "", "", instructor.name, instructor.email, reservation.canvas_group_name, "", req.session.lti.context_title);
let conversation_result_group = await canvasApi.createConversation(recipient, subject, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id = await db.addCanvasConversationLog(reservation.slot_id, reservation.id, reservation.canvas_course_id, recipient, subject, body);
log.info("Sent confirmation message of deleted reservation to the group, log id " + log_id.id);
if (course.message_cc_instructor) {
let conversation_result_cc = await canvasApi.createConversation(instructor.canvas_user_id, subject_cc, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id_cc = await db.addCanvasConversationLog(reservation.slot_id, reservation.id, reservation.canvas_course_id, instructor.canvas_user_id, subject_cc, body);
log.info("Sent a copy of confirmation message of deleted reservation to the instructor, log id " + log_id_cc.id);
}
}
else {
log.error("Could not find message body neither in general template file '" + template_type + "' or in db for courseId " + reservation.course_id);
}
}
else {
const subject = res.__('ConversationRobotCancelReservationSubjectPrefix') + course.name;
const subject_cc = res.__('ConversationRobotCancelReservationCcSubjectPrefix') + course.name + ", " + req.session.user.name;
const template_type = "reservation_individual_canceled";
let body = course.message_cancelled_body;
if (body === 'undefined' || body == '') {
body = utils.getTemplate(template_type);
}
if (body !== 'undefined' && body != '') {
body = utils.replaceMessageMagics(body, course.name, "", course.cancellation_policy_hours, req.session.user.name, reservation.time_human_readable, reservation.location_name, "", "", instructor.name, instructor.email, "", "", req.session.lti.context_title);
let conversation_result_user = await canvasApi.createConversation(req.session.user.id, subject, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id = await db.addCanvasConversationLog(reservation.slot_id, reservation.id, reservation.canvas_course_id, req.session.user.id, subject, body);
log.info("Sent confirmation message of deleted reservation to the user, log id " + log_id.id);
if (course.message_cc_instructor) {
let conversation_result_cc = await canvasApi.createConversation(instructor.canvas_user_id, subject_cc, body, { token_type: "Bearer", access_token: process.env.CONVERSATION_ROBOT_API_TOKEN });
let log_id_cc = await db.addCanvasConversationLog(reservation.slot_id, reservation.id, reservation.canvas_course_id, instructor.canvas_user_id, subject_cc, body);
log.info("Sent a copy of confirmation message of deleted reservation to the instructor, log id " + log_id_cc.id);
}
}
else {
log.error("Could not find message body neither in general template file '" + template_type + "' or in db for courseId " + reservation.course_id);
}
}
}
catch (error) {
log.error("When sending confirmation message for deleted reservation: " + error);
}
}
log.info("Reservation deleted, id " + req.params.id);
return res.send({
success: true,
message: 'Reservation was deleted.',
reservation_id: req.params.id
});
}
catch (error) {
log.error(error);
return res.send({
success: false,
message: error.message
});
}
});
/**
* Get some statistics used in web view
*/
app.get('/api/statistics', async (req, res, next) => {
try {
const reservations = await db.getReservationsForUser(res, res.locals.courseId, req.session.user.id, req.session.user.groups_ids);
return res.send({
counters: {
reservations_upcoming: reservations.filter(x => !x.is_passed).length,
reservations_total: reservations.length
}
});
}
catch (error) {
log.error(error);
return res.send({
success: false,
error: error
});
}
});
// This will only be logged in non-production
log.debug("This is not a production environment.");
/* Set server to listen and start working! */
app.listen(port, () => log.info(`Application listening on port ${port}.`));
/* Catch uncaught exceptions */
process.on('uncaughtException', (err) => {
log.error("Uncaught exception!", err);
console.error("Uncaught exception!", err);
process.exit(1); //mandatory (as per the Node docs)
});